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
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/LauncherWindow.java
[ { "identifier": "GenericWindow", "path": "app/src/main/java/net/lonelytransistor/launcher/generics/GenericWindow.java", "snippet": "public class GenericWindow {\n private static final String TAG = \"GenericWindow\";\n\n private static final int FADE_DURATION = 500;\n\n private static WindowMana...
import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.media.tv.TvContract; import android.media.tv.TvInputInfo; import android.media.tv.TvInputManager; import android.media.tv.TvView; import android.provider.Settings; import android.view.KeyEvent; import android.view.View; import net.lonelytransistor.launcher.generics.GenericWindow; import net.lonelytransistor.launcher.repos.ApkRepo; import net.lonelytransistor.launcher.repos.JustWatch; import net.lonelytransistor.launcher.repos.MovieRepo; import net.lonelytransistor.launcher.repos.MovieTitle; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor;
15,625
package net.lonelytransistor.launcher; @SuppressLint("RestrictedApi") public class LauncherWindow extends GenericWindow { private static final String TAG = "LauncherWindow"; private final Executor executor; private final View.OnKeyListener mKeyListener = (v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ESCAPE: hide(); return true; } } return false; }; private static final String INPUTS_ROW = "INPUTS_ROW"; private static final String RESUME_ROW = "RESUME_ROW"; private static final String POPULAR_MOVIES_ROW = "POPULAR_MOVIES_ROW"; private static final String POPULAR_SERIES_ROW = "POPULAR_SERIES_ROW"; private static final String OTHER_APPS_ROW = "OTHER_APPS_ROW"; private static final String SETTINGS_ROW = "SETTINGS_ROW"; private final Map<String, Integer> rows = new HashMap<>(); private final Map<String, Long> timestamps = new HashMap<>(); private final LauncherBar launcherBar; private final WidgetBar widgetBar; public LauncherWindow(Context ctx) { super(ctx, R.layout.activity_launcher_new); widgetBar = (WidgetBar) findViewById(R.id.widget_bar); launcherBar = (LauncherBar) findViewById(R.id.launcher_bar); getView().setOnKeyListener(mKeyListener); launcherBar.setOnKeyListener(mKeyListener); launcherBar.setOnClickListener(v -> hide()); executor = ctx.getMainExecutor(); int row; row = launcherBar.addRow(new BadgeCard("", "Select\nInput", R.drawable.icon_input, 0xFFFFFFFF,0xFF229C8F,null)); rows.put(INPUTS_ROW, row); timestamps.put(INPUTS_ROW, System.currentTimeMillis()); { TvInputManager inputManager = (TvInputManager) ctx.getSystemService(Context.TV_INPUT_SERVICE); TvView tvView = new TvView(ctx); for (TvInputInfo inputInfo : inputManager.getTvInputList()) { String id = inputInfo.getId(); int state = inputManager.getInputState(id); Drawable img = inputInfo.loadIcon(ctx); if (state != TvInputManager.INPUT_STATE_DISCONNECTED &&
package net.lonelytransistor.launcher; @SuppressLint("RestrictedApi") public class LauncherWindow extends GenericWindow { private static final String TAG = "LauncherWindow"; private final Executor executor; private final View.OnKeyListener mKeyListener = (v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ESCAPE: hide(); return true; } } return false; }; private static final String INPUTS_ROW = "INPUTS_ROW"; private static final String RESUME_ROW = "RESUME_ROW"; private static final String POPULAR_MOVIES_ROW = "POPULAR_MOVIES_ROW"; private static final String POPULAR_SERIES_ROW = "POPULAR_SERIES_ROW"; private static final String OTHER_APPS_ROW = "OTHER_APPS_ROW"; private static final String SETTINGS_ROW = "SETTINGS_ROW"; private final Map<String, Integer> rows = new HashMap<>(); private final Map<String, Long> timestamps = new HashMap<>(); private final LauncherBar launcherBar; private final WidgetBar widgetBar; public LauncherWindow(Context ctx) { super(ctx, R.layout.activity_launcher_new); widgetBar = (WidgetBar) findViewById(R.id.widget_bar); launcherBar = (LauncherBar) findViewById(R.id.launcher_bar); getView().setOnKeyListener(mKeyListener); launcherBar.setOnKeyListener(mKeyListener); launcherBar.setOnClickListener(v -> hide()); executor = ctx.getMainExecutor(); int row; row = launcherBar.addRow(new BadgeCard("", "Select\nInput", R.drawable.icon_input, 0xFFFFFFFF,0xFF229C8F,null)); rows.put(INPUTS_ROW, row); timestamps.put(INPUTS_ROW, System.currentTimeMillis()); { TvInputManager inputManager = (TvInputManager) ctx.getSystemService(Context.TV_INPUT_SERVICE); TvView tvView = new TvView(ctx); for (TvInputInfo inputInfo : inputManager.getTvInputList()) { String id = inputInfo.getId(); int state = inputManager.getInputState(id); Drawable img = inputInfo.loadIcon(ctx); if (state != TvInputManager.INPUT_STATE_DISCONNECTED &&
ApkRepo.isSystemApp(inputInfo.getServiceInfo().packageName) &&
1
2023-12-28 18:24:12+00:00
24k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/controller/ClickController.java
[ { "identifier": "Main", "path": "CS109_2022_Fall/Chess/Main.java", "snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素...
import Chess.Main; import Chess.chessComponent.SquareComponent; import Chess.model.ChessColor; import Chess.view.ChessGameFrame; import Chess.view.Chessboard; import javax.swing.*;
17,243
package Chess.controller; public class ClickController { private final Chessboard chessboard; private SquareComponent first; public ClickController(Chessboard chessboard) { this.chessboard = chessboard; } private int count = 0; public void onClick(SquareComponent squareComponent) {
package Chess.controller; public class ClickController { private final Chessboard chessboard; private SquareComponent first; public ClickController(Chessboard chessboard) { this.chessboard = chessboard; } private int count = 0; public void onClick(SquareComponent squareComponent) {
Main.playNotifyMusic("click");
0
2023-12-31 05:50:13+00:00
24k
psobiech/opengr8on
lib/src/main/java/pl/psobiech/opengr8on/client/CLUClient.java
[ { "identifier": "LuaScriptCommand", "path": "lib/src/main/java/pl/psobiech/opengr8on/client/commands/LuaScriptCommand.java", "snippet": "public class LuaScriptCommand {\n public static final String CHECK_ALIVE = \"checkAlive()\";\n\n private static final int IP_ADDRESS_PART = 1;\n\n private sta...
import java.io.Closeable; import java.io.IOException; import java.net.Inet4Address; import java.nio.file.Path; import java.time.Duration; import java.util.Objects; import java.util.Optional; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.psobiech.opengr8on.client.commands.LuaScriptCommand; import pl.psobiech.opengr8on.client.commands.ResetCommand; import pl.psobiech.opengr8on.client.commands.ResetCommand.Response; import pl.psobiech.opengr8on.client.commands.SetIpCommand; import pl.psobiech.opengr8on.client.commands.SetKeyCommand; import pl.psobiech.opengr8on.client.commands.StartTFTPdCommand; import pl.psobiech.opengr8on.client.device.CLUDevice; import pl.psobiech.opengr8on.client.device.CipherTypeEnum; import pl.psobiech.opengr8on.exceptions.UnexpectedException; import pl.psobiech.opengr8on.tftp.TFTPClient; import pl.psobiech.opengr8on.tftp.TFTPTransferMode; import pl.psobiech.opengr8on.tftp.exceptions.TFTPPacketException; import pl.psobiech.opengr8on.tftp.packets.TFTPErrorType; import pl.psobiech.opengr8on.util.FileUtil; import pl.psobiech.opengr8on.util.HexUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.RandomUtil; import pl.psobiech.opengr8on.util.SocketUtil; import pl.psobiech.opengr8on.util.SocketUtil.Payload; import pl.psobiech.opengr8on.util.Util;
16,928
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class CLUClient extends Client implements Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(CLUClient.class);
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class CLUClient extends Client implements Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(CLUClient.class);
private static final Duration DEFAULT_TIMEOUT_DURATION = Duration.ofMillis(SocketUtil.DEFAULT_TIMEOUT);
17
2023-12-23 09:56:14+00:00
24k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/renderer/RendererUtilitiesTest.java
[ { "identifier": "DomainOrder", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/DomainOrder.java", "snippet": "public final class DomainOrder implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 4902774943512072627L;\r\n\r\n /** No ord...
import static org.junit.Assert.assertEquals; import org.jfree.data.DomainOrder; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.junit.Test;
20,437
assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 3, 1.0, 2.2)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 2.0, 3.3)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 3.0, 4.4)); // check a series with four items d.addSeries("S5", new double[][] {{1.0, 2.0, 3.0, 4.0}, {9.9, 9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 1.1)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 4, 1.0, 2.2)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 4, 2.0, 3.3)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 3.0, 4.4)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 4.0, 5.5)); // check a series with repeating items d.addSeries("S5", new double[][] {{1.0, 2.0, 2.0, 2.0, 3.0}, {9.9, 9.9, 9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 1.0)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 2.0)); assertEquals(4, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 3.0)); assertEquals(4, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 4.0)); } /** * Some checks for the findLiveItemsUpperBound() method when the dataset is * DESCENDING. */ @Test public void testFindLiveItemsUpperBound_Descending() { DefaultXYDataset d = new DefaultXYDataset() { @Override public DomainOrder getDomainOrder() { // we're doing this for testing only, and make sure that we // only add data in descending order by x-value return DomainOrder.DESCENDING; } }; // check a series with no items d.addSeries("S1", new double[][] {{}, {}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 0, 10.0, 11.0)); // check a series with one item d.addSeries("S2", new double[][] {{1.0}, {9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 1, 0.0, 1.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 1, 1.1, 2.0)); // check a series with two items d.addSeries("S3", new double[][] {{2.0, 1.0}, {9.9, 9.9}}); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 2, 0.1, 0.5)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 2, 0.1, 1.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 2, 1.1, 2.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 2, 2.2, 3.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 2, 3.3, 4.0)); // check a series with three items d.addSeries("S4", new double[][] {{3.0, 2.0, 1.0}, {9.9, 9.9, 9.9}}); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 0.0, 1.0)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 1.0, 2.0)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 3, 2.0, 3.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 3, 3.0, 4.0)); // check a series with four items d.addSeries("S5", new double[][] {{4.0, 3.0, 2.0, 1.0}, {9.9, 9.9, 9.9, 9.9}}); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.1, 0.5)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.1, 1.0)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 4, 1.1, 2.0)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 4, 2.2, 3.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 4, 3.3, 4.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 4, 4.4, 5.0)); // check a series with repeating items d.addSeries("S6", new double[][] {{3.0, 2.0, 2.0, 2.0, 1.0}, {9.9, 9.9, 9.9, 9.9, 9.9}}); assertEquals(4, RendererUtilities.findLiveItemsUpperBound(d, 5, 0.0, 5.0)); assertEquals(4, RendererUtilities.findLiveItemsUpperBound(d, 5, 1.0, 5.0)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 5, 2.0, 5.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 5, 3.0, 5.0)); } /** * Checks the bounds calculation for a series where the x-ordering is not * known. See bug 3561093. */ @Test public void test3561093() {
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------------- * RendererUtilitiesTest.java * -------------------------- * (C) Copyright 2007-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 19-Apr-2007 : Version 1 (DG); * 23-Aug-2012 : Added test3561093() (DG); * */ package org.jfree.chart.renderer; /** * Some checks for the {@link RendererUtilities} class. */ public class RendererUtilitiesTest { /** * Some checks for the findLiveItemsLowerBound() method when the dataset is * unordered. */ @Test public void testFindLiveItemsLowerBound_Unordered() { DefaultXYDataset d = new DefaultXYDataset(); // check a series with no items d.addSeries("S1", new double[][] {{}, {}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 0, 10.0, 11.0)); // check a series with one item d.addSeries("S2", new double[][] {{0.0}, {9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 1, 0.0, 1.1)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 1, 2.0, 3.3)); // check a series with two items d.addSeries("S3", new double[][] {{0.0, 1.0}, {9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 2, 0.0, 1.1)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 2, 1.0, 2.2)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 2, 2.0, 3.3)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 2, 3.0, 4.4)); // check a series with three items d.addSeries("S4", new double[][] {{1.0, 2.0, 1.5}, {9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 3, 0.0, 1.1)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 3, 1.0, 2.2)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 3, 2.0, 3.3)); assertEquals(2, RendererUtilities.findLiveItemsLowerBound(d, 3, 3.0, 4.4)); // check a series with four items d.addSeries("S5", new double[][] {{1.0, 2.0, 1.5, 1.8}, {9.9, 9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 4, 0.0, 1.1)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 4, 1.0, 2.2)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 4, 2.0, 3.3)); assertEquals(3, RendererUtilities.findLiveItemsLowerBound(d, 4, 3.0, 4.4)); assertEquals(3, RendererUtilities.findLiveItemsLowerBound(d, 4, 4.0, 5.5)); } /** * Some checks for the findLiveItemsLowerBound() method when the dataset is * ASCENDING. */ @Test public void testFindLiveItemsLowerBound_Ascending() { DefaultXYDataset d = new DefaultXYDataset() { @Override public DomainOrder getDomainOrder() { // we're doing this for testing only, and make sure that we // only add data in ascending order by x-value return DomainOrder.ASCENDING; } }; // check a series with no items d.addSeries("S1", new double[][] {{}, {}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 0, 10.0, 11.1)); // check a series with one item d.addSeries("S2", new double[][] {{1.0}, {9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 1, 0.0, 1.1)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 1, 2.0, 2.2)); // check a series with two items d.addSeries("S3", new double[][] {{1.0, 2.0}, {9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 2, 0.0, 1.1)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 2, 1.0, 2.2)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 2, 2.0, 3.3)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 2, 3.0, 4.4)); // check a series with three items d.addSeries("S4", new double[][] {{1.0, 2.0, 3.0}, {9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 3, 0.0, 1.1)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 3, 1.0, 2.2)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 3, 2.0, 3.3)); assertEquals(2, RendererUtilities.findLiveItemsLowerBound(d, 3, 3.0, 4.4)); // check a series with four items d.addSeries("S5", new double[][] {{1.0, 2.0, 3.0, 4.0}, {9.9, 9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 4, 0.0, 1.1)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 4, 1.0, 2.2)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 4, 2.0, 3.3)); assertEquals(2, RendererUtilities.findLiveItemsLowerBound(d, 4, 3.0, 4.4)); assertEquals(3, RendererUtilities.findLiveItemsLowerBound(d, 4, 4.0, 5.5)); // check a series with repeating items d.addSeries("S5", new double[][] {{1.0, 2.0, 2.0, 2.0, 3.0}, {9.9, 9.9, 9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 4, 0.0, 4.0)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 4, 1.0, 4.0)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 4, 2.0, 4.0)); assertEquals(4, RendererUtilities.findLiveItemsLowerBound(d, 4, 3.0, 4.0)); } /** * Some checks for the findLiveItemsLowerBound() method when the dataset is * DESCENDING. */ @Test public void testFindLiveItemsLowerBound_Descending() { DefaultXYDataset d = new DefaultXYDataset() { @Override public DomainOrder getDomainOrder() { // we're doing this for testing only, and make sure that we // only add data in descending order by x-value return DomainOrder.DESCENDING; } }; // check a series with no items d.addSeries("S1", new double[][] {{}, {}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 0, 10.0, 11.0)); // check a series with one item d.addSeries("S2", new double[][] {{1.0}, {9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 1, 0.0, 1.0)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 1, 1.1, 2.0)); // check a series with two items d.addSeries("S3", new double[][] {{2.0, 1.0}, {9.9, 9.9}}); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 2, 0.1, 0.5)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 2, 0.1, 1.0)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 2, 1.1, 2.0)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 2, 2.2, 3.0)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 2, 3.3, 4.0)); // check a series with three items d.addSeries("S4", new double[][] {{3.0, 2.0, 1.0}, {9.9, 9.9, 9.9}}); assertEquals(2, RendererUtilities.findLiveItemsLowerBound(d, 3, 0.0, 1.0)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 3, 1.0, 2.0)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 3, 2.0, 3.0)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 3, 3.0, 4.0)); // check a series with four items d.addSeries("S5", new double[][] {{4.0, 3.0, 2.0, 1.0}, {9.9, 9.9, 9.9, 9.9}}); assertEquals(3, RendererUtilities.findLiveItemsLowerBound(d, 4, 0.1, 0.5)); assertEquals(3, RendererUtilities.findLiveItemsLowerBound(d, 4, 0.1, 1.0)); assertEquals(2, RendererUtilities.findLiveItemsLowerBound(d, 4, 1.1, 2.0)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 4, 2.2, 3.0)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 4, 3.3, 4.0)); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 4, 4.4, 5.0)); // check a series with repeating items d.addSeries("S6", new double[][] {{3.0, 2.0, 2.0, 2.0, 1.0}, {9.9, 9.9, 9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsLowerBound(d, 5, 0.0, 3.0)); assertEquals(1, RendererUtilities.findLiveItemsLowerBound(d, 5, 0.0, 2.0)); assertEquals(4, RendererUtilities.findLiveItemsLowerBound(d, 5, 0.0, 1.0)); assertEquals(4, RendererUtilities.findLiveItemsLowerBound(d, 5, 0.0, 0.5)); } /** * Some checks for the findLiveItemsUpperBound() method when the dataset is * unordered. */ @Test public void testFindLiveItemsUpperBound_Unordered() { DefaultXYDataset d = new DefaultXYDataset(); // check a series with no items d.addSeries("S1", new double[][] {{}, {}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 0, 10.0, 11.0)); // check a series with one item d.addSeries("S2", new double[][] {{1.0}, {9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 1, 0.0, 1.1)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 1, 2.0, 3.3)); // check a series with two items d.addSeries("S3", new double[][] {{1.0, 2.0}, {9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 2, 0.0, 1.1)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 2, 1.0, 2.2)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 2, 2.0, 3.3)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 2, 3.0, 4.4)); // check a series with three items d.addSeries("S4", new double[][] {{1.0, 2.0, 1.5}, {9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 3, 0.0, 1.1)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 1.0, 2.2)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 2.0, 3.3)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 3.0, 4.4)); // check a series with four items d.addSeries("S5", new double[][] {{1.0, 2.0, 1.5, 1.8}, {9.9, 9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 1.1)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 1.0, 2.2)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 2.0, 3.3)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 3.0, 4.4)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 4.0, 5.5)); } /** * Some checks for the findLiveItemsUpperBound() method when the dataset is * ASCENDING. */ @Test public void testFindLiveItemsUpperBound_Ascending() { DefaultXYDataset d = new DefaultXYDataset() { @Override public DomainOrder getDomainOrder() { // we're doing this for testing only, and make sure that we // only add data in ascending order by x-value return DomainOrder.ASCENDING; } }; // check a series with no items d.addSeries("S1", new double[][] {{}, {}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 0, 10.0, 11.1)); // check a series with one item d.addSeries("S2", new double[][] {{1.0}, {9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 1, 0.0, 1.1)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 1, 2.0, 2.2)); // check a series with two items d.addSeries("S3", new double[][] {{1.0, 2.0}, {9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 2, 0.0, 1.0)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 2, 1.0, 2.2)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 2, 2.0, 3.3)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 2, 3.0, 4.4)); // check a series with three items d.addSeries("S4", new double[][] {{1.0, 2.0, 3.0}, {9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 3, 0.0, 1.1)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 3, 1.0, 2.2)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 2.0, 3.3)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 3.0, 4.4)); // check a series with four items d.addSeries("S5", new double[][] {{1.0, 2.0, 3.0, 4.0}, {9.9, 9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 1.1)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 4, 1.0, 2.2)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 4, 2.0, 3.3)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 3.0, 4.4)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 4.0, 5.5)); // check a series with repeating items d.addSeries("S5", new double[][] {{1.0, 2.0, 2.0, 2.0, 3.0}, {9.9, 9.9, 9.9, 9.9, 9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 1.0)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 2.0)); assertEquals(4, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 3.0)); assertEquals(4, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.0, 4.0)); } /** * Some checks for the findLiveItemsUpperBound() method when the dataset is * DESCENDING. */ @Test public void testFindLiveItemsUpperBound_Descending() { DefaultXYDataset d = new DefaultXYDataset() { @Override public DomainOrder getDomainOrder() { // we're doing this for testing only, and make sure that we // only add data in descending order by x-value return DomainOrder.DESCENDING; } }; // check a series with no items d.addSeries("S1", new double[][] {{}, {}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 0, 10.0, 11.0)); // check a series with one item d.addSeries("S2", new double[][] {{1.0}, {9.9}}); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 1, 0.0, 1.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 1, 1.1, 2.0)); // check a series with two items d.addSeries("S3", new double[][] {{2.0, 1.0}, {9.9, 9.9}}); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 2, 0.1, 0.5)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 2, 0.1, 1.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 2, 1.1, 2.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 2, 2.2, 3.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 2, 3.3, 4.0)); // check a series with three items d.addSeries("S4", new double[][] {{3.0, 2.0, 1.0}, {9.9, 9.9, 9.9}}); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 0.0, 1.0)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 3, 1.0, 2.0)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 3, 2.0, 3.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 3, 3.0, 4.0)); // check a series with four items d.addSeries("S5", new double[][] {{4.0, 3.0, 2.0, 1.0}, {9.9, 9.9, 9.9, 9.9}}); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.1, 0.5)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 4, 0.1, 1.0)); assertEquals(2, RendererUtilities.findLiveItemsUpperBound(d, 4, 1.1, 2.0)); assertEquals(1, RendererUtilities.findLiveItemsUpperBound(d, 4, 2.2, 3.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 4, 3.3, 4.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 4, 4.4, 5.0)); // check a series with repeating items d.addSeries("S6", new double[][] {{3.0, 2.0, 2.0, 2.0, 1.0}, {9.9, 9.9, 9.9, 9.9, 9.9}}); assertEquals(4, RendererUtilities.findLiveItemsUpperBound(d, 5, 0.0, 5.0)); assertEquals(4, RendererUtilities.findLiveItemsUpperBound(d, 5, 1.0, 5.0)); assertEquals(3, RendererUtilities.findLiveItemsUpperBound(d, 5, 2.0, 5.0)); assertEquals(0, RendererUtilities.findLiveItemsUpperBound(d, 5, 3.0, 5.0)); } /** * Checks the bounds calculation for a series where the x-ordering is not * known. See bug 3561093. */ @Test public void test3561093() {
XYSeries s = new XYSeries("S1", false);
2
2023-12-24 12:36:47+00:00
24k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/module/impl/skills/Fishing.java
[ { "identifier": "MayOBeesConfig", "path": "src/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java", "snippet": "public class MayOBeesConfig extends Config {\n\n //<editor-fold desc=\"COMBAT\">\n @KeyBind(\n name = \"Shortbow Aura\",\n description = \"Automatica...
import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.event.SpawnParticleEvent; import com.github.may2beez.mayobees.handler.RotationHandler; import com.github.may2beez.mayobees.module.IModule; import com.github.may2beez.mayobees.module.IModuleActive; import com.github.may2beez.mayobees.module.impl.combat.MobKiller; import com.github.may2beez.mayobees.util.*; import com.github.may2beez.mayobees.util.helper.Clock; import com.github.may2beez.mayobees.util.helper.Rotation; import com.github.may2beez.mayobees.util.helper.RotationConfiguration; import com.github.may2beez.mayobees.util.helper.Timer; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.projectile.EntityFishHook; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.util.List; import java.util.Random; import java.util.concurrent.CopyOnWriteArrayList;
15,930
particles.clear(); rodSlot = InventoryUtils.getSlotIdOfItemInHotbar("Rod"); if (rodSlot == -1) { LogUtils.error("No rod found in hotbar!"); onDisable(); return; } startRotation = new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch); KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), MayOBeesConfig.sneakWhileFishing); MobKiller.getInstance().start(); MobKiller.getInstance().setTarget(fishingMobs.stream().filter(name -> !name.toLowerCase().contains("squid")).toArray(String[]::new)); } @Override public void onDisable() { if (MayOBeesConfig.sneakWhileFishing) { KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), false); } KeyBindUtils.stopMovement(); RotationHandler.getInstance().reset(); MobKiller.getInstance().stop(); UngrabUtils.regrabMouse(); } @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { if (event.phase != TickEvent.Phase.START || !isRunning() || mc.thePlayer == null || mc.theWorld == null) return; if (mc.currentScreen != null) return; ItemStack heldItem; particles.removeIf(p -> (System.currentTimeMillis() - p.timeAdded) > 1000); if (MobKiller.hasTarget) { return; } if (MayOBeesConfig.antiAfkWhileFishing && antiAfkTimer.hasPassed(3000 + new Random().nextInt(1500))) { antiAfkTimer.schedule(); if (RotationHandler.getInstance().isRotating()) { switch (antiAfkState) { case AWAY: { Rotation randomRotation = new Rotation(startRotation.getYaw() + (-2 + new Random().nextInt(4)), startRotation.getPitch() + (-2 + new Random().nextInt(4))); RotationHandler.getInstance().easeTo( new RotationConfiguration(randomRotation, 160, RotationConfiguration.RotationType.CLIENT, null)); antiAfkState = AntiAfkState.BACK; break; } case BACK: { RotationHandler.getInstance().easeTo( new RotationConfiguration(startRotation, 180, RotationConfiguration.RotationType.CLIENT, null)); antiAfkState = AntiAfkState.AWAY; break; } } } } if (MayOBeesConfig.sneakWhileFishing) { KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), true); } switch (currentState) { case THROWING: { if (mc.thePlayer.fishEntity == null && throwTimer.hasPassed(250) && RotationHandler.getInstance().isRotating()) { mc.thePlayer.inventory.currentItem = rodSlot; mc.playerController.sendUseItem(mc.thePlayer, mc.theWorld, mc.thePlayer.getHeldItem()); throwTimer.schedule(); inWaterTimer.schedule(); currentState = AutoFishState.IN_WATER; break; } if (throwTimer.hasPassed(2500) && mc.thePlayer.fishEntity != null) { currentState = AutoFishState.FISH_BITE; } break; } case IN_WATER: { heldItem = mc.thePlayer.getHeldItem(); if (heldItem != null && heldItem.getItem() == Items.fishing_rod) { if (throwTimer.hasPassed(500) && mc.thePlayer.fishEntity != null) { if (mc.thePlayer.fishEntity.isInWater() || mc.thePlayer.fishEntity.isInLava()) { EntityFishHook bobber = mc.thePlayer.fishEntity; if (inWaterTimer.hasPassed(2500) && Math.abs(bobber.motionX) < 0.01 && Math.abs(bobber.motionZ) < 0.01) { double movement = bobber.posY - oldBobberPosY; oldBobberPosY = bobber.posY; if ((movement < -0.04 && isBobberNearParticles(bobber)) || bobber.caughtEntity != null) { currentState = AutoFishState.FISH_BITE; } } break; } if (inWaterTimer.hasPassed(2500)) { currentState = AutoFishState.FISH_BITE; } break; } if (throwTimer.hasPassed(1000) && mc.thePlayer.fishEntity == null) { throwTimer.schedule(); currentState = AutoFishState.THROWING; } break; } mc.thePlayer.inventory.currentItem = rodSlot; break; } case FISH_BITE: { mc.thePlayer.inventory.currentItem = rodSlot; mc.playerController.sendUseItem(mc.thePlayer, mc.theWorld, mc.thePlayer.getHeldItem()); RotationHandler.getInstance().easeTo( new RotationConfiguration(startRotation, 45L, RotationConfiguration.RotationType.CLIENT, null)); throwTimer.schedule(); currentState = AutoFishState.THROWING; break; } } } @SubscribeEvent
package com.github.may2beez.mayobees.module.impl.skills; public class Fishing implements IModuleActive { private static Fishing instance; public static Fishing getInstance() { if (instance == null) { instance = new Fishing(); } return instance; } @Override public String getName() { return "Fishing"; } private final Minecraft mc = Minecraft.getMinecraft(); private static final List<String> fishingMobs = JsonUtils.getListFromUrl("https://raw.githubusercontent.com/May2Beez/May2BeezQoL/master/sea_creatures_list.json", "mobs"); private final Timer throwTimer = new Timer(); private final Timer inWaterTimer = new Timer(); private final Clock attackDelay = new Clock(); private final Timer antiAfkTimer = new Timer(); private double oldBobberPosY = 0.0D; private Rotation startRotation = null; private static final CopyOnWriteArrayList<ParticleEntry> particles = new CopyOnWriteArrayList<>(); private int rodSlot = 0; @Override public boolean isRunning() { return MayOBeesConfig.fishing; } private enum AutoFishState { THROWING, IN_WATER, FISH_BITE } private enum AntiAfkState { AWAY, BACK } private AntiAfkState antiAfkState = AntiAfkState.AWAY; private AutoFishState currentState = AutoFishState.THROWING; @Override public void onEnable() { currentState = AutoFishState.THROWING; throwTimer.schedule(); inWaterTimer.schedule(); attackDelay.reset(); antiAfkTimer.schedule(); if (MayOBeesConfig.mouseUngrab) UngrabUtils.ungrabMouse(); oldBobberPosY = 0.0D; particles.clear(); rodSlot = InventoryUtils.getSlotIdOfItemInHotbar("Rod"); if (rodSlot == -1) { LogUtils.error("No rod found in hotbar!"); onDisable(); return; } startRotation = new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch); KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), MayOBeesConfig.sneakWhileFishing); MobKiller.getInstance().start(); MobKiller.getInstance().setTarget(fishingMobs.stream().filter(name -> !name.toLowerCase().contains("squid")).toArray(String[]::new)); } @Override public void onDisable() { if (MayOBeesConfig.sneakWhileFishing) { KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), false); } KeyBindUtils.stopMovement(); RotationHandler.getInstance().reset(); MobKiller.getInstance().stop(); UngrabUtils.regrabMouse(); } @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { if (event.phase != TickEvent.Phase.START || !isRunning() || mc.thePlayer == null || mc.theWorld == null) return; if (mc.currentScreen != null) return; ItemStack heldItem; particles.removeIf(p -> (System.currentTimeMillis() - p.timeAdded) > 1000); if (MobKiller.hasTarget) { return; } if (MayOBeesConfig.antiAfkWhileFishing && antiAfkTimer.hasPassed(3000 + new Random().nextInt(1500))) { antiAfkTimer.schedule(); if (RotationHandler.getInstance().isRotating()) { switch (antiAfkState) { case AWAY: { Rotation randomRotation = new Rotation(startRotation.getYaw() + (-2 + new Random().nextInt(4)), startRotation.getPitch() + (-2 + new Random().nextInt(4))); RotationHandler.getInstance().easeTo( new RotationConfiguration(randomRotation, 160, RotationConfiguration.RotationType.CLIENT, null)); antiAfkState = AntiAfkState.BACK; break; } case BACK: { RotationHandler.getInstance().easeTo( new RotationConfiguration(startRotation, 180, RotationConfiguration.RotationType.CLIENT, null)); antiAfkState = AntiAfkState.AWAY; break; } } } } if (MayOBeesConfig.sneakWhileFishing) { KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), true); } switch (currentState) { case THROWING: { if (mc.thePlayer.fishEntity == null && throwTimer.hasPassed(250) && RotationHandler.getInstance().isRotating()) { mc.thePlayer.inventory.currentItem = rodSlot; mc.playerController.sendUseItem(mc.thePlayer, mc.theWorld, mc.thePlayer.getHeldItem()); throwTimer.schedule(); inWaterTimer.schedule(); currentState = AutoFishState.IN_WATER; break; } if (throwTimer.hasPassed(2500) && mc.thePlayer.fishEntity != null) { currentState = AutoFishState.FISH_BITE; } break; } case IN_WATER: { heldItem = mc.thePlayer.getHeldItem(); if (heldItem != null && heldItem.getItem() == Items.fishing_rod) { if (throwTimer.hasPassed(500) && mc.thePlayer.fishEntity != null) { if (mc.thePlayer.fishEntity.isInWater() || mc.thePlayer.fishEntity.isInLava()) { EntityFishHook bobber = mc.thePlayer.fishEntity; if (inWaterTimer.hasPassed(2500) && Math.abs(bobber.motionX) < 0.01 && Math.abs(bobber.motionZ) < 0.01) { double movement = bobber.posY - oldBobberPosY; oldBobberPosY = bobber.posY; if ((movement < -0.04 && isBobberNearParticles(bobber)) || bobber.caughtEntity != null) { currentState = AutoFishState.FISH_BITE; } } break; } if (inWaterTimer.hasPassed(2500)) { currentState = AutoFishState.FISH_BITE; } break; } if (throwTimer.hasPassed(1000) && mc.thePlayer.fishEntity == null) { throwTimer.schedule(); currentState = AutoFishState.THROWING; } break; } mc.thePlayer.inventory.currentItem = rodSlot; break; } case FISH_BITE: { mc.thePlayer.inventory.currentItem = rodSlot; mc.playerController.sendUseItem(mc.thePlayer, mc.theWorld, mc.thePlayer.getHeldItem()); RotationHandler.getInstance().easeTo( new RotationConfiguration(startRotation, 45L, RotationConfiguration.RotationType.CLIENT, null)); throwTimer.schedule(); currentState = AutoFishState.THROWING; break; } } } @SubscribeEvent
public void handleParticles(SpawnParticleEvent packet) {
1
2023-12-24 15:39:11+00:00
24k
viceice/verbrauchsapp
app/src/main/java/de/anipe/verbrauchsapp/fragments/CarContentFragment.java
[ { "identifier": "CarInputActivity", "path": "app/src/main/java/de/anipe/verbrauchsapp/CarInputActivity.java", "snippet": "public class CarInputActivity extends AppCompatActivity {\n\n private ConsumptionDataSource dataSource;\n private FileSystemAccessor accessor;\n private long carId;\n pri...
import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.fragment.app.Fragment; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.text.DecimalFormat; import de.anipe.verbrauchsapp.CarInputActivity; import de.anipe.verbrauchsapp.ConsumptionInputActivity; import de.anipe.verbrauchsapp.ConsumptionListActivity; import de.anipe.verbrauchsapp.GDriveStoreActivity; import de.anipe.verbrauchsapp.GraphViewPlot; import de.anipe.verbrauchsapp.ImportActivity; import de.anipe.verbrauchsapp.MainActivity; import de.anipe.verbrauchsapp.PictureImportActivity; import de.anipe.verbrauchsapp.R; import de.anipe.verbrauchsapp.db.ConsumptionDataSource; import de.anipe.verbrauchsapp.io.FileSystemAccessor; import de.anipe.verbrauchsapp.io.XMLHandler; import de.anipe.verbrauchsapp.objects.Car;
18,816
intent.putExtra("kmstate", dataSource.getMileageForCar(carId)); getActivity().startActivity(intent); } private void createAddPictureActivity() { Intent intent = new Intent(getActivity(), PictureImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createImportDataActivity() { Intent intent = new Intent(getActivity(), ImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void removeEntry() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getActivity()); // set title alertDialogBuilder.setTitle("Eintrag löschen?"); TypedValue typedValue = new TypedValue(); getActivity().getTheme().resolveAttribute(android.R.attr.alertDialogIcon, typedValue, true); alertDialogBuilder.setIcon(typedValue.resourceId); // set dialog message alertDialogBuilder .setMessage( "Mit 'Ja' wird der Fahrzeugdatensatz und alle dazugehörigen Verbrauchsdatensätze gelöscht!") .setCancelable(false) .setPositiveButton("Ja", (dialog, id) -> { dataSource.deleteConsumptionsForCar(carId); dataSource.deleteCar(dataSource.getCarForId(carId)); getActivity().finish(); }) .setNegativeButton("Nein", (dialog, id) -> dialog.cancel()); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } private void createViewConsumptionsActivity() { Intent intent = new Intent(getActivity(), ConsumptionListActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createConsumptionPlotActivity() { // Intent intent = new Intent(CarContentActivity.this, PlotActivity.class); // Intent intent = new Intent(CarContentActivity.this, XYPlot.class); Intent intent = new Intent(getActivity(), GraphViewPlot.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void updateView() { Car car = dataSource.getCarForId(carId); TextView header = rootView.findViewById(R.id.fullscreen_car_content); header.setText(car.getBrand().value() + " " + car.getType()); TextView startkm = rootView.findViewById(R.id.startkmValueLine); startkm.setText(String.valueOf(car.getStartKm())); TextView actualkm = rootView.findViewById(R.id.actualkmValueLine); int mileage = dataSource.getMileageForCar(carId); actualkm.setText(String.valueOf(mileage)); TextView consumption = rootView.findViewById(R.id.consumptionValueLine); consumption.setText(new DecimalFormat("#.00").format(dataSource .getOverallConsumptionForCar(carId)) + " l/100km"); TextView overallKm = rootView.findViewById(R.id.drivenKmValueLine); overallKm.setText(String.valueOf(mileage - car.getStartKm())); TextView overallCosts = rootView.findViewById(R.id.overallCostsValueLine); overallCosts.setText(new DecimalFormat("#0.00").format(dataSource .getOverallCostsForCar(carId)) + " \u20ac"); if (car.getImage() != null) { ImageView image = rootView.findViewById(R.id.pictureLine); image.setImageBitmap(car.getImage()); } } @SuppressWarnings("unused") private void exportData() { Car car = dataSource.getCarForId(carId); XMLHandler handler = new XMLHandler(null, car, dataSource.getOverallConsumptionForCar(carId), dataSource.getConsumptionCycles(carId)); try { accessor.writeXMLFileToStorage(getActivity(), handler.createConsumptionDocument(), MainActivity.STORAGE_DIR, car.getBrand() + "_" + car.getType()); Toast.makeText(getActivity(), "Daten erfolgreich in XML-Datei exportiert!", Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText( getActivity(), "Fehler beim Schreiben der XML-Datei. Grund: " + e.getLocalizedMessage(), Toast.LENGTH_LONG) .show(); } } private void storeDriveData() { Intent intent = new Intent(getActivity(),
package de.anipe.verbrauchsapp.fragments; /** * */ public class CarContentFragment extends Fragment { private FileSystemAccessor accessor; private ConsumptionDataSource dataSource; private long carId; private View rootView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accessor = FileSystemAccessor.getInstance(); dataSource = ConsumptionDataSource.getInstance(getActivity()); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { carId = getArguments().getLong("carid"); // The last two arguments ensure LayoutParams are inflated properly. rootView = inflater.inflate(R.layout.activity_car_content, container, false); FloatingActionButton btn = rootView.findViewById(R.id.float_add); btn.setOnClickListener(clickListener); return rootView; } @Override public void onResume() { updateView(); super.onResume(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.car_menubar, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_edit_entry: createCarEditActivity(); return true; case R.id.action_add_picture: createAddPictureActivity(); return true; case R.id.action_view_consumptions: createViewConsumptionsActivity(); return true; case R.id.action_view_chart: createConsumptionPlotActivity(); return true; case R.id.action_remove_entry: removeEntry(); return true; case R.id.action_import_data: createImportDataActivity(); return true; case R.id.action_export_data: // exportData(); storeDriveData(); return true; default: return super.onOptionsItemSelected(item); } } // Create an anonymous implementation of OnClickListener private OnClickListener clickListener = v -> { switch (v.getId()) { case R.id.float_add: createAddConsumptionActivity(); break; } }; private void createCarEditActivity() { Intent intent = new Intent(getActivity(), CarInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("update", true); getActivity().startActivity(intent); } private void createAddConsumptionActivity() { Intent intent = new Intent(getActivity(), ConsumptionInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("kmstate", dataSource.getMileageForCar(carId)); getActivity().startActivity(intent); } private void createAddPictureActivity() { Intent intent = new Intent(getActivity(), PictureImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createImportDataActivity() { Intent intent = new Intent(getActivity(), ImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void removeEntry() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getActivity()); // set title alertDialogBuilder.setTitle("Eintrag löschen?"); TypedValue typedValue = new TypedValue(); getActivity().getTheme().resolveAttribute(android.R.attr.alertDialogIcon, typedValue, true); alertDialogBuilder.setIcon(typedValue.resourceId); // set dialog message alertDialogBuilder .setMessage( "Mit 'Ja' wird der Fahrzeugdatensatz und alle dazugehörigen Verbrauchsdatensätze gelöscht!") .setCancelable(false) .setPositiveButton("Ja", (dialog, id) -> { dataSource.deleteConsumptionsForCar(carId); dataSource.deleteCar(dataSource.getCarForId(carId)); getActivity().finish(); }) .setNegativeButton("Nein", (dialog, id) -> dialog.cancel()); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } private void createViewConsumptionsActivity() { Intent intent = new Intent(getActivity(), ConsumptionListActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createConsumptionPlotActivity() { // Intent intent = new Intent(CarContentActivity.this, PlotActivity.class); // Intent intent = new Intent(CarContentActivity.this, XYPlot.class); Intent intent = new Intent(getActivity(), GraphViewPlot.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void updateView() { Car car = dataSource.getCarForId(carId); TextView header = rootView.findViewById(R.id.fullscreen_car_content); header.setText(car.getBrand().value() + " " + car.getType()); TextView startkm = rootView.findViewById(R.id.startkmValueLine); startkm.setText(String.valueOf(car.getStartKm())); TextView actualkm = rootView.findViewById(R.id.actualkmValueLine); int mileage = dataSource.getMileageForCar(carId); actualkm.setText(String.valueOf(mileage)); TextView consumption = rootView.findViewById(R.id.consumptionValueLine); consumption.setText(new DecimalFormat("#.00").format(dataSource .getOverallConsumptionForCar(carId)) + " l/100km"); TextView overallKm = rootView.findViewById(R.id.drivenKmValueLine); overallKm.setText(String.valueOf(mileage - car.getStartKm())); TextView overallCosts = rootView.findViewById(R.id.overallCostsValueLine); overallCosts.setText(new DecimalFormat("#0.00").format(dataSource .getOverallCostsForCar(carId)) + " \u20ac"); if (car.getImage() != null) { ImageView image = rootView.findViewById(R.id.pictureLine); image.setImageBitmap(car.getImage()); } } @SuppressWarnings("unused") private void exportData() { Car car = dataSource.getCarForId(carId); XMLHandler handler = new XMLHandler(null, car, dataSource.getOverallConsumptionForCar(carId), dataSource.getConsumptionCycles(carId)); try { accessor.writeXMLFileToStorage(getActivity(), handler.createConsumptionDocument(), MainActivity.STORAGE_DIR, car.getBrand() + "_" + car.getType()); Toast.makeText(getActivity(), "Daten erfolgreich in XML-Datei exportiert!", Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText( getActivity(), "Fehler beim Schreiben der XML-Datei. Grund: " + e.getLocalizedMessage(), Toast.LENGTH_LONG) .show(); } } private void storeDriveData() { Intent intent = new Intent(getActivity(),
GDriveStoreActivity.class);
3
2023-12-28 12:33:52+00:00
24k
strokegmd/StrokeClient
stroke/client/modules/ModuleManager.java
[ { "identifier": "AntiKnockback", "path": "stroke/client/modules/combat/AntiKnockback.java", "snippet": "public class AntiKnockback extends BaseModule {\r\n\tpublic static AntiKnockback instance;\r\n\t\r\n\tpublic AntiKnockback() {\r\n\t\tsuper(\"AntiKnockBack\", \"Disables knockback\", 0x00, ModuleCateg...
import java.util.ArrayList; import java.util.Comparator; import net.minecraft.client.Minecraft; import net.stroke.client.modules.combat.AntiKnockback; import net.stroke.client.modules.combat.AutoArmor; import net.stroke.client.modules.combat.AutoGApple; import net.stroke.client.modules.combat.AutoTotem; import net.stroke.client.modules.combat.Criticals; import net.stroke.client.modules.combat.CrystalAura; import net.stroke.client.modules.combat.KillAura; import net.stroke.client.modules.fun.HalalMode; import net.stroke.client.modules.misc.DiscordRPCModule; import net.stroke.client.modules.misc.MCF; import net.stroke.client.modules.misc.MigrationCape; import net.stroke.client.modules.misc.SelfDestruct; import net.stroke.client.modules.misc.Spammer; import net.stroke.client.modules.misc.StashLogger; import net.stroke.client.modules.movement.AirJump; import net.stroke.client.modules.movement.AutoJump; import net.stroke.client.modules.movement.EntitySpeed; import net.stroke.client.modules.movement.Flight; import net.stroke.client.modules.movement.InventoryMove; import net.stroke.client.modules.movement.NoSlowDown; import net.stroke.client.modules.movement.SafeWalk; import net.stroke.client.modules.movement.Sprint; import net.stroke.client.modules.movement.Step; import net.stroke.client.modules.player.Blink; import net.stroke.client.modules.player.ChestStealer; import net.stroke.client.modules.player.FastPlace; import net.stroke.client.modules.player.Freecam; import net.stroke.client.modules.player.NoFall; import net.stroke.client.modules.player.Portals; import net.stroke.client.modules.player.Timer; import net.stroke.client.modules.render.AntiOverlay; import net.stroke.client.modules.render.BlockHitAnim; import net.stroke.client.modules.render.ClickGui; import net.stroke.client.modules.render.FullBright; import net.stroke.client.modules.render.Hud; import net.stroke.client.modules.render.NameTags; import net.stroke.client.modules.render.NoScoreBoard; import net.stroke.client.modules.render.NoWeather; import net.stroke.client.modules.render.PlayerESP; import net.stroke.client.modules.render.StorageESP; import net.stroke.client.modules.render.TargetHUD; import net.stroke.client.modules.render.Tracers; import net.stroke.client.modules.render.ViewModel; import net.stroke.client.modules.render.Wallhack; import net.stroke.client.modules.render.XRay;
16,553
package net.stroke.client.modules; public class ModuleManager { public static Minecraft mc = Minecraft.getMinecraft(); public static ArrayList<BaseModule> modules = new ArrayList<BaseModule>(); public static void addModule(BaseModule module) { modules.add(module); } public static void sortModules() { modules.sort(Comparator.comparingInt(module -> mc.fontRendererObj.getStringWidth(((BaseModule)module).name)).reversed()); } public static void loadModules() { ModuleManager.addModule(new AntiKnockback()); ModuleManager.addModule(new AutoArmor()); ModuleManager.addModule(new AutoGApple()); ModuleManager.addModule(new AutoTotem()); ModuleManager.addModule(new Criticals()); ModuleManager.addModule(new CrystalAura()); ModuleManager.addModule(new KillAura()); ModuleManager.addModule(new AirJump()); ModuleManager.addModule(new AutoJump()); ModuleManager.addModule(new EntitySpeed()); ModuleManager.addModule(new Flight()); ModuleManager.addModule(new InventoryMove()); ModuleManager.addModule(new NoSlowDown()); ModuleManager.addModule(new SafeWalk()); ModuleManager.addModule(new Sprint()); ModuleManager.addModule(new Step()); ModuleManager.addModule(new Blink()); ModuleManager.addModule(new ChestStealer()); ModuleManager.addModule(new FastPlace()); ModuleManager.addModule(new Freecam()); ModuleManager.addModule(new NoFall()); ModuleManager.addModule(new Portals()); ModuleManager.addModule(new Timer()); ModuleManager.addModule(new AntiOverlay()); ModuleManager.addModule(new BlockHitAnim()); ModuleManager.addModule(new ClickGui()); ModuleManager.addModule(new FullBright()); ModuleManager.addModule(new Hud()); ModuleManager.addModule(new NameTags()); ModuleManager.addModule(new NoScoreBoard()); ModuleManager.addModule(new NoWeather()); ModuleManager.addModule(new PlayerESP()); ModuleManager.addModule(new StorageESP()); ModuleManager.addModule(new TargetHUD()); ModuleManager.addModule(new Tracers()); ModuleManager.addModule(new ViewModel()); ModuleManager.addModule(new Wallhack());
package net.stroke.client.modules; public class ModuleManager { public static Minecraft mc = Minecraft.getMinecraft(); public static ArrayList<BaseModule> modules = new ArrayList<BaseModule>(); public static void addModule(BaseModule module) { modules.add(module); } public static void sortModules() { modules.sort(Comparator.comparingInt(module -> mc.fontRendererObj.getStringWidth(((BaseModule)module).name)).reversed()); } public static void loadModules() { ModuleManager.addModule(new AntiKnockback()); ModuleManager.addModule(new AutoArmor()); ModuleManager.addModule(new AutoGApple()); ModuleManager.addModule(new AutoTotem()); ModuleManager.addModule(new Criticals()); ModuleManager.addModule(new CrystalAura()); ModuleManager.addModule(new KillAura()); ModuleManager.addModule(new AirJump()); ModuleManager.addModule(new AutoJump()); ModuleManager.addModule(new EntitySpeed()); ModuleManager.addModule(new Flight()); ModuleManager.addModule(new InventoryMove()); ModuleManager.addModule(new NoSlowDown()); ModuleManager.addModule(new SafeWalk()); ModuleManager.addModule(new Sprint()); ModuleManager.addModule(new Step()); ModuleManager.addModule(new Blink()); ModuleManager.addModule(new ChestStealer()); ModuleManager.addModule(new FastPlace()); ModuleManager.addModule(new Freecam()); ModuleManager.addModule(new NoFall()); ModuleManager.addModule(new Portals()); ModuleManager.addModule(new Timer()); ModuleManager.addModule(new AntiOverlay()); ModuleManager.addModule(new BlockHitAnim()); ModuleManager.addModule(new ClickGui()); ModuleManager.addModule(new FullBright()); ModuleManager.addModule(new Hud()); ModuleManager.addModule(new NameTags()); ModuleManager.addModule(new NoScoreBoard()); ModuleManager.addModule(new NoWeather()); ModuleManager.addModule(new PlayerESP()); ModuleManager.addModule(new StorageESP()); ModuleManager.addModule(new TargetHUD()); ModuleManager.addModule(new Tracers()); ModuleManager.addModule(new ViewModel()); ModuleManager.addModule(new Wallhack());
ModuleManager.addModule(new XRay());
44
2023-12-31 10:56:59+00:00
24k
HuXin0817/shop_api
framework/src/main/java/cn/lili/modules/permission/serviceimpl/AdminUserServiceImpl.java
[ { "identifier": "Cache", "path": "framework/src/main/java/cn/lili/cache/Cache.java", "snippet": "public interface Cache<T> {\n\n /**\n * Get an item from the cache, nontransactionally\n *\n * @param key 缓存key\n * @return the cached object or <tt>null</tt>\n */\n T get(Object ke...
import cn.hutool.core.text.CharSequenceUtil; import cn.lili.cache.Cache; import cn.lili.cache.CachePrefix; import cn.lili.common.enums.ResultCode; import cn.lili.common.exception.ServiceException; import cn.lili.common.security.AuthUser; import cn.lili.common.security.context.UserContext; import cn.lili.common.security.enums.UserEnums; import cn.lili.common.security.token.Token; import cn.lili.common.utils.BeanUtil; import cn.lili.common.utils.StringUtils; import cn.lili.modules.permission.entity.dos.AdminUser; import cn.lili.modules.permission.entity.dos.Department; import cn.lili.modules.permission.entity.dos.Role; import cn.lili.modules.permission.entity.dos.UserRole; import cn.lili.modules.permission.entity.dto.AdminUserDTO; import cn.lili.modules.permission.entity.vo.AdminUserVO; import cn.lili.modules.permission.mapper.AdminUserMapper; import cn.lili.modules.permission.service.*; import cn.lili.modules.system.aspect.annotation.SystemLogPoint; import cn.lili.modules.system.token.ManagerTokenGenerate; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
20,919
package cn.lili.modules.permission.serviceimpl; /** * 用户业务层实现 * * @author Chopper * @since 2020/11/17 3:46 下午 */ @Slf4j @Service public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService { /** * 角色长度 */ private final int rolesMaxSize = 10; @Autowired private UserRoleService userRoleService; @Autowired private RoleService roleService; @Autowired private DepartmentService departmentService; @Autowired private MenuService menuService; @Autowired private ManagerTokenGenerate managerTokenGenerate; @Autowired
package cn.lili.modules.permission.serviceimpl; /** * 用户业务层实现 * * @author Chopper * @since 2020/11/17 3:46 下午 */ @Slf4j @Service public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService { /** * 角色长度 */ private final int rolesMaxSize = 10; @Autowired private UserRoleService userRoleService; @Autowired private RoleService roleService; @Autowired private DepartmentService departmentService; @Autowired private MenuService menuService; @Autowired private ManagerTokenGenerate managerTokenGenerate; @Autowired
private Cache cache;
0
2023-12-24 19:45:18+00:00
24k
huidongyin/kafka-2.7.2
clients/src/main/java/org/apache/kafka/clients/producer/internals/ProducerMetadata.java
[ { "identifier": "Metadata", "path": "clients/src/main/java/org/apache/kafka/clients/Metadata.java", "snippet": "public class Metadata implements Closeable {\n private final Logger log;\n //元数据刷新的退避时间,即在进行元数据刷新的时候,如果失败会等待一段时间后尝试,这个参数表示在多长时间内避免对元数据进行过多的刷新。\n private final long refreshBackoffMs;\n...
import org.apache.kafka.clients.Metadata; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.internals.ClusterResourceListeners; import org.apache.kafka.common.requests.MetadataRequest; import org.apache.kafka.common.requests.MetadataResponse; import org.apache.kafka.common.utils.LogContext; import org.apache.kafka.common.utils.Time; import org.slf4j.Logger; import java.util.*;
18,163
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients.producer.internals; public class ProducerMetadata extends Metadata { // If a topic hasn't been accessed for this many milliseconds, it is removed from the cache. //控制主题元数据在多长时间内没有访问后将被从缓存中删除。默认情况下是 5 分钟。这个时间用于确定缓存中的主题元数据是否过期,并决定是否需要从集群中重新获取主题的元数据信息。 private final long metadataIdleMs; /* 存储了带有过期时间的主题。这是一个 `Map` 类型的数据结构,将主题名与其对应的过期时间进行了关联。 */ private final Map<String, Long> topics = new HashMap<>(); //用于存储新添加的主题集合。这个集合中存储了当前生产者实例中新添加的主题。 private final Set<String> newTopics = new HashSet<>(); private final Logger log; private final Time time; public ProducerMetadata(long refreshBackoffMs, long metadataExpireMs, long metadataIdleMs, LogContext logContext, ClusterResourceListeners clusterResourceListeners, Time time) { super(refreshBackoffMs, metadataExpireMs, logContext, clusterResourceListeners); this.metadataIdleMs = metadataIdleMs; this.log = logContext.logger(ProducerMetadata.class); this.time = time; } //构建获取元数据的请求 @Override
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients.producer.internals; public class ProducerMetadata extends Metadata { // If a topic hasn't been accessed for this many milliseconds, it is removed from the cache. //控制主题元数据在多长时间内没有访问后将被从缓存中删除。默认情况下是 5 分钟。这个时间用于确定缓存中的主题元数据是否过期,并决定是否需要从集群中重新获取主题的元数据信息。 private final long metadataIdleMs; /* 存储了带有过期时间的主题。这是一个 `Map` 类型的数据结构,将主题名与其对应的过期时间进行了关联。 */ private final Map<String, Long> topics = new HashMap<>(); //用于存储新添加的主题集合。这个集合中存储了当前生产者实例中新添加的主题。 private final Set<String> newTopics = new HashSet<>(); private final Logger log; private final Time time; public ProducerMetadata(long refreshBackoffMs, long metadataExpireMs, long metadataIdleMs, LogContext logContext, ClusterResourceListeners clusterResourceListeners, Time time) { super(refreshBackoffMs, metadataExpireMs, logContext, clusterResourceListeners); this.metadataIdleMs = metadataIdleMs; this.log = logContext.logger(ProducerMetadata.class); this.time = time; } //构建获取元数据的请求 @Override
public synchronized MetadataRequest.Builder newMetadataRequestBuilder() {
3
2023-12-23 07:12:18+00:00
24k
qiusunshine/xiu
app/src/main/java/org/mozilla/xiu/browser/dlan/MediaPlayActivity.java
[ { "identifier": "Intents", "path": "clinglibrary/src/main/java/com/qingfeng/clinglibrary/Intents.java", "snippet": "public class Intents {\n /**\n * Prefix for all intents created\n */\n public static final String INTENT_PREFIX = \"com.zane.androidupnpdemo.\";\n\n /**\n * Prefix for...
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatSeekBar; import com.alibaba.fastjson.JSON; import com.qingfeng.clinglibrary.Intents; import com.qingfeng.clinglibrary.control.ClingPlayControl; import com.qingfeng.clinglibrary.control.callback.ControlCallback; import com.qingfeng.clinglibrary.control.callback.ControlReceiveCallback; import com.qingfeng.clinglibrary.entity.ClingVolumeResponse; import com.qingfeng.clinglibrary.entity.DLANPlayState; import com.qingfeng.clinglibrary.entity.IResponse; import com.qingfeng.clinglibrary.service.manager.ClingManager; import org.fourthline.cling.model.ModelUtil; import org.fourthline.cling.support.model.PositionInfo; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.mozilla.xiu.browser.R; import org.mozilla.xiu.browser.base.BaseActivity; import org.mozilla.xiu.browser.utils.StringUtil; import org.mozilla.xiu.browser.utils.ToastMgr; import java.util.Timer; import java.util.TimerTask;
21,018
findViewById(R.id.img_next).setOnClickListener(v -> { ToastMgr.shortCenter(getContext(), "暂不支持此功能"); }); findViewById(R.id.img_previous).setOnClickListener(v -> { ToastMgr.shortCenter(getContext(), "嘿嘿,我是个假按钮~"); }); } private void next() { } @Subscribe(threadMode = ThreadMode.MAIN) public void onDlan(DlanPlayEvent event) { initData(event.getUrl(), event.getTitle(), event.getHeaders()); } private Context getContext() { return this; } private void getVolume() { mClingPlayControl.getVolume(new ControlReceiveCallback() { @Override public void receive(IResponse response) { Object responseResponse = response.getResponse(); if (responseResponse instanceof ClingVolumeResponse) { ClingVolumeResponse resp = (ClingVolumeResponse) response; currentVolume = resp.getResponse(); } } @Override public void success(IResponse response) { } @Override public void fail(IResponse response) { } }); } private void initData(String playUrl, String playTitle, String headers) { tvVideoName.setText(playTitle); playStatus.setText("正在缓冲..."); playNew(playUrl, playTitle, headers); Log.d(TAG, "initData: playUrl==>" + playUrl + ", playTitle==>" + playTitle + ", headers==>" + headers); } private void initListener() { playBt.setOnClickListener(v -> { if (isPlaying) { pause(); playBt.setSelected(false); playStatus.setText("暂停播放..."); } else { continuePlay(); playBt.setSelected(true); playStatus.setText("正在播放"); } }); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int newProgress = (int) (hostLength * (progress * 0.01f)); String time = ModelUtil.toTimeString(newProgress); currTime.setText(time); } @Override public void onStartTrackingTouch(SeekBar seekBar) { isSeeking = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { int currentProgress = seekBar.getProgress(); // 转为毫秒 isSeeking = false; int progress = (int) (hostLength * 1000 * (currentProgress * 0.01f)); mClingPlayControl.seek(progress, new ControlCallback() { @Override public void success(IResponse response) { Log.e(TAG, "seek success"); } @Override public void fail(IResponse response) { Log.e(TAG, "seek fail"); } }); } }); // } private String getPlayUrl(String url, String headers) { if (StringUtil.isEmpty(headers)) { return url; } String device = DlanListPopUtil.instance().getUsedDeviceName(); if (StringUtil.isNotEmpty(device) && (device.contains("波澜投屏2") || device.contains("Macast"))) { //拼接header return url + "##|" + headers; } return url; } private void playNew(String url, String playTitle, String headers) { url = getPlayUrl(url, headers); Log.d(TAG, "playNew start: " + url); mClingPlayControl.playNew(url, playTitle, new ControlCallback() { @Override public void success(IResponse response) { Log.d(TAG, "playNew success: "); isPlaying = true; playBt.setSelected(true);
package org.mozilla.xiu.browser.dlan; public class MediaPlayActivity extends AppCompatActivity { private static final String TAG = "MediaPlayActivity"; /** * 连接设备状态: 播放状态 */ public static final int PLAY_ACTION = 0xa1; /** * 连接设备状态: 暂停状态 */ public static final int PAUSE_ACTION = 0xa2; /** * 连接设备状态: 停止状态 */ public static final int STOP_ACTION = 0xa3; /** * 连接设备状态: 转菊花状态 */ public static final int TRANSITIONING_ACTION = 0xa4; /** * 获取进度 */ public static final int EXTRA_POSITION = 0xa5; /** * 投放失败 */ public static final int ERROR_ACTION = 0xa6; /** * tv端播放完成 */ public static final int ACTION_PLAY_COMPLETE = 0xa7; public static final int ACTION_POSITION_CALLBACK = 0xa8; private TextView tvVideoName; private Context mContext; private Handler mHandler = new InnerHandler(); private Timer timer = null; private boolean isPlaying = false; private ClingPlayControl mClingPlayControl = new ClingPlayControl();//投屏控制器 private AppCompatSeekBar seekBar; private ImageView playBt; private TextView currTime; private TextView countTime; private long hostLength; private ImageView plusVolume; private ImageView reduceVolume; private int currentVolume; private TextView playStatus; private boolean isSeeking = false; private int pos = -1; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { BaseActivity.checkForceDarkMode(this); super.onCreate(savedInstanceState); mContext = this; initStatusBar(); setContentView(R.layout.activity_dlan_play_layout); initView(); initListener(); registerReceivers(); String playUrl = getIntent().getStringExtra(DLandataInter.Key.PLAYURL); String playTitle = getIntent().getStringExtra(DLandataInter.Key.PLAY_TITLE); String headers = getIntent().getStringExtra(DLandataInter.Key.HEADER); pos = getIntent().getIntExtra(DLandataInter.Key.PLAY_POS, -1); initData(playUrl, playTitle, headers); if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } } private void initStatusBar() { requestWindowFeature(Window.FEATURE_NO_TITLE); //去除状态栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } private void initView() { tvVideoName = findViewById(R.id.text_content_title); playBt = findViewById(R.id.img_play); findViewById(R.id.backup).setOnClickListener(v -> finish()); seekBar = findViewById(R.id.seek_bar_progress); currTime = findViewById(R.id.text_play_time); countTime = findViewById(R.id.text_play_max_time); playStatus = findViewById(R.id.play_status); plusVolume = findViewById(R.id.plus_volume); reduceVolume = findViewById(R.id.reduce_volume); getVolume(); plusVolume.setOnClickListener(v -> { if (currentVolume >= 96) { return; } currentVolume += 4; mClingPlayControl.setVolume(currentVolume, new ControlCallback() { @Override public void success(IResponse response) { getVolume(); } @Override public void fail(IResponse response) { getVolume(); } }); }); reduceVolume.setOnClickListener(v -> { if (currentVolume <= 4) { return; } currentVolume -= 4; mClingPlayControl.setVolume(currentVolume, new ControlCallback() { @Override public void success(IResponse response) { getVolume(); } @Override public void fail(IResponse response) { } }); }); findViewById(R.id.img_next).setOnClickListener(v -> { ToastMgr.shortCenter(getContext(), "暂不支持此功能"); }); findViewById(R.id.img_previous).setOnClickListener(v -> { ToastMgr.shortCenter(getContext(), "嘿嘿,我是个假按钮~"); }); } private void next() { } @Subscribe(threadMode = ThreadMode.MAIN) public void onDlan(DlanPlayEvent event) { initData(event.getUrl(), event.getTitle(), event.getHeaders()); } private Context getContext() { return this; } private void getVolume() { mClingPlayControl.getVolume(new ControlReceiveCallback() { @Override public void receive(IResponse response) { Object responseResponse = response.getResponse(); if (responseResponse instanceof ClingVolumeResponse) { ClingVolumeResponse resp = (ClingVolumeResponse) response; currentVolume = resp.getResponse(); } } @Override public void success(IResponse response) { } @Override public void fail(IResponse response) { } }); } private void initData(String playUrl, String playTitle, String headers) { tvVideoName.setText(playTitle); playStatus.setText("正在缓冲..."); playNew(playUrl, playTitle, headers); Log.d(TAG, "initData: playUrl==>" + playUrl + ", playTitle==>" + playTitle + ", headers==>" + headers); } private void initListener() { playBt.setOnClickListener(v -> { if (isPlaying) { pause(); playBt.setSelected(false); playStatus.setText("暂停播放..."); } else { continuePlay(); playBt.setSelected(true); playStatus.setText("正在播放"); } }); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int newProgress = (int) (hostLength * (progress * 0.01f)); String time = ModelUtil.toTimeString(newProgress); currTime.setText(time); } @Override public void onStartTrackingTouch(SeekBar seekBar) { isSeeking = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { int currentProgress = seekBar.getProgress(); // 转为毫秒 isSeeking = false; int progress = (int) (hostLength * 1000 * (currentProgress * 0.01f)); mClingPlayControl.seek(progress, new ControlCallback() { @Override public void success(IResponse response) { Log.e(TAG, "seek success"); } @Override public void fail(IResponse response) { Log.e(TAG, "seek fail"); } }); } }); // } private String getPlayUrl(String url, String headers) { if (StringUtil.isEmpty(headers)) { return url; } String device = DlanListPopUtil.instance().getUsedDeviceName(); if (StringUtil.isNotEmpty(device) && (device.contains("波澜投屏2") || device.contains("Macast"))) { //拼接header return url + "##|" + headers; } return url; } private void playNew(String url, String playTitle, String headers) { url = getPlayUrl(url, headers); Log.d(TAG, "playNew start: " + url); mClingPlayControl.playNew(url, playTitle, new ControlCallback() { @Override public void success(IResponse response) { Log.d(TAG, "playNew success: "); isPlaying = true; playBt.setSelected(true);
ClingManager.getInstance().registerAVTransport(mContext);
7
2023-11-10 14:28:40+00:00
24k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/commandexecutors/ShrineCommandExecutor.java
[ { "identifier": "Deity", "path": "src/main/java/me/xidentified/devotions/Deity.java", "snippet": "public class Deity {\n private final Devotions plugin;\n // Getter methods below\n @Getter public final String name;\n @Getter private final String lore;\n @Getter private final String alignm...
import de.cubbossa.tinytranslations.GlobalMessages; import me.xidentified.devotions.Deity; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.Shrine; import me.xidentified.devotions.managers.DevotionManager; import me.xidentified.devotions.managers.FavorManager; import me.xidentified.devotions.managers.ShrineManager; import me.xidentified.devotions.util.Messages; import net.kyori.adventure.text.minimessage.tag.resolver.Formatter; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; import org.jetbrains.annotations.NotNull; import java.util.*;
15,352
package me.xidentified.devotions.commandexecutors; public class ShrineCommandExecutor implements CommandExecutor, Listener, TabCompleter { private final Map<Player, Deity> pendingShrineDesignations = new HashMap<>(); private final Map<UUID, Boolean> pendingShrineRemovals = new HashMap<>(); private final DevotionManager devotionManager; private final ShrineManager shrineManager; public ShrineCommandExecutor(DevotionManager devotionManager, ShrineManager shrineManager) { this.devotionManager = devotionManager; this.shrineManager = shrineManager; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length > 0) { if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("devotions.shrine.list")) { displayShrineList(player); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_LIST); } return true; } else if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("devotions.shrine.remove")) { pendingShrineRemovals.put(player.getUniqueId(), true); Devotions.getInstance().sendMessage(player, Messages.SHRINE_RC_TO_REMOVE); //Bukkit.getLogger().log(Level.WARNING, "Current pendingShrineRemovals map: " + pendingShrineRemovals); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_REMOVE); } return true; } } else if (player.hasPermission("devotions.shrine.set")) { int currentShrineCount = shrineManager.getShrineCount(player); int shrineLimit = shrineManager.getPlugin().getShrineLimit(); if (currentShrineCount >= shrineLimit) { Devotions.getInstance().sendMessage(player, Messages.SHRINE_LIMIT_REACHED.formatted( Formatter.number("limit", shrineLimit) )); return true; } // If the player doesn't follow a deity, don't let them make a shrine
package me.xidentified.devotions.commandexecutors; public class ShrineCommandExecutor implements CommandExecutor, Listener, TabCompleter { private final Map<Player, Deity> pendingShrineDesignations = new HashMap<>(); private final Map<UUID, Boolean> pendingShrineRemovals = new HashMap<>(); private final DevotionManager devotionManager; private final ShrineManager shrineManager; public ShrineCommandExecutor(DevotionManager devotionManager, ShrineManager shrineManager) { this.devotionManager = devotionManager; this.shrineManager = shrineManager; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length > 0) { if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("devotions.shrine.list")) { displayShrineList(player); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_LIST); } return true; } else if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("devotions.shrine.remove")) { pendingShrineRemovals.put(player.getUniqueId(), true); Devotions.getInstance().sendMessage(player, Messages.SHRINE_RC_TO_REMOVE); //Bukkit.getLogger().log(Level.WARNING, "Current pendingShrineRemovals map: " + pendingShrineRemovals); } else { Devotions.getInstance().sendMessage(player, Messages.SHRINE_NO_PERM_REMOVE); } return true; } } else if (player.hasPermission("devotions.shrine.set")) { int currentShrineCount = shrineManager.getShrineCount(player); int shrineLimit = shrineManager.getPlugin().getShrineLimit(); if (currentShrineCount >= shrineLimit) { Devotions.getInstance().sendMessage(player, Messages.SHRINE_LIMIT_REACHED.formatted( Formatter.number("limit", shrineLimit) )); return true; } // If the player doesn't follow a deity, don't let them make a shrine
FavorManager favorManager = devotionManager.getPlayerDevotion(player.getUniqueId());
4
2023-11-10 07:03:24+00:00
24k
SplitfireUptown/datalinkx
flinkx/flinkx-hive/flinkx-hive-writer/src/main/java/com/dtstack/flinkx/hive/writer/HiveOutputFormat.java
[ { "identifier": "WriteRecordException", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/exception/WriteRecordException.java", "snippet": "public class WriteRecordException extends Exception {\n\n private int colIndex = -1;\n private Row row;\n\n public int getColIndex() {\n ...
import com.dtstack.flinkx.exception.WriteRecordException; import com.dtstack.flinkx.hdfs.writer.BaseHdfsOutputFormat; import com.dtstack.flinkx.hdfs.writer.HdfsOutputFormatBuilder; import com.dtstack.flinkx.hive.TableInfo; import com.dtstack.flinkx.hive.TimePartitionFormat; import com.dtstack.flinkx.hive.util.HiveDbUtil; import com.dtstack.flinkx.hive.util.HiveUtil; import com.dtstack.flinkx.hive.util.PathConverterUtil; import com.dtstack.flinkx.outputformat.BaseRichOutputFormat; import com.dtstack.flinkx.restore.FormatState; import com.dtstack.flinkx.util.ExceptionUtil; import com.dtstack.flinkx.util.GsonUtil; import com.google.gson.JsonSyntaxException; import org.apache.commons.collections.MapUtils; import org.apache.commons.math3.util.Pair; import org.apache.flink.types.Row; import org.apache.hadoop.conf.Configuration; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import static com.dtstack.flinkx.hive.HiveConfigKeys.KEY_SCHEMA; import static com.dtstack.flinkx.hive.HiveConfigKeys.KEY_TABLE;
18,260
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.hive.writer; /** * @author toutian */ public class HiveOutputFormat extends BaseRichOutputFormat { private static final String SP = "/"; /** * hdfs高可用配置 */ protected Map<String, Object> hadoopConfig; protected String fileType; /** * 写入模式 */ protected String writeMode; /** * 压缩方式 */ protected String compress; protected String defaultFs; protected String delimiter; protected String charsetName = "UTF-8"; protected Configuration conf; protected int rowGroupSize; protected long maxFileSize; /* ----------以上hdfs插件参数----------- */ protected Map<String, TableInfo> tableInfos; protected Map<String, String> distributeTableMapping; protected String partition; protected String partitionType; protected String partitionPath; protected String tbPath; protected long bufferSize; protected String jdbcUrl; protected String username; protected String password; protected String tableBasePath; protected boolean autoCreateTable; protected String schema; private transient HiveUtil hiveUtil; private transient TimePartitionFormat partitionFormat; private org.apache.flink.configuration.Configuration parameters; private int taskNumber; private int numTasks; private Map<String, TableInfo> tableCache;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.hive.writer; /** * @author toutian */ public class HiveOutputFormat extends BaseRichOutputFormat { private static final String SP = "/"; /** * hdfs高可用配置 */ protected Map<String, Object> hadoopConfig; protected String fileType; /** * 写入模式 */ protected String writeMode; /** * 压缩方式 */ protected String compress; protected String defaultFs; protected String delimiter; protected String charsetName = "UTF-8"; protected Configuration conf; protected int rowGroupSize; protected long maxFileSize; /* ----------以上hdfs插件参数----------- */ protected Map<String, TableInfo> tableInfos; protected Map<String, String> distributeTableMapping; protected String partition; protected String partitionType; protected String partitionPath; protected String tbPath; protected long bufferSize; protected String jdbcUrl; protected String username; protected String password; protected String tableBasePath; protected boolean autoCreateTable; protected String schema; private transient HiveUtil hiveUtil; private transient TimePartitionFormat partitionFormat; private org.apache.flink.configuration.Configuration parameters; private int taskNumber; private int numTasks; private Map<String, TableInfo> tableCache;
private Map<String, BaseHdfsOutputFormat> outputFormats;
1
2023-11-16 02:22:52+00:00
24k
bdmarius/jndarray-toolbox
src/main/java/internals/TensorDot.java
[ { "identifier": "JNumDataType", "path": "src/main/java/utils/JNumDataType.java", "snippet": "public enum JNumDataType {\n BYTE,\n SHORT,\n INT,\n LONG,\n FLOAT,\n DOUBLE\n}" }, { "identifier": "NumberUtils", "path": "src/main/java/utils/NumberUtils.java", "snippet": "pu...
import utils.JNumDataType; import utils.NumberUtils; import utils.TypeUtils; import java.util.Arrays;
20,184
package internals; public class TensorDot { /** * If either one of the tensors is a scalar (shape length is 0), then TensorArithmetic.multiply is returned. * If both tensors are 1-D, inner product is returned * If both tensors are 2-D, matrix multiplication is returned * If first tensor is N-D and the second tensor is 1-D, then: * - a (N-1)-D tensor is returned * - The difference between the first tensor shape and the result shape is that the N-th element from the first * tensor shape is dropped. Rest of elements remain the same * - the result tensor is the sum product over the last axis of the first tensor and the second tensor * If first tensor is N-D and the second tensor is M-D (M >= 2), then: * - a (M+N-2)-D tensor is returned * - The new tensor looks like this: we copy the first N-1 elements from the first tensor shape, * then we continue with the elements from the second tensor shape, except for the second-to-last one * - the result tensor is the sum product over the last axis of the first tensor and the second-to-last * dimension of the first tensor */ static Tensor dot(Tensor firstTensor, Tensor secondTensor) { int[] firstTensorShape = firstTensor.getShape(); int[] secondTensorShape = secondTensor.getShape(); if (firstTensorShape.length == 0 || secondTensorShape.length == 0) { return TensorArithmetic.multiply(firstTensor, secondTensor); } if (firstTensorShape.length == 1 && secondTensorShape.length == 1) { return doInnerProduct(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } if (firstTensorShape.length == 2 && secondTensorShape.length == 2) { return doMatrixMultiplication(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } if (firstTensorShape.length >= 2 && secondTensorShape.length == 1) { return doSumProductWith1D(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } return doSumProduct(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } private static Tensor doInnerProduct(Tensor firstTensor, int[] firstTensorShape, Tensor secondTensor, int[] secondTensorShape) { if (firstTensorShape[0] != secondTensorShape[0]) { throw new IllegalArgumentException( String.format("Shapes %s and %s do not match for dot operation because " + "%s (dim 0) != %s (dim 0)", Arrays.toString(firstTensorShape), Arrays.toString(secondTensorShape), firstTensorShape[0], secondTensorShape[0])); } JNumDataType resultDataType = TypeUtils.getHighestDataType(firstTensor.getDataType(), secondTensor.getDataType()); Number innerProduct = TypeUtils.getDefaultValue(resultDataType); for (int i = 0; i < firstTensorShape[0]; i++) {
package internals; public class TensorDot { /** * If either one of the tensors is a scalar (shape length is 0), then TensorArithmetic.multiply is returned. * If both tensors are 1-D, inner product is returned * If both tensors are 2-D, matrix multiplication is returned * If first tensor is N-D and the second tensor is 1-D, then: * - a (N-1)-D tensor is returned * - The difference between the first tensor shape and the result shape is that the N-th element from the first * tensor shape is dropped. Rest of elements remain the same * - the result tensor is the sum product over the last axis of the first tensor and the second tensor * If first tensor is N-D and the second tensor is M-D (M >= 2), then: * - a (M+N-2)-D tensor is returned * - The new tensor looks like this: we copy the first N-1 elements from the first tensor shape, * then we continue with the elements from the second tensor shape, except for the second-to-last one * - the result tensor is the sum product over the last axis of the first tensor and the second-to-last * dimension of the first tensor */ static Tensor dot(Tensor firstTensor, Tensor secondTensor) { int[] firstTensorShape = firstTensor.getShape(); int[] secondTensorShape = secondTensor.getShape(); if (firstTensorShape.length == 0 || secondTensorShape.length == 0) { return TensorArithmetic.multiply(firstTensor, secondTensor); } if (firstTensorShape.length == 1 && secondTensorShape.length == 1) { return doInnerProduct(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } if (firstTensorShape.length == 2 && secondTensorShape.length == 2) { return doMatrixMultiplication(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } if (firstTensorShape.length >= 2 && secondTensorShape.length == 1) { return doSumProductWith1D(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } return doSumProduct(firstTensor, firstTensorShape, secondTensor, secondTensorShape); } private static Tensor doInnerProduct(Tensor firstTensor, int[] firstTensorShape, Tensor secondTensor, int[] secondTensorShape) { if (firstTensorShape[0] != secondTensorShape[0]) { throw new IllegalArgumentException( String.format("Shapes %s and %s do not match for dot operation because " + "%s (dim 0) != %s (dim 0)", Arrays.toString(firstTensorShape), Arrays.toString(secondTensorShape), firstTensorShape[0], secondTensorShape[0])); } JNumDataType resultDataType = TypeUtils.getHighestDataType(firstTensor.getDataType(), secondTensor.getDataType()); Number innerProduct = TypeUtils.getDefaultValue(resultDataType); for (int i = 0; i < firstTensorShape[0]; i++) {
Number tempProduct = NumberUtils.multiplyElements(firstTensor.getDataType(),
1
2023-11-13 19:53:02+00:00
24k
raphael-goetz/betterflowers
src/main/java/com/uroria/betterflowers/menus/FlowerCreationMenu.java
[ { "identifier": "BetterFlowers", "path": "src/main/java/com/uroria/betterflowers/BetterFlowers.java", "snippet": "@Getter\npublic final class BetterFlowers extends JavaPlugin {\n\n private final FlowerManager flowerManager;\n private final LanguageManager languageManager;\n\n public BetterFlowe...
import com.uroria.betterflowers.BetterFlowers; import com.uroria.betterflowers.data.FlowerGroupData; import com.uroria.betterflowers.flowers.SingleFlower; import com.uroria.betterflowers.flowers.placable.FlowerGroup; import com.uroria.betterflowers.managers.LanguageManager; import com.uroria.betterflowers.utils.BukkitPlayerInventory; import com.uroria.betterflowers.utils.CandleCollection; import com.uroria.betterflowers.utils.FlowerCollection; import com.uroria.betterflowers.data.FlowerData; import com.uroria.betterflowers.utils.ItemBuilder; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
19,975
package com.uroria.betterflowers.menus; public final class FlowerCreationMenu extends BukkitPlayerInventory { private final LanguageManager languageManager; private final List<FlowerData> personalFlower; private final List<Boolean> isGroup; private final List<Boolean> randomizer; private final Player player; private final ItemStack active; private final ItemStack notActive; private final ItemStack wholeCategoryRan; private final ItemStack wholeCategory; private final BetterFlowers betterFlowers; public FlowerCreationMenu(Player player, BetterFlowers betterFlowers) { super(betterFlowers.getLanguageManager().getComponent("gui.flower.title"), 6); this.player = player; this.betterFlowers = betterFlowers; this.languageManager = betterFlowers.getLanguageManager(); this.personalFlower = new ArrayList<>(); this.randomizer = new ArrayList<>(); this.isGroup = new ArrayList<>();
package com.uroria.betterflowers.menus; public final class FlowerCreationMenu extends BukkitPlayerInventory { private final LanguageManager languageManager; private final List<FlowerData> personalFlower; private final List<Boolean> isGroup; private final List<Boolean> randomizer; private final Player player; private final ItemStack active; private final ItemStack notActive; private final ItemStack wholeCategoryRan; private final ItemStack wholeCategory; private final BetterFlowers betterFlowers; public FlowerCreationMenu(Player player, BetterFlowers betterFlowers) { super(betterFlowers.getLanguageManager().getComponent("gui.flower.title"), 6); this.player = player; this.betterFlowers = betterFlowers; this.languageManager = betterFlowers.getLanguageManager(); this.personalFlower = new ArrayList<>(); this.randomizer = new ArrayList<>(); this.isGroup = new ArrayList<>();
this.active = new ItemBuilder(Material.LIME_STAINED_GLASS_PANE)
8
2023-11-18 16:13:59+00:00
24k
jpdev01/asaasSdk
src/main/java/io/github/jpdev/asaassdk/doc/Examples.java
[ { "identifier": "Asaas", "path": "src/main/java/io/github/jpdev/asaassdk/http/Asaas.java", "snippet": "public class Asaas {\n\n private static final String ENDPOINT_PRODUCTION = \"https://www.asaas.com/api/v3\";\n private static final String ENDPOINT_SANDBOX = \"https://sandbox.asaas.com/api/v3\";...
import io.github.jpdev.asaassdk.http.Asaas; import io.github.jpdev.asaassdk.rest.accounts.Account; import io.github.jpdev.asaassdk.rest.accounts.AccountCreator; import io.github.jpdev.asaassdk.rest.action.ResourceSet; import io.github.jpdev.asaassdk.rest.bill.Bill; import io.github.jpdev.asaassdk.rest.commons.DeletedResource; import io.github.jpdev.asaassdk.rest.customeraccount.CustomerAccount; import io.github.jpdev.asaassdk.rest.finance.FinanceBalance; import io.github.jpdev.asaassdk.rest.financialtransaction.FinancialTransaction; import io.github.jpdev.asaassdk.rest.installment.Installment; import io.github.jpdev.asaassdk.rest.invoice.Invoice; import io.github.jpdev.asaassdk.rest.invoice.Taxes; import io.github.jpdev.asaassdk.rest.myaccount.accountnumber.AccountNumber; import io.github.jpdev.asaassdk.rest.myaccount.commercialinfo.CommercialInfo; import io.github.jpdev.asaassdk.rest.myaccount.fee.AccountFee; import io.github.jpdev.asaassdk.rest.myaccount.status.MyAccountStatus; import io.github.jpdev.asaassdk.rest.notification.NotificationConfig; import io.github.jpdev.asaassdk.rest.payment.Payment; import io.github.jpdev.asaassdk.rest.payment.enums.PaymentLinkChargeType; import io.github.jpdev.asaassdk.rest.payment.enums.PaymentStatus; import io.github.jpdev.asaassdk.rest.payment.identificationfield.PaymentIdentificationField; import io.github.jpdev.asaassdk.rest.payment.status.PaymentStatusData; import io.github.jpdev.asaassdk.rest.paymentlink.PaymentLink; import io.github.jpdev.asaassdk.rest.pix.addresskey.PixAddressKey; import io.github.jpdev.asaassdk.rest.pix.enums.PixAddressKeyStatus; import io.github.jpdev.asaassdk.rest.pix.enums.PixAddressKeyType; import io.github.jpdev.asaassdk.rest.pix.enums.PixTransactionType; import io.github.jpdev.asaassdk.rest.pix.qrcode.PixQrCode; import io.github.jpdev.asaassdk.rest.pix.qrcode.decode.PixDecodedQrCode; import io.github.jpdev.asaassdk.rest.pix.transaction.PixTransaction; import io.github.jpdev.asaassdk.rest.transfer.Transfer; import io.github.jpdev.asaassdk.rest.transfer.children.BankAccountSetting; import io.github.jpdev.asaassdk.rest.transfer.children.BankAccountType; import io.github.jpdev.asaassdk.rest.transfer.children.BankSetting; import io.github.jpdev.asaassdk.utils.BillingType; import io.github.jpdev.asaassdk.utils.Money; import java.math.BigDecimal; import java.util.Date;
20,949
package io.github.jpdev.asaassdk.doc; public class Examples { public static void main(String[] args) { Asaas.init(Secret.getAccessToken()); myStatus(); subAccount(); } private void pixTransaction() { ResourceSet<PixTransaction> pixTransactionResourceSet = PixTransaction.reader().read(); PixTransaction pixTransaction = PixTransaction.fetcher("bc515f74-d5c7-4bc2-93e5-3bafc0a9b15d").fetch(); PixTransaction cancelledPixTransaction = PixTransaction.canceller("35363f6e-93e2-11ec-b9d9-96f4053b1bd4").create(); ResourceSet<PixTransaction> pixTransactionDebitResourceSet = PixTransaction.reader() .setType(PixTransactionType.DEBIT) .read(); } private void pixAddressKey() { ResourceSet<PixAddressKey> pixAddressKeyResourceSet = PixAddressKey.reader() .setStatus(PixAddressKeyStatus.ACTIVE) .setLimit(1) .read(); PixAddressKey.creator().setType(PixAddressKeyType.EVP).create(); PixAddressKey.reader().read(); } private void decodePixQrCode() { PixDecodedQrCode decodedQrCode = PixDecodedQrCode.decoder() .setPayload("payload") .create(); } private void transfer() { ResourceSet<Transfer> transferList = Transfer.reader().read(); Transfer transfer = Transfer.pixAddressKeyCreator() .setPixAddressKey("09414368965") .setValue(Money.create(0.01)) .setDescription("teste") .setPixAddressKeyType(PixAddressKeyType.CPF) .create(); System.out.println(transfer.getValue().toString()); Date birthDate = new Date(); BankAccountSetting bankAccountSetting = new BankAccountSetting() .setBank( new BankSetting().setCode("085") ) .setAccountName("Paulo") .setOwnerName("Paulo") .setOwnerBirthDate(new Date()) .setCpfCnpj("06928316000124") .setAgency("0108") .setAccount("10895") .setAccountDigit("5") .setBankAccountType(BankAccountType.CONTA_CORRENTE); Transfer pixManualTransfer = Transfer.pixManualCreator() .setBankAccount(bankAccountSetting) .setValue(Money.create(new BigDecimal(1.01))) .create(); System.out.println(pixManualTransfer.getValue().toString()); Transfer ted = Transfer.tedCreator() .setBankAccount(bankAccountSetting) .setValue(Money.create(new BigDecimal(1.01))) .create(); } private void bill() { Bill bill = Bill.creator() .setIdentificationField("25794150099003551916515000211407100000000000000") .create(); } private void pixStaticQrCode() { PixQrCode qrCode = PixQrCode .creator() .setAddressKey(PixAddressKey.reader().read().getData().get(0).key) .setDescription("teste") .setValue(Money.create(0.01)) .create(); System.out.printf(qrCode.payload); } private void payment() { Payment payment = Payment.creator() .setCustomer("cus_000072683114") .setBillingType(BillingType.PIX) .setDueDate(new Date()) .setInstallmentCount(2) .setInstallmentValue(Money.create(50)) .setDescription("Teste") .create(); ResourceSet<Payment> paymentResourceSet = Payment.reader() .setStatus(PaymentStatus.RECEIVED) .setStartPaymentDate(new Date()) .setFinishDueDate(new Date()) .read(); DeletedResource paymentDeleted = Payment.deleter(payment.getId()).delete(); payment = Payment.restorer(payment.getId()).create(); PaymentStatusData paymentStatusData = Payment.statusFetcher("pay_9087711026766517").fetch(); PaymentIdentificationField linhaDigitavel = Payment.identificationFieldFetcher("pay_9087711026766517").fetch(); } private void customerAccount() { CustomerAccount.fetcher("cus_000072683044").fetch(); CustomerAccount customerAccount = CustomerAccount.creator() .setName("criado via API") .setCpfCnpj("10030823005") .create(); } private void notification() { ResourceSet<NotificationConfig> notificationConfigList = NotificationConfig.customerAccountReader("cus_000072683044").read(); NotificationConfig.updater(notificationConfigList.getData().get(0).getId()).setEnabled(false).update(); } private void paymentLink() {
package io.github.jpdev.asaassdk.doc; public class Examples { public static void main(String[] args) { Asaas.init(Secret.getAccessToken()); myStatus(); subAccount(); } private void pixTransaction() { ResourceSet<PixTransaction> pixTransactionResourceSet = PixTransaction.reader().read(); PixTransaction pixTransaction = PixTransaction.fetcher("bc515f74-d5c7-4bc2-93e5-3bafc0a9b15d").fetch(); PixTransaction cancelledPixTransaction = PixTransaction.canceller("35363f6e-93e2-11ec-b9d9-96f4053b1bd4").create(); ResourceSet<PixTransaction> pixTransactionDebitResourceSet = PixTransaction.reader() .setType(PixTransactionType.DEBIT) .read(); } private void pixAddressKey() { ResourceSet<PixAddressKey> pixAddressKeyResourceSet = PixAddressKey.reader() .setStatus(PixAddressKeyStatus.ACTIVE) .setLimit(1) .read(); PixAddressKey.creator().setType(PixAddressKeyType.EVP).create(); PixAddressKey.reader().read(); } private void decodePixQrCode() { PixDecodedQrCode decodedQrCode = PixDecodedQrCode.decoder() .setPayload("payload") .create(); } private void transfer() { ResourceSet<Transfer> transferList = Transfer.reader().read(); Transfer transfer = Transfer.pixAddressKeyCreator() .setPixAddressKey("09414368965") .setValue(Money.create(0.01)) .setDescription("teste") .setPixAddressKeyType(PixAddressKeyType.CPF) .create(); System.out.println(transfer.getValue().toString()); Date birthDate = new Date(); BankAccountSetting bankAccountSetting = new BankAccountSetting() .setBank( new BankSetting().setCode("085") ) .setAccountName("Paulo") .setOwnerName("Paulo") .setOwnerBirthDate(new Date()) .setCpfCnpj("06928316000124") .setAgency("0108") .setAccount("10895") .setAccountDigit("5") .setBankAccountType(BankAccountType.CONTA_CORRENTE); Transfer pixManualTransfer = Transfer.pixManualCreator() .setBankAccount(bankAccountSetting) .setValue(Money.create(new BigDecimal(1.01))) .create(); System.out.println(pixManualTransfer.getValue().toString()); Transfer ted = Transfer.tedCreator() .setBankAccount(bankAccountSetting) .setValue(Money.create(new BigDecimal(1.01))) .create(); } private void bill() { Bill bill = Bill.creator() .setIdentificationField("25794150099003551916515000211407100000000000000") .create(); } private void pixStaticQrCode() { PixQrCode qrCode = PixQrCode .creator() .setAddressKey(PixAddressKey.reader().read().getData().get(0).key) .setDescription("teste") .setValue(Money.create(0.01)) .create(); System.out.printf(qrCode.payload); } private void payment() { Payment payment = Payment.creator() .setCustomer("cus_000072683114") .setBillingType(BillingType.PIX) .setDueDate(new Date()) .setInstallmentCount(2) .setInstallmentValue(Money.create(50)) .setDescription("Teste") .create(); ResourceSet<Payment> paymentResourceSet = Payment.reader() .setStatus(PaymentStatus.RECEIVED) .setStartPaymentDate(new Date()) .setFinishDueDate(new Date()) .read(); DeletedResource paymentDeleted = Payment.deleter(payment.getId()).delete(); payment = Payment.restorer(payment.getId()).create(); PaymentStatusData paymentStatusData = Payment.statusFetcher("pay_9087711026766517").fetch(); PaymentIdentificationField linhaDigitavel = Payment.identificationFieldFetcher("pay_9087711026766517").fetch(); } private void customerAccount() { CustomerAccount.fetcher("cus_000072683044").fetch(); CustomerAccount customerAccount = CustomerAccount.creator() .setName("criado via API") .setCpfCnpj("10030823005") .create(); } private void notification() { ResourceSet<NotificationConfig> notificationConfigList = NotificationConfig.customerAccountReader("cus_000072683044").read(); NotificationConfig.updater(notificationConfigList.getData().get(0).getId()).setEnabled(false).update(); } private void paymentLink() {
PaymentLink link = PaymentLink.fetcher("725104409743").fetch();
22
2023-11-12 01:19:17+00:00
24k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/client/gui/hud/items/HudItemHydration.java
[ { "identifier": "Gui_EventManager", "path": "src/main/java/enviromine/client/gui/Gui_EventManager.java", "snippet": "@SideOnly(Side.CLIENT)\npublic class Gui_EventManager\n{\n\n\tint width, height;\n\n\t//Render HUD\n\t//Render Player\n\n\t// Button Functions\n\tGuiButton enviromine;\n\n\t// Captures th...
import org.lwjgl.opengl.GL11; import enviromine.client.gui.Gui_EventManager; import enviromine.client.gui.UI_Settings; import enviromine.client.gui.hud.HUDRegistry; import enviromine.client.gui.hud.HudItem; import enviromine.core.EM_Settings; import enviromine.utils.Alignment; import enviromine.utils.EnviroUtils; import enviromine.utils.RenderAssist; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector;
18,790
package enviromine.client.gui.hud.items; public class HudItemHydration extends HudItem { @Override public String getName() { return "Hydration"; } public String getNameLoc() { return StatCollector.translateToLocal("options.enviromine.hud.hydration"); } @Override public String getButtonLabel() { return getNameLoc() + "Bar"; } @Override
package enviromine.client.gui.hud.items; public class HudItemHydration extends HudItem { @Override public String getName() { return "Hydration"; } public String getNameLoc() { return StatCollector.translateToLocal("options.enviromine.hud.hydration"); } @Override public String getButtonLabel() { return getNameLoc() + "Bar"; } @Override
public Alignment getDefaultAlignment() {
5
2023-11-16 18:15:29+00:00
24k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/render/GenericGunRenderer.java
[ { "identifier": "ClientProxy", "path": "src/main/java/sheridan/gunscraft/ClientProxy.java", "snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa...
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.AbstractClientPlayerEntity; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.PlayerRenderer; import net.minecraft.client.renderer.model.ItemCameraTransforms; import net.minecraft.client.renderer.model.ModelRenderer; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.vector.Matrix4f; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.lwjgl.opengl.GL11; import sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationData; import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationHandler; import sheridan.gunscraft.capability.CapabilityHandler; import sheridan.gunscraft.events.PlayerEvents; import sheridan.gunscraft.events.RenderEvents; import sheridan.gunscraft.items.attachments.util.GunAttachmentSlot; import sheridan.gunscraft.items.attachments.util.GunRenderContext; import sheridan.gunscraft.items.attachments.util.NBTAttachmentsMap; import sheridan.gunscraft.items.guns.IGenericGun; import sheridan.gunscraft.model.IGunModel; import sheridan.gunscraft.render.bulletShell.BulletShellRenderer; import sheridan.gunscraft.render.fx.muzzleFlash.CommonMuzzleFlash; import sheridan.gunscraft.render.fx.muzzleFlash.MuzzleFlash; import sheridan.gunscraft.render.fx.muzzleFlash.MuzzleFlashTrans; import static sheridan.gunscraft.ClientProxy.TICK_LEN; import static sheridan.gunscraft.ClientProxy.bulletSpread;
20,410
package sheridan.gunscraft.render; @OnlyIn(Dist.CLIENT) public class GenericGunRenderer implements IGunRender{ private static final Matrix4f DEFAULT_FIRST_PERSON_FOV_MATRIX; public static final float DEFAULT_FIRST_PERSON_FOV = 56.75f; public PlayerEntity player; static { DEFAULT_FIRST_PERSON_FOV_MATRIX = new Matrix4f(); DEFAULT_FIRST_PERSON_FOV_MATRIX.setIdentity(); Minecraft minecraft = Minecraft.getInstance(); DEFAULT_FIRST_PERSON_FOV_MATRIX.mul(Matrix4f.perspective(DEFAULT_FIRST_PERSON_FOV, (float) minecraft.getMainWindow().getFramebufferWidth() / (float) minecraft.getMainWindow().getFramebufferHeight(), 0.05F, (float) minecraft.gameSettings.renderDistanceChunks * 64F)); } public void justRenderModel(ItemStack itemStackIn, ItemCameraTransforms.TransformType transformTypeIn, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int combinedLightIn, int combinedOverlayIn, IGenericGun gun, IGunModel model, TransformData transformData) { if (model != null) { if (transformData != null) { matrixStackIn.push(); transformData.applyTransform(transformTypeIn, matrixStackIn, false, 0); int fireMode = gun.getFireMode(itemStackIn); int ammoLeft = gun.getAmmoLeft(itemStackIn); long fireDis = (gun.getShootDelay() - 1) * TICK_LEN; GunRenderContext context = NBTAttachmentsMap.renderAttachments(matrixStackIn, transformTypeIn, combinedLightIn, combinedOverlayIn, ammoLeft, 0, true, fireMode,itemStackIn, gun); model.render(matrixStackIn, bufferIn.getBuffer(RenderType.getEntityCutoutNoCull(gun.getTexture(gun.getCurrentTextureIndex(itemStackIn)))), transformTypeIn, combinedLightIn, combinedOverlayIn, 1, 1, 1, 1, ammoLeft,0, false, fireMode,context,fireDis); matrixStackIn.pop(); } } } private long tempLastShootMain; private long tempLastShootOff; int delay; Matrix4f temp; public void renderWithLivingEntity(LivingEntity entityIn, MatrixStack stackIn, ItemStack itemStackIn, ItemCameraTransforms.TransformType type, IRenderTypeBuffer bufferIn, IGenericGun gun, int combinedLightIn, int combinedOverlayIn, boolean leftHand, IGunModel model, TransformData transformData) { if (!Gunscraft.proxy.shouldRenderCustom(itemStackIn, gun, entityIn, !leftHand)) { return; } int ammoLeft = gun.getAmmoLeft(itemStackIn); if (entityIn == null) { justRenderModel(itemStackIn,type,stackIn,bufferIn,combinedLightIn,combinedOverlayIn,gun,model,transformData); return; } delay ++; if (model != null) { if (transformData != null) { stackIn.push(); ClientProxy.mainHandStatus.handleAiming(RenderEvents.delta); boolean isFirstPerson = type.isFirstPerson(); boolean transAiming = entityIn instanceof PlayerEntity && !leftHand && (ClientProxy.mainHandStatus.aiming || ClientProxy.mainHandStatus.aimingProgress != 0) && isFirstPerson; float aimingProgress = ClientProxy.mainHandStatus.aimingProgress; transformData.applyTransform(type, stackIn, transAiming, aimingProgress);
package sheridan.gunscraft.render; @OnlyIn(Dist.CLIENT) public class GenericGunRenderer implements IGunRender{ private static final Matrix4f DEFAULT_FIRST_PERSON_FOV_MATRIX; public static final float DEFAULT_FIRST_PERSON_FOV = 56.75f; public PlayerEntity player; static { DEFAULT_FIRST_PERSON_FOV_MATRIX = new Matrix4f(); DEFAULT_FIRST_PERSON_FOV_MATRIX.setIdentity(); Minecraft minecraft = Minecraft.getInstance(); DEFAULT_FIRST_PERSON_FOV_MATRIX.mul(Matrix4f.perspective(DEFAULT_FIRST_PERSON_FOV, (float) minecraft.getMainWindow().getFramebufferWidth() / (float) minecraft.getMainWindow().getFramebufferHeight(), 0.05F, (float) minecraft.gameSettings.renderDistanceChunks * 64F)); } public void justRenderModel(ItemStack itemStackIn, ItemCameraTransforms.TransformType transformTypeIn, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int combinedLightIn, int combinedOverlayIn, IGenericGun gun, IGunModel model, TransformData transformData) { if (model != null) { if (transformData != null) { matrixStackIn.push(); transformData.applyTransform(transformTypeIn, matrixStackIn, false, 0); int fireMode = gun.getFireMode(itemStackIn); int ammoLeft = gun.getAmmoLeft(itemStackIn); long fireDis = (gun.getShootDelay() - 1) * TICK_LEN; GunRenderContext context = NBTAttachmentsMap.renderAttachments(matrixStackIn, transformTypeIn, combinedLightIn, combinedOverlayIn, ammoLeft, 0, true, fireMode,itemStackIn, gun); model.render(matrixStackIn, bufferIn.getBuffer(RenderType.getEntityCutoutNoCull(gun.getTexture(gun.getCurrentTextureIndex(itemStackIn)))), transformTypeIn, combinedLightIn, combinedOverlayIn, 1, 1, 1, 1, ammoLeft,0, false, fireMode,context,fireDis); matrixStackIn.pop(); } } } private long tempLastShootMain; private long tempLastShootOff; int delay; Matrix4f temp; public void renderWithLivingEntity(LivingEntity entityIn, MatrixStack stackIn, ItemStack itemStackIn, ItemCameraTransforms.TransformType type, IRenderTypeBuffer bufferIn, IGenericGun gun, int combinedLightIn, int combinedOverlayIn, boolean leftHand, IGunModel model, TransformData transformData) { if (!Gunscraft.proxy.shouldRenderCustom(itemStackIn, gun, entityIn, !leftHand)) { return; } int ammoLeft = gun.getAmmoLeft(itemStackIn); if (entityIn == null) { justRenderModel(itemStackIn,type,stackIn,bufferIn,combinedLightIn,combinedOverlayIn,gun,model,transformData); return; } delay ++; if (model != null) { if (transformData != null) { stackIn.push(); ClientProxy.mainHandStatus.handleAiming(RenderEvents.delta); boolean isFirstPerson = type.isFirstPerson(); boolean transAiming = entityIn instanceof PlayerEntity && !leftHand && (ClientProxy.mainHandStatus.aiming || ClientProxy.mainHandStatus.aimingProgress != 0) && isFirstPerson; float aimingProgress = ClientProxy.mainHandStatus.aimingProgress; transformData.applyTransform(type, stackIn, transAiming, aimingProgress);
RecoilAnimationData recoilAnimationData = transformData.getRecoilAnimationData();
2
2023-11-14 14:00:55+00:00
24k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/fragments/APKsFragment.java
[ { "identifier": "APKInstallerActivity", "path": "app/src/main/java/com/threethan/questpatcher/activities/APKInstallerActivity.java", "snippet": "public class APKInstallerActivity extends AppCompatActivity {\n\n private AppCompatImageButton mExploreIcon;\n private AppCompatImageView mAppIcon;\n ...
import android.app.Activity; import android.content.ClipData; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.appcompat.widget.PopupMenu; import androidx.documentfile.provider.DocumentFile; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.threethan.questpatcher.R; import com.threethan.questpatcher.activities.APKInstallerActivity; import com.threethan.questpatcher.activities.InstallerFilePickerActivity; import com.threethan.questpatcher.adapters.APKsAdapter; import com.threethan.questpatcher.utils.APKData; import com.threethan.questpatcher.utils.APKEditorUtils; import com.threethan.questpatcher.utils.APKExplorer; import com.threethan.questpatcher.utils.AppData; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.tasks.ExploreAPK; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.tabs.TabLayout; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Objects; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils;
16,142
installer.addCategory(Intent.CATEGORY_OPENABLE); installer.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false); explorerFilePicker.launch(installer); } } private void launchAEEInstaller() { if (Build.VERSION.SDK_INT >= 29) { Intent installer = new Intent(Intent.ACTION_GET_CONTENT); installer.setType("*/*"); String[] mimeTypes = { "application/vnd.android.package-archive", "application/xapk-package-archive", "application/octet-stream", "application/vnd.apkm" }; installer.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes); installer.addCategory(Intent.CATEGORY_OPENABLE); installer.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); installerFilePicker.launch(installer); } else { Common.getAPKList().clear(); Common.setPath(Environment.getExternalStorageDirectory().toString()); Intent installer = new Intent(requireActivity(), InstallerFilePickerActivity.class); startActivity(installer); } } private void loadAPKs(Activity activity) { new sExecutor() { @Override public void onPreExecute() { mRecyclerView.setVisibility(View.GONE); Common.setProgress(true, mProgress); mRecyclerView.removeAllViews(); } @Override public void doInBackground() { mRecycleViewAdapter = new APKsAdapter(APKData.getData(activity)); } @Override public void onPostExecute() { mRecyclerView.setAdapter(mRecycleViewAdapter); mRecyclerView.setVisibility(View.VISIBLE); Common.setProgress(false, mProgress); } }.execute(); } private sExecutor handleMultipleAPKs(ClipData uriFiles, Activity activity) { return new sExecutor() { private final File mParentDir = new File(activity.getExternalCacheDir(), "APKs"); @Override public void onPreExecute() { Common.setProgress(true, mProgress); if (mParentDir.exists()) { sFileUtils.delete(mParentDir); } sFileUtils.mkdir(mParentDir); Common.getAPKList().clear(); } @Override public void doInBackground() { for (int i = 0; i < uriFiles.getItemCount(); i++) { String fileName = Objects.requireNonNull(DocumentFile.fromSingleUri(activity, uriFiles.getItemAt(i).getUri())).getName(); File mFile = new File(mParentDir, Objects.requireNonNull(fileName)); try (FileOutputStream outputStream = new FileOutputStream(mFile, false)) { InputStream inputStream = activity.getContentResolver().openInputStream(uriFiles.getItemAt(i).getUri()); int read; byte[] bytes = new byte[8192]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } // In this case, we don't really care about app bundles! if (mFile.getName().endsWith(".apk")) { Common.getAPKList().add(mFile.getAbsolutePath()); } inputStream.close(); } catch (IOException ignored) { } } } @Override public void onPostExecute() { APKExplorer.handleAPKs(false, activity); Common.setProgress(false, mProgress); } }; } ActivityResultLauncher<Intent> installerFilePicker = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) { Intent data = result.getData(); if (data.getClipData() != null) { handleMultipleAPKs(data.getClipData(), requireActivity()).execute(); } else if (data.getData() != null) { Intent intent = new Intent(requireActivity(), APKInstallerActivity.class); intent.putExtra("apkFileUri", data.getData().toString()); startActivity(intent); } } } ); ActivityResultLauncher<Intent> explorerFilePicker = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) { Intent data = result.getData(); if (data.getData() != null) {
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 04, 2021 */ public class APKsFragment extends Fragment { private LinearLayoutCompat mProgress; private RecyclerView mRecyclerView; private APKsAdapter mRecycleViewAdapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mRootView = inflater.inflate(R.layout.fragment_apks, container, false); Common.initializeAPKsTitle(mRootView, R.id.app_title); Common.initializeAPKsSearchWord(mRootView, R.id.search_word); mProgress = mRootView.findViewById(R.id.progress_layout); AppCompatImageButton mSearchButton = mRootView.findViewById(R.id.search_button); AppCompatImageButton mSortButton = mRootView.findViewById(R.id.sort_button); AppCompatImageButton mAddButton = mRootView.findViewById(R.id.add_button); LinearLayoutCompat mBottomLayout = mRootView.findViewById(R.id.layout_bottom); TabLayout mTabLayout = mRootView.findViewById(R.id.tab_layout); mRecyclerView = mRootView.findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity())); Common.getAPKsTitle().setText(getString(R.string.apps_exported)); mTabLayout.setVisibility(View.VISIBLE); mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.apks))); mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.bundles))); Objects.requireNonNull(mTabLayout.getTabAt(getTabPosition(requireActivity()))).select(); mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { String mStatus = sCommonUtils.getString("apkTypes", "apks", requireActivity()); switch (tab.getPosition()) { case 0: if (!mStatus.equals("apks")) { sCommonUtils.saveString("apkTypes", "apks", requireActivity()); loadAPKs(requireActivity()); } break; case 1: if (!mStatus.equals("bundles")) { sCommonUtils.saveString("apkTypes", "bundles", requireActivity()); loadAPKs(requireActivity()); } break; } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); mSearchButton.setOnClickListener(v -> { if (Common.getAPKsSearchWord().getVisibility() == View.VISIBLE) { Common.getAPKsSearchWord().setVisibility(View.GONE); Common.getAPKsTitle().setVisibility(View.VISIBLE); if (Common.getAPKsSearchWord() != null) { Common.getAPKsSearchWord().setText(null); } AppData.toggleKeyboard(0, Common.getAPKsSearchWord(), requireActivity()); } else { Common.getAPKsSearchWord().setVisibility(View.VISIBLE); Common.getAPKsSearchWord().requestFocus(); Common.getAPKsTitle().setVisibility(View.GONE); AppData.toggleKeyboard(1, Common.getAPKsSearchWord(), requireActivity()); } }); mSortButton.setOnClickListener(v -> { PopupMenu popupMenu = new PopupMenu(requireActivity(), mSortButton); Menu menu = popupMenu.getMenu(); menu.add(Menu.NONE, 0, Menu.NONE, getString(R.string.sort_order)).setCheckable(true) .setChecked(sCommonUtils.getBoolean("az_order", true, requireActivity())); popupMenu.setOnMenuItemClickListener(item -> { if (item.getItemId() == 0) { sCommonUtils.saveBoolean("az_order", !sCommonUtils.getBoolean("az_order", true, requireActivity()), requireActivity()); loadAPKs(requireActivity()); } return false; }); popupMenu.show(); }); loadAPKs(requireActivity()); Common.getAPKsSearchWord().addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { Common.setSearchWord(s.toString().toLowerCase()); loadAPKs(requireActivity()); } }); mAddButton.setOnClickListener(v -> launchInstallerFilePicker()); mBottomLayout.setOnClickListener(v -> launchInstallerFilePicker()); return mRootView; } private int getTabPosition(Activity activity) { String mStatus = sCommonUtils.getString("apkTypes", "apks", activity); if (mStatus.equals("bundles")) { return 1; } else { return 0; } } private void launchInstallerFilePicker() { if (APKEditorUtils.isFullVersion(requireActivity())) { if (!sCommonUtils.getBoolean("firstInstall", false, requireActivity())) { new MaterialAlertDialogBuilder(requireActivity()) .setIcon(R.mipmap.ic_launcher) .setTitle(R.string.split_apk_installer) .setMessage(getString(R.string.installer_message)) .setCancelable(false) .setPositiveButton(getString(R.string.got_it), (dialog, id) -> { sCommonUtils.saveBoolean("firstInstall", true, requireActivity()); launchAEEInstaller(); }).show(); } else { launchAEEInstaller(); } } else { Intent installer = new Intent(Intent.ACTION_GET_CONTENT); installer.setType("application/vnd.android.package-archive"); installer.addCategory(Intent.CATEGORY_OPENABLE); installer.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false); explorerFilePicker.launch(installer); } } private void launchAEEInstaller() { if (Build.VERSION.SDK_INT >= 29) { Intent installer = new Intent(Intent.ACTION_GET_CONTENT); installer.setType("*/*"); String[] mimeTypes = { "application/vnd.android.package-archive", "application/xapk-package-archive", "application/octet-stream", "application/vnd.apkm" }; installer.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes); installer.addCategory(Intent.CATEGORY_OPENABLE); installer.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); installerFilePicker.launch(installer); } else { Common.getAPKList().clear(); Common.setPath(Environment.getExternalStorageDirectory().toString()); Intent installer = new Intent(requireActivity(), InstallerFilePickerActivity.class); startActivity(installer); } } private void loadAPKs(Activity activity) { new sExecutor() { @Override public void onPreExecute() { mRecyclerView.setVisibility(View.GONE); Common.setProgress(true, mProgress); mRecyclerView.removeAllViews(); } @Override public void doInBackground() { mRecycleViewAdapter = new APKsAdapter(APKData.getData(activity)); } @Override public void onPostExecute() { mRecyclerView.setAdapter(mRecycleViewAdapter); mRecyclerView.setVisibility(View.VISIBLE); Common.setProgress(false, mProgress); } }.execute(); } private sExecutor handleMultipleAPKs(ClipData uriFiles, Activity activity) { return new sExecutor() { private final File mParentDir = new File(activity.getExternalCacheDir(), "APKs"); @Override public void onPreExecute() { Common.setProgress(true, mProgress); if (mParentDir.exists()) { sFileUtils.delete(mParentDir); } sFileUtils.mkdir(mParentDir); Common.getAPKList().clear(); } @Override public void doInBackground() { for (int i = 0; i < uriFiles.getItemCount(); i++) { String fileName = Objects.requireNonNull(DocumentFile.fromSingleUri(activity, uriFiles.getItemAt(i).getUri())).getName(); File mFile = new File(mParentDir, Objects.requireNonNull(fileName)); try (FileOutputStream outputStream = new FileOutputStream(mFile, false)) { InputStream inputStream = activity.getContentResolver().openInputStream(uriFiles.getItemAt(i).getUri()); int read; byte[] bytes = new byte[8192]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } // In this case, we don't really care about app bundles! if (mFile.getName().endsWith(".apk")) { Common.getAPKList().add(mFile.getAbsolutePath()); } inputStream.close(); } catch (IOException ignored) { } } } @Override public void onPostExecute() { APKExplorer.handleAPKs(false, activity); Common.setProgress(false, mProgress); } }; } ActivityResultLauncher<Intent> installerFilePicker = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) { Intent data = result.getData(); if (data.getClipData() != null) { handleMultipleAPKs(data.getClipData(), requireActivity()).execute(); } else if (data.getData() != null) { Intent intent = new Intent(requireActivity(), APKInstallerActivity.class); intent.putExtra("apkFileUri", data.getData().toString()); startActivity(intent); } } } ); ActivityResultLauncher<Intent> explorerFilePicker = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) { Intent data = result.getData(); if (data.getData() != null) {
new ExploreAPK(null, null, data.getData(), requireActivity()).execute();
8
2023-11-18 15:13:30+00:00
24k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/service/impl/UserServiceImpl.java
[ { "identifier": "FileProperties", "path": "dimple-common/src/main/java/com/dimple/config/FileProperties.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"file\")\npublic class FileProperties {\n\n /**\n * 文件大小限制\n */\n private Long maxSize;\n\n /**\n * 头像...
import com.dimple.config.FileProperties; import com.dimple.exception.EntityExistException; import com.dimple.exception.EntityNotFoundException; import com.dimple.modules.system.domain.User; import com.dimple.modules.system.repository.UserRepository; import com.dimple.modules.system.service.UserService; import com.dimple.modules.system.service.dto.JobSmallDto; import com.dimple.modules.system.service.dto.RoleSmallDTO; import com.dimple.modules.system.service.dto.UserDTO; import com.dimple.modules.system.service.dto.UserQueryCriteria; import com.dimple.modules.system.service.mapstruct.UserMapper; import com.dimple.utils.FileUtil; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.RedisUtils; import com.dimple.utils.SecurityUtils; import com.dimple.utils.StringUtils; import com.dimple.utils.ValidationUtil; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors;
14,725
package com.dimple.modules.system.service.impl; /** * @className: UserServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "user") public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final UserMapper userMapper; private final FileProperties properties; private final RedisUtils redisUtils; @Override public Object queryAll(UserQueryCriteria criteria, Pageable pageable) { Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable); return PageUtil.toPage(page.map(userMapper::toDto)); } @Override public List<UserDTO> queryAll(UserQueryCriteria criteria) { List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); return userMapper.toDto(users); } @Override @Cacheable(key = "'id:' + #p0") @Transactional(rollbackFor = Exception.class) public UserDTO findById(long id) { User user = userRepository.findById(id).orElseGet(User::new); ValidationUtil.isNull(user.getId(), "User", "id", id); return userMapper.toDto(user); } @Override @Transactional(rollbackFor = Exception.class) public void create(User resources) { if (userRepository.findByUsername(resources.getUsername()) != null) { throw new EntityExistException(User.class, "username", resources.getUsername()); } if (userRepository.findByEmail(resources.getEmail()) != null) { throw new EntityExistException(User.class, "email", resources.getEmail()); } userRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(User resources) { User user = userRepository.findById(resources.getId()).orElseGet(User::new); ValidationUtil.isNull(user.getId(), "User", "id", resources.getId()); User user1 = userRepository.findByUsername(resources.getUsername()); User user2 = userRepository.findByEmail(resources.getEmail()); if (user1 != null && !user.getId().equals(user1.getId())) { throw new EntityExistException(User.class, "username", resources.getUsername()); } if (user2 != null && !user.getId().equals(user2.getId())) { throw new EntityExistException(User.class, "email", resources.getEmail()); } // 如果用户的角色改变 if (!resources.getRoles().equals(user.getRoles())) { redisUtils.del("data::user:" + resources.getId()); redisUtils.del("menu::user:" + resources.getId()); redisUtils.del("role::auth:" + resources.getId()); } // 如果用户名称修改 if (!resources.getUsername().equals(user.getUsername())) { redisUtils.del("user::username:" + user.getUsername()); } user.setUsername(resources.getUsername()); user.setEmail(resources.getEmail()); user.setEnabled(resources.getEnabled()); user.setRoles(resources.getRoles()); user.setPhone(resources.getPhone()); user.setNickName(resources.getNickName()); user.setGender(resources.getGender()); userRepository.save(user); // 清除缓存 delCaches(user.getId(), user.getUsername()); } @Override @Transactional(rollbackFor = Exception.class) public void updateCenter(User resources) { User user = userRepository.findById(resources.getId()).orElseGet(User::new); user.setNickName(resources.getNickName()); user.setPhone(resources.getPhone()); user.setGender(resources.getGender()); userRepository.save(user); // 清理缓存 delCaches(user.getId(), user.getUsername()); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Long> ids) { for (Long id : ids) { // 清理缓存 UserDTO user = findById(id); delCaches(user.getId(), user.getUsername()); } userRepository.deleteAllByIdIn(ids); } @Override @Cacheable(key = "'username:' + #p0") public UserDTO findByName(String userName) { User user = userRepository.findByUsername(userName); if (user == null) { throw new EntityNotFoundException(User.class, "name", userName); } else { return userMapper.toDto(user); } } @Override @Transactional(rollbackFor = Exception.class) public void updatePass(String username, String pass) { userRepository.updatePass(username, pass, new Date()); redisUtils.del("user::username:" + username); } @Override @Transactional(rollbackFor = Exception.class) public Map<String, String> updateAvatar(MultipartFile multipartFile) { User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername()); String oldPath = user.getAvatarPath(); File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar()); user.setAvatarPath(Objects.requireNonNull(file).getPath()); user.setAvatarName(file.getName()); userRepository.save(user);
package com.dimple.modules.system.service.impl; /** * @className: UserServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "user") public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final UserMapper userMapper; private final FileProperties properties; private final RedisUtils redisUtils; @Override public Object queryAll(UserQueryCriteria criteria, Pageable pageable) { Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable); return PageUtil.toPage(page.map(userMapper::toDto)); } @Override public List<UserDTO> queryAll(UserQueryCriteria criteria) { List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); return userMapper.toDto(users); } @Override @Cacheable(key = "'id:' + #p0") @Transactional(rollbackFor = Exception.class) public UserDTO findById(long id) { User user = userRepository.findById(id).orElseGet(User::new); ValidationUtil.isNull(user.getId(), "User", "id", id); return userMapper.toDto(user); } @Override @Transactional(rollbackFor = Exception.class) public void create(User resources) { if (userRepository.findByUsername(resources.getUsername()) != null) { throw new EntityExistException(User.class, "username", resources.getUsername()); } if (userRepository.findByEmail(resources.getEmail()) != null) { throw new EntityExistException(User.class, "email", resources.getEmail()); } userRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(User resources) { User user = userRepository.findById(resources.getId()).orElseGet(User::new); ValidationUtil.isNull(user.getId(), "User", "id", resources.getId()); User user1 = userRepository.findByUsername(resources.getUsername()); User user2 = userRepository.findByEmail(resources.getEmail()); if (user1 != null && !user.getId().equals(user1.getId())) { throw new EntityExistException(User.class, "username", resources.getUsername()); } if (user2 != null && !user.getId().equals(user2.getId())) { throw new EntityExistException(User.class, "email", resources.getEmail()); } // 如果用户的角色改变 if (!resources.getRoles().equals(user.getRoles())) { redisUtils.del("data::user:" + resources.getId()); redisUtils.del("menu::user:" + resources.getId()); redisUtils.del("role::auth:" + resources.getId()); } // 如果用户名称修改 if (!resources.getUsername().equals(user.getUsername())) { redisUtils.del("user::username:" + user.getUsername()); } user.setUsername(resources.getUsername()); user.setEmail(resources.getEmail()); user.setEnabled(resources.getEnabled()); user.setRoles(resources.getRoles()); user.setPhone(resources.getPhone()); user.setNickName(resources.getNickName()); user.setGender(resources.getGender()); userRepository.save(user); // 清除缓存 delCaches(user.getId(), user.getUsername()); } @Override @Transactional(rollbackFor = Exception.class) public void updateCenter(User resources) { User user = userRepository.findById(resources.getId()).orElseGet(User::new); user.setNickName(resources.getNickName()); user.setPhone(resources.getPhone()); user.setGender(resources.getGender()); userRepository.save(user); // 清理缓存 delCaches(user.getId(), user.getUsername()); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Long> ids) { for (Long id : ids) { // 清理缓存 UserDTO user = findById(id); delCaches(user.getId(), user.getUsername()); } userRepository.deleteAllByIdIn(ids); } @Override @Cacheable(key = "'username:' + #p0") public UserDTO findByName(String userName) { User user = userRepository.findByUsername(userName); if (user == null) { throw new EntityNotFoundException(User.class, "name", userName); } else { return userMapper.toDto(user); } } @Override @Transactional(rollbackFor = Exception.class) public void updatePass(String username, String pass) { userRepository.updatePass(username, pass, new Date()); redisUtils.del("user::username:" + username); } @Override @Transactional(rollbackFor = Exception.class) public Map<String, String> updateAvatar(MultipartFile multipartFile) { User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername()); String oldPath = user.getAvatarPath(); File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar()); user.setAvatarPath(Objects.requireNonNull(file).getPath()); user.setAvatarName(file.getName()); userRepository.save(user);
if (StringUtils.isNotBlank(oldPath)) {
16
2023-11-10 03:30:36+00:00
24k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/component/codeintput/inputmeta/pane/command/operation/AdditionalFunctionControlPane.java
[ { "identifier": "LabelElementName", "path": "database/src/main/java/com/lazycoder/database/common/LabelElementName.java", "snippet": "public class LabelElementName {\n\n\t/**\n\t * 内容输入 t !!\n\t */\n\tpublic static final String TEXT_INPUT = \"textInput\";\n\n\t/**\n\t * 选择 c !!\n\t */\n\tpublic static f...
import com.lazycoder.database.common.LabelElementName; import com.lazycoder.database.common.MarkElementName; import com.lazycoder.database.common.NotNamed; import com.lazycoder.database.model.OptionDataModel; import com.lazycoder.service.GeneralHolder; import com.lazycoder.service.fileStructure.DatabaseFileStructure; import com.lazycoder.service.fileStructure.SysFileStructure; import com.lazycoder.service.service.SysService; import com.lazycoder.service.vo.datasourceedit.general.AbstractEditContainerModel; import com.lazycoder.service.vo.element.lable.control.FunctionAddControl; import com.lazycoder.service.vo.element.lable.control.InfrequentlyUsedSettingControl; import com.lazycoder.service.vo.transferparam.FunctionAddParam; import com.lazycoder.service.vo.transferparam.InfrequentlyUsedSettingParam; import com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.command.CommandCodeControl; import com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.command.AbstractFunctionControlInputPane; import com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.condition.ControlCondition; import com.lazycoder.uidatasourceedit.component.codeintput.intputscutcheon.labelscutcheon.editframe.choose.ContentChooseFrameAddForBaseControlTextFrame; import com.lazycoder.uidatasourceedit.component.codeintput.intputscutcheon.labelscutcheon.control.FunctionAddControlLabel; import com.lazycoder.uidatasourceedit.component.codeintput.intputscutcheon.labelscutcheon.control.InfrequentlyUsedSettingControlLabel; import java.io.File; import java.util.List;
20,928
package com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.command.operation; public class AdditionalFunctionControlPane extends AbstractFunctionControlInputPane { /** * */ private static final long serialVersionUID = 6613257798034012175L; private transient List<OptionDataModel> listTemp; /** * 对应可选模板的标识编号 */ private int additionalSerialNumber = 0; public AdditionalFunctionControlPane(int additionalSerialNumber) { // TODO Auto-generated constructor stub super(); this.additionalSerialNumber = additionalSerialNumber; ControlCondition condition = new ControlCondition(true, true, true, true); menuInit(condition); } @Override protected List<OptionDataModel> getUpdateChooseMenuList() { return listTemp; } @Override protected List<OptionDataModel> getDelCorrespondingChooseFromDBMenuList() { return listTemp; } @Override public File getImageRootPath() { File file = DatabaseFileStructure.getAdditionalPictureFolder(SysFileStructure.getDataFileFolder(), GeneralHolder.currentUserDataSourceLabel.getDataSourceName(), additionalSerialNumber); return file; } @Override public File getFileSelectorRootPath() { File file = DatabaseFileStructure.getAdditionalNeedFileFolder(SysFileStructure.getDataFileFolder(), GeneralHolder.currentUserDataSourceLabel.getDataSourceName(), additionalSerialNumber); return file; } @Override protected void addFunctionAddOpratingLabel() { String name = CommandCodeControl.generateComponentName(model, LabelElementName.FUNCTION_ADD); FunctionAddParam functionAddParam = new FunctionAddParam();// 在使用过程中需要的参数 functionAddParam.setClassName(NotNamed.additionalFuncition.getClassName()); functionAddParam.setModuleName(NotNamed.additionalFuncition.getModuleName()); functionAddParam.setPaneType(MarkElementName.ADDITIONAL_FUNCTION_MARK); functionAddParam.setAdditionalSerialNumber(additionalSerialNumber); FunctionAddControlLabel temp = new FunctionAddControlLabel(name, functionAddParam); temp.setPassingComponentParams(passingComponentParams); addCorrespondingComponentMethod(temp, name, LabelElementName.FUNCTION_ADD, delFunctionAddMenu); CommandCodeControl.addControlLabelAndUpdateCodePaneMenu(model, temp.getControl().controlComponentInformation()); } @Override protected FunctionAddControlLabel getFunctionAddControlLabel(FunctionAddControl controlElement) { FunctionAddParam functionAddParam = new FunctionAddParam();// 在使用过程中需要的参数 functionAddParam.setClassName(NotNamed.additionalFuncition.getClassName()); functionAddParam.setModuleName(NotNamed.additionalFuncition.getModuleName()); functionAddParam.setPaneType(MarkElementName.ADDITIONAL_FUNCTION_MARK); functionAddParam.setAdditionalSerialNumber(additionalSerialNumber); FunctionAddControlLabel functionAddControlLabel = new FunctionAddControlLabel(controlElement, functionAddParam); return functionAddControlLabel; } @Override protected void addInfrequentlyUsedSettingOpratingLabel() { InfrequentlyUsedSettingParam infrequentlyUsedSettingParam = new InfrequentlyUsedSettingParam(); infrequentlyUsedSettingParam.setClassName(NotNamed.additionalFuncition.getClassName()); infrequentlyUsedSettingParam.setModuleName(NotNamed.additionalFuncition.getModuleName()); infrequentlyUsedSettingParam.setPaneType(MarkElementName.ADDITIONAL_FUNCTION_MARK); infrequentlyUsedSettingParam.setAdditionalSerialNumber(additionalSerialNumber); InfrequentlyUsedSettingControlLabel temp = new InfrequentlyUsedSettingControlLabel(model, infrequentlyUsedSettingParam); super.addInfrequentlyUsedSettingOpratingLabel(temp); } @Override
package com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.command.operation; public class AdditionalFunctionControlPane extends AbstractFunctionControlInputPane { /** * */ private static final long serialVersionUID = 6613257798034012175L; private transient List<OptionDataModel> listTemp; /** * 对应可选模板的标识编号 */ private int additionalSerialNumber = 0; public AdditionalFunctionControlPane(int additionalSerialNumber) { // TODO Auto-generated constructor stub super(); this.additionalSerialNumber = additionalSerialNumber; ControlCondition condition = new ControlCondition(true, true, true, true); menuInit(condition); } @Override protected List<OptionDataModel> getUpdateChooseMenuList() { return listTemp; } @Override protected List<OptionDataModel> getDelCorrespondingChooseFromDBMenuList() { return listTemp; } @Override public File getImageRootPath() { File file = DatabaseFileStructure.getAdditionalPictureFolder(SysFileStructure.getDataFileFolder(), GeneralHolder.currentUserDataSourceLabel.getDataSourceName(), additionalSerialNumber); return file; } @Override public File getFileSelectorRootPath() { File file = DatabaseFileStructure.getAdditionalNeedFileFolder(SysFileStructure.getDataFileFolder(), GeneralHolder.currentUserDataSourceLabel.getDataSourceName(), additionalSerialNumber); return file; } @Override protected void addFunctionAddOpratingLabel() { String name = CommandCodeControl.generateComponentName(model, LabelElementName.FUNCTION_ADD); FunctionAddParam functionAddParam = new FunctionAddParam();// 在使用过程中需要的参数 functionAddParam.setClassName(NotNamed.additionalFuncition.getClassName()); functionAddParam.setModuleName(NotNamed.additionalFuncition.getModuleName()); functionAddParam.setPaneType(MarkElementName.ADDITIONAL_FUNCTION_MARK); functionAddParam.setAdditionalSerialNumber(additionalSerialNumber); FunctionAddControlLabel temp = new FunctionAddControlLabel(name, functionAddParam); temp.setPassingComponentParams(passingComponentParams); addCorrespondingComponentMethod(temp, name, LabelElementName.FUNCTION_ADD, delFunctionAddMenu); CommandCodeControl.addControlLabelAndUpdateCodePaneMenu(model, temp.getControl().controlComponentInformation()); } @Override protected FunctionAddControlLabel getFunctionAddControlLabel(FunctionAddControl controlElement) { FunctionAddParam functionAddParam = new FunctionAddParam();// 在使用过程中需要的参数 functionAddParam.setClassName(NotNamed.additionalFuncition.getClassName()); functionAddParam.setModuleName(NotNamed.additionalFuncition.getModuleName()); functionAddParam.setPaneType(MarkElementName.ADDITIONAL_FUNCTION_MARK); functionAddParam.setAdditionalSerialNumber(additionalSerialNumber); FunctionAddControlLabel functionAddControlLabel = new FunctionAddControlLabel(controlElement, functionAddParam); return functionAddControlLabel; } @Override protected void addInfrequentlyUsedSettingOpratingLabel() { InfrequentlyUsedSettingParam infrequentlyUsedSettingParam = new InfrequentlyUsedSettingParam(); infrequentlyUsedSettingParam.setClassName(NotNamed.additionalFuncition.getClassName()); infrequentlyUsedSettingParam.setModuleName(NotNamed.additionalFuncition.getModuleName()); infrequentlyUsedSettingParam.setPaneType(MarkElementName.ADDITIONAL_FUNCTION_MARK); infrequentlyUsedSettingParam.setAdditionalSerialNumber(additionalSerialNumber); InfrequentlyUsedSettingControlLabel temp = new InfrequentlyUsedSettingControlLabel(model, infrequentlyUsedSettingParam); super.addInfrequentlyUsedSettingOpratingLabel(temp); } @Override
protected InfrequentlyUsedSettingControlLabel getInfrequentlyUsedSettingControlLabel(InfrequentlyUsedSettingControl controlElement, AbstractEditContainerModel model) {
10
2023-11-16 11:55:06+00:00
24k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506_ex/KSHouseMeter2.java
[ { "identifier": "PropertyMap", "path": "app/src/main/java/kr/or/kashi/hde/base/PropertyMap.java", "snippet": "public abstract class PropertyMap {\n /** Get the value of a property */\n public <E> E get(String name, Class<E> clazz) {\n return (E) get(name).getValue();\n }\n\n /** Put n...
import java.util.Map; import android.content.Context; import android.util.Log; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.MainContext; import kr.or.kashi.hde.HomeDevice; import kr.or.kashi.hde.device.HouseMeter; import kr.or.kashi.hde.ksx4506.KSAddress; import kr.or.kashi.hde.ksx4506.KSDeviceContextBase; import kr.or.kashi.hde.ksx4506.KSHouseMeter; import kr.or.kashi.hde.ksx4506.KSPacket; import java.util.List;
18,194
/* * 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.ksx4506_ex; /** * Extended implementation of [KS X 4506] the house-meter */ public class KSHouseMeter2 extends KSHouseMeter { private static final String TAG = "KSHouseMeter2"; private static final boolean DBG = true; // HACK: Some device of manufacturer sends different size // of meter value in total measure. public static final int EXTENDED_CURRENT_METER_BYTES = KSHouseMeter.CURRENT_METER_BYTES; public static final int EXTENDED_TOTAL_METER_BYTES = KSHouseMeter.TOTAL_METER_BYTES + 1; public static final int EXTENDED_METER_DATA_BYTES = EXTENDED_CURRENT_METER_BYTES + EXTENDED_TOTAL_METER_BYTES; private boolean mExtendedMeterDigits = false;
/* * 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.ksx4506_ex; /** * Extended implementation of [KS X 4506] the house-meter */ public class KSHouseMeter2 extends KSHouseMeter { private static final String TAG = "KSHouseMeter2"; private static final boolean DBG = true; // HACK: Some device of manufacturer sends different size // of meter value in total measure. public static final int EXTENDED_CURRENT_METER_BYTES = KSHouseMeter.CURRENT_METER_BYTES; public static final int EXTENDED_TOTAL_METER_BYTES = KSHouseMeter.TOTAL_METER_BYTES + 1; public static final int EXTENDED_METER_DATA_BYTES = EXTENDED_CURRENT_METER_BYTES + EXTENDED_TOTAL_METER_BYTES; private boolean mExtendedMeterDigits = false;
public KSHouseMeter2(MainContext mainContext, Map defaultProps) {
1
2023-11-10 01:19:44+00:00
24k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/core/WidgetManager.java
[ { "identifier": "TextTools", "path": "src/main/java/io/xlorey/FluxLoader/client/api/TextTools.java", "snippet": "public class TextTools {\n /**\n * Drawing colored text at specified coordinates\n * @param text the text to be drawn. Must not be null\n * @param font text font corresponding ...
import imgui.ImGui; import imgui.ImGuiIO; import imgui.gl3.ImGuiImplGl3; import imgui.glfw.ImGuiImplGlfw; import io.xlorey.FluxLoader.client.api.TextTools; import io.xlorey.FluxLoader.client.ui.ScreenWidget; import io.xlorey.FluxLoader.client.ui.pluginMenu.MainMenuButton; import io.xlorey.FluxLoader.client.ui.pluginMenu.PluginMenu; import io.xlorey.FluxLoader.interfaces.IWidget; import io.xlorey.FluxLoader.utils.Constants; import org.lwjglx.opengl.Display; import zombie.GameWindow; import zombie.core.Core; import zombie.core.opengl.RenderThread; import zombie.gameStates.MainScreenState; import zombie.ui.UIFont; import java.util.ArrayList;
16,202
package io.xlorey.FluxLoader.client.core; /** * Custom UI management system */ public class WidgetManager { /** * Pointer to the game window */ private static final long windowHandler = Display.getWindow(); /** * Implementation of ImGui GLFW */ private final static ImGuiImplGlfw imGuiGlfw = new ImGuiImplGlfw(); /** * Implementation of ImGui GL3 */ private final static ImGuiImplGl3 imGuiGl3 = new ImGuiImplGl3(); /** * Flag indicating the initialization state of ImGui */ private static boolean isImGuiInit = false; /** * A register of all UI elements that should be rendered */ public static ArrayList<IWidget> widgetsRegistry = new ArrayList<>(); /** * Flag showing mouse capture for ImGui widgets (prevents events for standard UI) */ private static boolean isMouseCapture = false; /** * Change mouse capture state for ImGui widgets. Used only inside widgets via the captureMouseFocus method */ public static void captureMouse() { isMouseCapture = true; } /** * Returns the value of the mouse capture flag. * @return true if the mouse is captured, false otherwise. */ public static boolean isMouseCapture() { return isMouseCapture; } /** * Release the mouse from being captured by ImGui widgets */ public static void releaseMouse() { isMouseCapture = false; } /** * Initializing the UI Manager */ public static void init(){ RenderThread.invokeOnRenderContext(WidgetManager::initImGui); loadPluginsMenu(); } /** * Initializing the ImGui context */ private static void initImGui() { ImGui.createContext(); ImGuiIO io = ImGui.getIO(); // Preventing UI Elements from Saving State io.setIniFilename(null); imGuiGlfw.init(windowHandler, true); imGuiGl3.init("#version 130"); isImGuiInit = true; } /** * Loading a custom plugin management menu */ private static void loadPluginsMenu() { MainMenuButton screenMenuButton = new MainMenuButton(); screenMenuButton.addToScreenDraw(); PluginMenu pluginMenu = new PluginMenu(); pluginMenu.addToScreenDraw(); } /** * FluxLoader credits rendering update */ public static void drawCredits(){ UIFont font = UIFont.Small; int margin = 15; int screenHeight = Core.getInstance().getScreenHeight(); int fontHeight = TextTools.getFontHeight(font); String creditsText = String.format("Modded with %s (v%s)", Constants.FLUX_NAME, Constants.FLUX_VERSION); TextTools.drawText(creditsText, font, margin, screenHeight - fontHeight - margin, 1f, 1f, 1f, 0.5f); } /** * Updating the UI manager to render its components */ public static void update() {
package io.xlorey.FluxLoader.client.core; /** * Custom UI management system */ public class WidgetManager { /** * Pointer to the game window */ private static final long windowHandler = Display.getWindow(); /** * Implementation of ImGui GLFW */ private final static ImGuiImplGlfw imGuiGlfw = new ImGuiImplGlfw(); /** * Implementation of ImGui GL3 */ private final static ImGuiImplGl3 imGuiGl3 = new ImGuiImplGl3(); /** * Flag indicating the initialization state of ImGui */ private static boolean isImGuiInit = false; /** * A register of all UI elements that should be rendered */ public static ArrayList<IWidget> widgetsRegistry = new ArrayList<>(); /** * Flag showing mouse capture for ImGui widgets (prevents events for standard UI) */ private static boolean isMouseCapture = false; /** * Change mouse capture state for ImGui widgets. Used only inside widgets via the captureMouseFocus method */ public static void captureMouse() { isMouseCapture = true; } /** * Returns the value of the mouse capture flag. * @return true if the mouse is captured, false otherwise. */ public static boolean isMouseCapture() { return isMouseCapture; } /** * Release the mouse from being captured by ImGui widgets */ public static void releaseMouse() { isMouseCapture = false; } /** * Initializing the UI Manager */ public static void init(){ RenderThread.invokeOnRenderContext(WidgetManager::initImGui); loadPluginsMenu(); } /** * Initializing the ImGui context */ private static void initImGui() { ImGui.createContext(); ImGuiIO io = ImGui.getIO(); // Preventing UI Elements from Saving State io.setIniFilename(null); imGuiGlfw.init(windowHandler, true); imGuiGl3.init("#version 130"); isImGuiInit = true; } /** * Loading a custom plugin management menu */ private static void loadPluginsMenu() { MainMenuButton screenMenuButton = new MainMenuButton(); screenMenuButton.addToScreenDraw(); PluginMenu pluginMenu = new PluginMenu(); pluginMenu.addToScreenDraw(); } /** * FluxLoader credits rendering update */ public static void drawCredits(){ UIFont font = UIFont.Small; int margin = 15; int screenHeight = Core.getInstance().getScreenHeight(); int fontHeight = TextTools.getFontHeight(font); String creditsText = String.format("Modded with %s (v%s)", Constants.FLUX_NAME, Constants.FLUX_VERSION); TextTools.drawText(creditsText, font, margin, screenHeight - fontHeight - margin, 1f, 1f, 1f, 0.5f); } /** * Updating the UI manager to render its components */ public static void update() {
if (GameWindow.states.current instanceof MainScreenState){
6
2023-11-16 09:05:44+00:00
24k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/commands/handlers/AdminCommands.java
[ { "identifier": "EnchantManager", "path": "src/main/java/com/sweattypalms/skyblock/core/enchants/EnchantManager.java", "snippet": "public class EnchantManager {\n public static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<>();\n\n\n public static void init() {\n Reflections ref...
import com.sweattypalms.skyblock.commands.Command; import com.sweattypalms.skyblock.commands.TabCompleter; import com.sweattypalms.skyblock.core.enchants.EnchantManager; import com.sweattypalms.skyblock.core.enchants.builder.Enchantment; import com.sweattypalms.skyblock.core.helpers.PDCHelper; import com.sweattypalms.skyblock.core.helpers.PlaceholderFormatter; import com.sweattypalms.skyblock.core.items.ItemManager; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.reforges.Reforge; import com.sweattypalms.skyblock.core.items.builder.reforges.ReforgeManager; import com.sweattypalms.skyblock.core.items.types.end.armor.SuperiorChestplate; import com.sweattypalms.skyblock.core.mobs.builder.MobManager; import com.sweattypalms.skyblock.core.mobs.builder.NameAttributes; import com.sweattypalms.skyblock.core.mobs.builder.SkyblockMob; import com.sweattypalms.skyblock.core.mobs.builder.dragons.loot.DragonDropItemEntity; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import com.sweattypalms.skyblock.core.player.sub.stats.StatsManager; import com.sweattypalms.skyblock.slayers.ISlayerMob; import com.sweattypalms.skyblock.ui.guis.ItemsGUI; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftZombie; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.util.Arrays; import java.util.List;
19,765
package com.sweattypalms.skyblock.commands.handlers; public class AdminCommands { @Command(name = "mob", description = "Mob command", op = true) public void mobCommand(Player player, String[] args) { if (args.length == 0) { player.sendMessage(ChatColor.RED + "Usage: /mob id"); return; } String id = args[0].toLowerCase(); SkyblockMob skyblockMob = getAndSpawnMob(id, player); if (skyblockMob == null) return; player.sendMessage(ChatColor.RED + "Successfully spawned: " + skyblockMob.getNameAttribute(NameAttributes.CUSTOM_NAME)); } @Command(name = "sitem", description = "Item command", op = true) public void itemCommand(Player player, String[] args) { if (args.length == 0) { ItemsGUI gui = new ItemsGUI(); gui.open(player); String message = ChatColor.YELLOW + "If you want to get an item of a specific id, do:"; message += "\n" + ChatColor.YELLOW + "/item <id> [optional: amount]"; player.sendMessage(message); return; } String id = args[0].toLowerCase(); if (!ItemManager.ITEMS_LIST.containsKey(id)) { player.sendMessage(ChatColor.RED + "Invalid item ID!"); return; } SkyblockItem skyblockItem = ItemManager.ITEMS_LIST.get(id); ItemStack itemStack = skyblockItem.toItemStack(); int amount = 1; if (args.length > 1) { try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { player.sendMessage(ChatColor.RED + "Invalid amount!"); return; } } for (int i = 0; i < amount; i++) { PDCHelper.setString(itemStack, "uuid", java.util.UUID.randomUUID().toString()); player.getInventory().addItem(itemStack); } } @TabCompleter(command = "sitem") public List<String> itemTabCompleter(Player player, String[] args) { // Smart tab completer to only serve the correct part :) if (args.length > 1) { return List.of(); } if (args.length == 0) { return ItemManager.ITEMS_LIST.keySet().stream().toList(); } String id = args[0].toLowerCase(); return ItemManager.ITEMS_LIST.keySet().stream().filter(s -> s.startsWith(id)).toList(); } @Command(name = "stat", description = "Stat command", op = true) public void statCommand(Player player, String[] args) { if (args.length == 0) { player.sendMessage(ChatColor.RED + "Usage: /stat stat value"); return; } Stats stat; double value = 0; try { stat = Stats.valueOf(args[0].toUpperCase()); value = Double.parseDouble(args[1]); } catch (Exception e) { player.sendMessage(ChatColor.RED + "Invalid stat or value!"); return; } player.sendMessage(ChatColor.GREEN + "Setting " + stat + " to " + value);
package com.sweattypalms.skyblock.commands.handlers; public class AdminCommands { @Command(name = "mob", description = "Mob command", op = true) public void mobCommand(Player player, String[] args) { if (args.length == 0) { player.sendMessage(ChatColor.RED + "Usage: /mob id"); return; } String id = args[0].toLowerCase(); SkyblockMob skyblockMob = getAndSpawnMob(id, player); if (skyblockMob == null) return; player.sendMessage(ChatColor.RED + "Successfully spawned: " + skyblockMob.getNameAttribute(NameAttributes.CUSTOM_NAME)); } @Command(name = "sitem", description = "Item command", op = true) public void itemCommand(Player player, String[] args) { if (args.length == 0) { ItemsGUI gui = new ItemsGUI(); gui.open(player); String message = ChatColor.YELLOW + "If you want to get an item of a specific id, do:"; message += "\n" + ChatColor.YELLOW + "/item <id> [optional: amount]"; player.sendMessage(message); return; } String id = args[0].toLowerCase(); if (!ItemManager.ITEMS_LIST.containsKey(id)) { player.sendMessage(ChatColor.RED + "Invalid item ID!"); return; } SkyblockItem skyblockItem = ItemManager.ITEMS_LIST.get(id); ItemStack itemStack = skyblockItem.toItemStack(); int amount = 1; if (args.length > 1) { try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { player.sendMessage(ChatColor.RED + "Invalid amount!"); return; } } for (int i = 0; i < amount; i++) { PDCHelper.setString(itemStack, "uuid", java.util.UUID.randomUUID().toString()); player.getInventory().addItem(itemStack); } } @TabCompleter(command = "sitem") public List<String> itemTabCompleter(Player player, String[] args) { // Smart tab completer to only serve the correct part :) if (args.length > 1) { return List.of(); } if (args.length == 0) { return ItemManager.ITEMS_LIST.keySet().stream().toList(); } String id = args[0].toLowerCase(); return ItemManager.ITEMS_LIST.keySet().stream().filter(s -> s.startsWith(id)).toList(); } @Command(name = "stat", description = "Stat command", op = true) public void statCommand(Player player, String[] args) { if (args.length == 0) { player.sendMessage(ChatColor.RED + "Usage: /stat stat value"); return; } Stats stat; double value = 0; try { stat = Stats.valueOf(args[0].toUpperCase()); value = Double.parseDouble(args[1]); } catch (Exception e) { player.sendMessage(ChatColor.RED + "Invalid stat or value!"); return; } player.sendMessage(ChatColor.GREEN + "Setting " + stat + " to " + value);
SkyblockPlayer skyblockPlayer = SkyblockPlayer.getSkyblockPlayer(player);
13
2023-11-15 15:05:58+00:00
24k
GoogleCloudPlatform/dataflow-ordered-processing
business-model/src/main/java/com/google/cloud/orderbook/MatcherContext.java
[ { "identifier": "OrderBookEvent", "path": "business-model/src/main/java/com/google/cloud/orderbook/model/OrderBookEvent.java", "snippet": "public final class OrderBookEvent extends\n com.google.protobuf.GeneratedMessageV3 implements\n // @@protoc_insertion_point(message_implements:OrderBookEvent)\...
import java.util.Iterator; import java.util.List; import java.util.concurrent.Callable; import com.google.cloud.orderbook.model.OrderBookEvent; import com.google.cloud.orderbook.model.OrderBookEvent.Side;
19,202
this.nextBucketTime = startTimeMillis; this.maxDurationSeconds = maxSeconds; this.maxEvents = maxEvents; } public void add(long delay, Callable<List<OrderBookEvent>> work) { this.que.add(delay, work); } public void addAtShutdown(Callable<List<OrderBookEvent>> work) { this.que.addAtShutdown(work); } private long getNextEventTimeMillis() { long eventTimeMillis; // Just use system time and go as fast as possible if (mode != TimeThrottleMode.UNTHROTTLED_EVENTS_THROTTLED_SIMULATED_TIME) { eventTimeMillis = System.currentTimeMillis(); } // // Now we need to calculate the synthetic time (bucketing) // // Count events in the bucket and total events eventsInBucket ++; totalEvents ++; // If bucket is full, need to delay and/or shift bucket if (eventsInBucket == eventsPerBucket) { // If throttled system time, we need a real delay // (we don't need absolute precision, so interruptions we can ignore) if (mode == TimeThrottleMode.THROTTLED_SYSTEM_TIME) { long neededDelay = nextBucketTime - System.currentTimeMillis(); if (neededDelay > 0) { try { Thread.sleep(neededDelay); } catch (InterruptedException e) {} } } // Shift to next time bucket nextBucketTime += MILLISECOND_BUCKET_SIZE; eventsInBucket = 0; } // If it's simulated time, return the bucket time if (mode == TimeThrottleMode.UNTHROTTLED_EVENTS_THROTTLED_SIMULATED_TIME) { eventTimeMillis = nextBucketTime; } else { eventTimeMillis = System.currentTimeMillis(); } // Check if we need to shutdown the queue due to time if ((maxDurationSeconds > 0) && (eventTimeMillis - startTimeMillis)/1000 >= maxDurationSeconds) { this.que.shutdown(); } // Or shutdown due to max events if (maxEvents > 0 && totalEvents >= maxEvents) { this.que.shutdown(); } return eventTimeMillis; } OrderBookEvent.Builder buildFinalOrderBookEvent(long contractSeqId, long contractId) { long eventTimeMillis = getNextEventTimeMillis(); return OrderBookEvent.newBuilder() .setTimestampMS(eventTimeMillis) .setSeqId(nextSeqId++) .setContractSeqId(contractSeqId) .setContractId(contractId) .setLastMessage(false) .setSessionId(sessionId) .setLastContractMessage(true); } public OrderBookEvent.Builder buildFinalOrderBookEvent() { long eventTimeMillis = getNextEventTimeMillis(); return OrderBookEvent.newBuilder() .setTimestampMS(eventTimeMillis) .setSeqId(nextSeqId++) .setSessionId(sessionId) .setLastMessage(true); } OrderBookEvent.Builder buildOrderBookEvent(OrderBookEvent.Type type, long contractSeqId, long contractId, Order order) { long eventTimeMillis = getNextEventTimeMillis(); return OrderBookEvent.newBuilder() .setTimestampMS(eventTimeMillis) .setSeqId(nextSeqId++) .setContractSeqId(contractSeqId) .setContractId(contractId) .setLastMessage(false) .setSessionId(sessionId) .setLastContractMessage(false) .setType(type) .setOrderId(order.getOrderId()) .setPrice(order.getPrice()) .setSide(order.getSide()) .setQuantity(order.getQuantity()) .setQuantityRemaining(order.getQuantityRemaining()) .setQuantityFilled(0) .setMatchNumber(0); } @Override public Iterator<List<OrderBookEvent>> iterator() { return this.que; } private long currentOrderId = 1;
/* * 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 com.google.cloud.orderbook; public class MatcherContext implements Iterable<List<OrderBookEvent>> { enum TimeThrottleMode { /* Generate OrderBookEvents without throttling (no sleep), * and use the system time for the order events. */ UNTHROTTLED_EVENTS_SYSTEM_TIME, /* Generate OrderBookEvents without throttling (no sleep), * and generate a simulated time that is throttled at a certain rate */ UNTHROTTLED_EVENTS_THROTTLED_SIMULATED_TIME, /* Generate OrderBookEvents with throttling (sleep), * and use the system time for generation. */ THROTTLED_SYSTEM_TIME, } // Global Sequence ID private long nextSeqId = 1; // Queued producer -- used to synchronise the output of the matchers final private QueuedProducer<OrderBookEvent> que = new QueuedProducer<>(); // Minimum rate for simulated time (events per second) final private static long MINIMUM_RATE = 10; // Number of milliseconds in a bucket for throttling final private static long MILLISECOND_BUCKET_SIZE = 1000 / MINIMUM_RATE; // Throttling mode and number of events per second we expect final private TimeThrottleMode mode; final private long eventsPerBucket; final private long startTimeMillis; private final String sessionId; // Maximum duration (optional) final private long maxDurationSeconds; // Maximum number of events produced (optional) // Note this isn't strict -- once maxEvents is reached, shutdown will be initiated. // This means that slightly more events may be produced than maxEvents. final private long maxEvents; // Current throttling status private long eventsInBucket = 0; private long totalEvents = 0; private long nextBucketTime; // MatcherContextBuilder public static class Builder { private final String sessionId; private final TimeThrottleMode mode; private final long eventsPerSecond; Builder(String sessionId, TimeThrottleMode mode, long eventsPerSecond) { this.sessionId = sessionId; this.mode = mode; this.eventsPerSecond = eventsPerSecond; if (eventsPerSecond > 0 && eventsPerSecond < MINIMUM_RATE) { throw new RuntimeException( String.format("Event rate must be at least %d", MINIMUM_RATE)); } } private long startTimeMillis; public Builder withStartTimeMillis(long startTimeMillis) { this.startTimeMillis = startTimeMillis; return this; } private long maxSeconds; public Builder withMaxSeconds(long maxSeconds) { this.maxSeconds = maxSeconds; return this; } private long maxEvents; public Builder withMaxEvents(long maxEvents) { this.maxEvents = maxEvents; return this; } public MatcherContext build() { return new MatcherContext( mode, sessionId, eventsPerSecond, startTimeMillis, maxSeconds, maxEvents); } } /* * Use unthrottled event generation and the system time. * * This generates events as fast as it can (no sleeping, no delays), and uses the system time * for the events. * * Recommended for PubSub or Dataflow usage when you want to stream things as fast as you can. */ static public Builder build(String sessionId) { return new Builder(sessionId, TimeThrottleMode.UNTHROTTLED_EVENTS_SYSTEM_TIME, 0); } /* * This generates events as fast as it can (no sleeping, no delays), and uses a simulated time * at the specific events per second rate. * * Recommended for batch data generation (Dataflow) or testing purposes. */ static public Builder buildSimulated(String sessionId, long eventsPerSecond) { return new Builder(sessionId, TimeThrottleMode.UNTHROTTLED_EVENTS_THROTTLED_SIMULATED_TIME, eventsPerSecond); } /* * This generates events at the specific event rate using system time. * * Recommended for general PubSub or Dataflow usage. */ static public Builder buildThrottled(String sessionId, long eventsPerSecond) { return new Builder(sessionId, TimeThrottleMode.THROTTLED_SYSTEM_TIME, eventsPerSecond); } private MatcherContext(TimeThrottleMode mode, String sessionId, long eventsPerSecond, long startTimeMillis, long maxSeconds, long maxEvents) { this.mode = mode; this.sessionId = sessionId; this.eventsPerBucket = eventsPerSecond / (1000 / MILLISECOND_BUCKET_SIZE); this.startTimeMillis = startTimeMillis; this.nextBucketTime = startTimeMillis; this.maxDurationSeconds = maxSeconds; this.maxEvents = maxEvents; } public void add(long delay, Callable<List<OrderBookEvent>> work) { this.que.add(delay, work); } public void addAtShutdown(Callable<List<OrderBookEvent>> work) { this.que.addAtShutdown(work); } private long getNextEventTimeMillis() { long eventTimeMillis; // Just use system time and go as fast as possible if (mode != TimeThrottleMode.UNTHROTTLED_EVENTS_THROTTLED_SIMULATED_TIME) { eventTimeMillis = System.currentTimeMillis(); } // // Now we need to calculate the synthetic time (bucketing) // // Count events in the bucket and total events eventsInBucket ++; totalEvents ++; // If bucket is full, need to delay and/or shift bucket if (eventsInBucket == eventsPerBucket) { // If throttled system time, we need a real delay // (we don't need absolute precision, so interruptions we can ignore) if (mode == TimeThrottleMode.THROTTLED_SYSTEM_TIME) { long neededDelay = nextBucketTime - System.currentTimeMillis(); if (neededDelay > 0) { try { Thread.sleep(neededDelay); } catch (InterruptedException e) {} } } // Shift to next time bucket nextBucketTime += MILLISECOND_BUCKET_SIZE; eventsInBucket = 0; } // If it's simulated time, return the bucket time if (mode == TimeThrottleMode.UNTHROTTLED_EVENTS_THROTTLED_SIMULATED_TIME) { eventTimeMillis = nextBucketTime; } else { eventTimeMillis = System.currentTimeMillis(); } // Check if we need to shutdown the queue due to time if ((maxDurationSeconds > 0) && (eventTimeMillis - startTimeMillis)/1000 >= maxDurationSeconds) { this.que.shutdown(); } // Or shutdown due to max events if (maxEvents > 0 && totalEvents >= maxEvents) { this.que.shutdown(); } return eventTimeMillis; } OrderBookEvent.Builder buildFinalOrderBookEvent(long contractSeqId, long contractId) { long eventTimeMillis = getNextEventTimeMillis(); return OrderBookEvent.newBuilder() .setTimestampMS(eventTimeMillis) .setSeqId(nextSeqId++) .setContractSeqId(contractSeqId) .setContractId(contractId) .setLastMessage(false) .setSessionId(sessionId) .setLastContractMessage(true); } public OrderBookEvent.Builder buildFinalOrderBookEvent() { long eventTimeMillis = getNextEventTimeMillis(); return OrderBookEvent.newBuilder() .setTimestampMS(eventTimeMillis) .setSeqId(nextSeqId++) .setSessionId(sessionId) .setLastMessage(true); } OrderBookEvent.Builder buildOrderBookEvent(OrderBookEvent.Type type, long contractSeqId, long contractId, Order order) { long eventTimeMillis = getNextEventTimeMillis(); return OrderBookEvent.newBuilder() .setTimestampMS(eventTimeMillis) .setSeqId(nextSeqId++) .setContractSeqId(contractSeqId) .setContractId(contractId) .setLastMessage(false) .setSessionId(sessionId) .setLastContractMessage(false) .setType(type) .setOrderId(order.getOrderId()) .setPrice(order.getPrice()) .setSide(order.getSide()) .setQuantity(order.getQuantity()) .setQuantityRemaining(order.getQuantityRemaining()) .setQuantityFilled(0) .setMatchNumber(0); } @Override public Iterator<List<OrderBookEvent>> iterator() { return this.que; } private long currentOrderId = 1;
public Order newOrder(Side side, long price, long quantity) {
1
2023-11-15 21:26:06+00:00
24k
Hikaito/Fox-Engine
src/system/project/ProjectManager.java
[ { "identifier": "Program", "path": "src/system/Program.java", "snippet": "public class Program {\n\n //region initialization------------------------------------------\n\n // \"global\" variables\n private static UserSetting userSetting;\n private static MainWindow window;\n private static...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import system.Program; import system.backbone.ColorAdapter; import system.layerTree.RendererTypeAdapter; import system.layerTree.data.Folder; import system.layerTree.data.Layer; import system.layerTree.data.TreeUnit; import system.backbone.FileOperations; import system.backbone.VersionNumber; import system.gui.WarningWindow; import system.project.treeElements.ProjectFolderInterface; import system.project.treeElements.*; import system.gui.project.ProjectEditor; import system.gui.project.ProjectFileSelection; import system.gui.project.ProjectReconciliation; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.LinkedList; import java.util.SortedSet; import java.util.TreeSet;
18,086
package system.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectManager { // UUID methods public String getUUID(){return root.getUUID();} public boolean matchesUUID(String other){ return root.getUUID().equals(other); } public String getTitle(){return root.getTitle();} // reject if program number is lower than project
package system.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectManager { // UUID methods public String getUUID(){return root.getUUID();} public boolean matchesUUID(String other){ return root.getUUID().equals(other); } public String getTitle(){return root.getTitle();} // reject if program number is lower than project
public static boolean evaluateProjectNumber(VersionNumber program, VersionNumber project){
7
2023-11-12 21:12:21+00:00
24k
ryosoraa/E-Rapor
src/main/java/com/erapor/erapor/service/UserServices.java
[ { "identifier": "ApiException", "path": "src/main/java/com/erapor/erapor/exception/ApiException.java", "snippet": "public class ApiException extends RuntimeException{\n public ApiException(String message) {\n super(message);\n }\n}" }, { "identifier": "AccountsDAO", "path": "src...
import com.erapor.erapor.exception.ApiException; import com.erapor.erapor.model.DAO.AccountsDAO; import com.erapor.erapor.model.DTO.RegisterDTO; import com.erapor.erapor.repository.AccountsRepository; import com.erapor.erapor.security.BCrypt; import jakarta.validation.ConstraintViolation; import jakarta.validation.ConstraintViolationException; import jakarta.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Set;
16,494
package com.erapor.erapor.service; @Service public class UserServices { @Autowired
package com.erapor.erapor.service; @Service public class UserServices { @Autowired
AccountsRepository accountsRepository;
3
2023-11-11 19:40:43+00:00
24k
shizotoaster/thaumon
fabric/src/main/java/jdlenl/thaumon/client/fabric/ThaumonClientFabric.java
[ { "identifier": "ColorProviderRegistries", "path": "fabric/src/main/java/jdlenl/thaumon/color/fabric/ColorProviderRegistries.java", "snippet": "public class ColorProviderRegistries {\n public static void init() {\n ColorProviderRegistry.BLOCK.register(\n new BlockColorProvider()...
import jdlenl.thaumon.color.fabric.ColorProviderRegistries; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.minecraft.client.render.RenderLayer; import static jdlenl.thaumon.block.ThaumonBlocks.*;
14,799
package jdlenl.thaumon.client.fabric; public class ThaumonClientFabric implements ClientModInitializer { @Override public void onInitializeClient() { BlockRenderLayerMap.INSTANCE.putBlocks(RenderLayer.getTranslucent(), AMBERGLASS.get(), AMBERGLASS_PANE.get() ); BlockRenderLayerMap.INSTANCE.putBlocks(RenderLayer.getCutout(), GREATWOOD_WINDOW.get(), GREATWOOD_WINDOW_PANE.get(), SILVERWOOD_WINDOW.get(), SILVERWOOD_WINDOW_PANE.get(), ARCANE_STONE_WINDOW.get(), ARCANE_STONE_WINDOW_PANE.get(), ELDRITCH_STONE_WINDOW.get(), ELDRITCH_STONE_WINDOW_PANE.get(), ANCIENT_STONE_WINDOW.get(), ANCIENT_STONE_WINDOW_PANE.get(), SILVERWOOD_DOOR.get(), ANCIENT_STONE_DOOR.get(), GREATWOOD_DOOR.get(), GILDED_GREATWOOD_DOOR.get(), SILVERWOOD_TRAPDOOR.get(), GREATWOOD_TRAPDOOR.get(), GILDED_GREATWOOD_TRAPDOOR.get(), RESEARCH_NOTES.get() );
package jdlenl.thaumon.client.fabric; public class ThaumonClientFabric implements ClientModInitializer { @Override public void onInitializeClient() { BlockRenderLayerMap.INSTANCE.putBlocks(RenderLayer.getTranslucent(), AMBERGLASS.get(), AMBERGLASS_PANE.get() ); BlockRenderLayerMap.INSTANCE.putBlocks(RenderLayer.getCutout(), GREATWOOD_WINDOW.get(), GREATWOOD_WINDOW_PANE.get(), SILVERWOOD_WINDOW.get(), SILVERWOOD_WINDOW_PANE.get(), ARCANE_STONE_WINDOW.get(), ARCANE_STONE_WINDOW_PANE.get(), ELDRITCH_STONE_WINDOW.get(), ELDRITCH_STONE_WINDOW_PANE.get(), ANCIENT_STONE_WINDOW.get(), ANCIENT_STONE_WINDOW_PANE.get(), SILVERWOOD_DOOR.get(), ANCIENT_STONE_DOOR.get(), GREATWOOD_DOOR.get(), GILDED_GREATWOOD_DOOR.get(), SILVERWOOD_TRAPDOOR.get(), GREATWOOD_TRAPDOOR.get(), GILDED_GREATWOOD_TRAPDOOR.get(), RESEARCH_NOTES.get() );
ColorProviderRegistries.init();
0
2023-11-16 06:03:29+00:00
24k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/predictionengine/predictions/PredictionEngineWater.java
[ { "identifier": "GrimPlayer", "path": "src/main/java/ac/grim/grimac/player/GrimPlayer.java", "snippet": "public class GrimPlayer {\n public final UUID playerUUID;\n public final int entityID;\n public final Player bukkitPlayer;\n // Determining player ping\n // The difference between keep...
import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.utils.collisions.datatypes.SimpleCollisionBox; import ac.grim.grimac.utils.data.VectorData; import ac.grim.grimac.utils.enums.FluidTag; import ac.grim.grimac.utils.nmsutil.Collisions; import ac.grim.grimac.utils.nmsutil.FluidFallingAdjustedMovement; import io.github.retrooper.packetevents.utils.player.ClientVersion; import org.bukkit.util.Vector; import java.util.HashSet; import java.util.Set;
19,928
package ac.grim.grimac.predictionengine.predictions; public class PredictionEngineWater extends PredictionEngine { boolean isFalling; double playerGravity; float swimmingSpeed; float swimmingFriction; double lastY; public void guessBestMovement(float swimmingSpeed, GrimPlayer player, boolean isFalling, double playerGravity, float swimmingFriction, double lastY) { this.isFalling = isFalling; this.playerGravity = playerGravity; this.swimmingSpeed = swimmingSpeed; this.swimmingFriction = swimmingFriction; this.lastY = lastY; super.guessBestMovement(swimmingSpeed, player); } public static void staticVectorEndOfTick(GrimPlayer player, Vector vector, float swimmingFriction, double playerGravity, boolean isFalling) { vector.multiply(new Vector(swimmingFriction, 0.8F, swimmingFriction)); Vector fluidVector = FluidFallingAdjustedMovement.getFluidFallingAdjustedMovement(player, playerGravity, isFalling, vector); vector.setX(fluidVector.getX()); vector.setY(fluidVector.getY()); vector.setZ(fluidVector.getZ()); } @Override public void addJumpsToPossibilities(GrimPlayer player, Set<VectorData> existingVelocities) { for (VectorData vector : new HashSet<>(existingVelocities)) { existingVelocities.add(vector.returnNewModified(vector.vector.clone().add(new Vector(0, 0.04, 0)), VectorData.VectorType.Jump)); if (player.slightlyTouchingWater && player.lastOnGround && !player.onGround) { Vector withJump = vector.vector.clone(); super.doJump(player, withJump); existingVelocities.add(new VectorData(withJump, vector, VectorData.VectorType.Jump)); } } } @Override public void endOfTick(GrimPlayer player, double playerGravity, float friction) { super.endOfTick(player, playerGravity, friction); for (VectorData vector : player.getPossibleVelocitiesMinusKnockback()) { staticVectorEndOfTick(player, vector.vector, swimmingFriction, playerGravity, isFalling); } } @Override public Set<VectorData> fetchPossibleStartTickVectors(GrimPlayer player) { // "hacky" climbing where player enters ladder within 0.03 movement (WHY THE FUCK DOES 0.03 EXIST???) if (player.lastWasClimbing == 0 && player.pointThreeEstimator.isNearClimbable() && (player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14) || !Collisions.isEmpty(player, player.boundingBox.copy().expand(
package ac.grim.grimac.predictionengine.predictions; public class PredictionEngineWater extends PredictionEngine { boolean isFalling; double playerGravity; float swimmingSpeed; float swimmingFriction; double lastY; public void guessBestMovement(float swimmingSpeed, GrimPlayer player, boolean isFalling, double playerGravity, float swimmingFriction, double lastY) { this.isFalling = isFalling; this.playerGravity = playerGravity; this.swimmingSpeed = swimmingSpeed; this.swimmingFriction = swimmingFriction; this.lastY = lastY; super.guessBestMovement(swimmingSpeed, player); } public static void staticVectorEndOfTick(GrimPlayer player, Vector vector, float swimmingFriction, double playerGravity, boolean isFalling) { vector.multiply(new Vector(swimmingFriction, 0.8F, swimmingFriction)); Vector fluidVector = FluidFallingAdjustedMovement.getFluidFallingAdjustedMovement(player, playerGravity, isFalling, vector); vector.setX(fluidVector.getX()); vector.setY(fluidVector.getY()); vector.setZ(fluidVector.getZ()); } @Override public void addJumpsToPossibilities(GrimPlayer player, Set<VectorData> existingVelocities) { for (VectorData vector : new HashSet<>(existingVelocities)) { existingVelocities.add(vector.returnNewModified(vector.vector.clone().add(new Vector(0, 0.04, 0)), VectorData.VectorType.Jump)); if (player.slightlyTouchingWater && player.lastOnGround && !player.onGround) { Vector withJump = vector.vector.clone(); super.doJump(player, withJump); existingVelocities.add(new VectorData(withJump, vector, VectorData.VectorType.Jump)); } } } @Override public void endOfTick(GrimPlayer player, double playerGravity, float friction) { super.endOfTick(player, playerGravity, friction); for (VectorData vector : player.getPossibleVelocitiesMinusKnockback()) { staticVectorEndOfTick(player, vector.vector, swimmingFriction, playerGravity, isFalling); } } @Override public Set<VectorData> fetchPossibleStartTickVectors(GrimPlayer player) { // "hacky" climbing where player enters ladder within 0.03 movement (WHY THE FUCK DOES 0.03 EXIST???) if (player.lastWasClimbing == 0 && player.pointThreeEstimator.isNearClimbable() && (player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14) || !Collisions.isEmpty(player, player.boundingBox.copy().expand(
player.clientVelocity.getX(), 0, player.clientVelocity.getZ()).expand(0.5, -SimpleCollisionBox.COLLISION_EPSILON, 0.5)))) {
1
2023-11-11 05:14:12+00:00
24k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/dialog/ShareDialog.java
[ { "identifier": "BaseAdapter", "path": "library/base/src/main/java/com/hjq/base/BaseAdapter.java", "snippet": "public abstract class BaseAdapter<VH extends BaseAdapter<?>.ViewHolder>\n extends RecyclerView.Adapter<VH> implements ResourcesAction {\n\n /** 上下文对象 */\n private final Context mCo...
import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.hjq.base.BaseAdapter; import com.hjq.base.BaseDialog; import com.buaa.food.R; import com.buaa.food.app.AppAdapter; import com.hjq.toast.ToastUtils; import com.hjq.umeng.Platform; import com.hjq.umeng.UmengClient; import com.hjq.umeng.UmengShare; import com.umeng.socialize.ShareAction; import com.umeng.socialize.ShareContent; import com.umeng.socialize.media.UMEmoji; import com.umeng.socialize.media.UMImage; import com.umeng.socialize.media.UMMin; import com.umeng.socialize.media.UMQQMini; import com.umeng.socialize.media.UMVideo; import com.umeng.socialize.media.UMWeb; import com.umeng.socialize.media.UMusic; import java.util.ArrayList; import java.util.List;
17,331
package com.buaa.food.ui.dialog; public final class ShareDialog { public static final class Builder extends BaseDialog.Builder<Builder> implements BaseAdapter.OnItemClickListener { private final RecyclerView mRecyclerView; private final ShareAdapter mAdapter; private final ShareAction mShareAction; private final ShareBean mCopyLink; @Nullable private UmengShare.OnShareListener mListener; public Builder(Activity activity) { super(activity); setContentView(R.layout.share_dialog); final List<ShareBean> data = new ArrayList<>(); data.add(new ShareBean(getDrawable(R.drawable.share_wechat_ic), getString(R.string.share_platform_wechat), Platform.WECHAT)); data.add(new ShareBean(getDrawable(R.drawable.share_moment_ic), getString(R.string.share_platform_moment), Platform.CIRCLE)); data.add(new ShareBean(getDrawable(R.drawable.share_qq_ic), getString(R.string.share_platform_qq), Platform.QQ)); data.add(new ShareBean(getDrawable(R.drawable.share_qzone_ic), getString(R.string.share_platform_qzone), Platform.QZONE)); mCopyLink = new ShareBean(getDrawable(R.drawable.share_link_ic), getString(R.string.share_platform_link), null); mAdapter = new ShareAdapter(activity); mAdapter.setData(data); mAdapter.setOnItemClickListener(this); mRecyclerView = findViewById(R.id.rv_share_list); mRecyclerView.setLayoutManager(new GridLayoutManager(activity, data.size())); mRecyclerView.setAdapter(mAdapter); mShareAction = new ShareAction(activity); } /** * 分享网页链接:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu7F51u9875u94FEu63A51 */ public Builder setShareLink(UMWeb content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享图片:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu56FEu72473 */ public Builder setShareImage(UMImage content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享纯文本:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu7EAFu6587u672C5 */ public Builder setShareText(String content) { mShareAction.withText(content); refreshShareOptions(); return this; } /** * 分享音乐:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu97F3u4E507 */ public Builder setShareMusic(UMusic content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享视频:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu89C6u98916 */ public Builder setShareVideo(UMVideo content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享 Gif 表情:https://developer.umeng.com/docs/128606/detail/193883#h2--gif-8 */ public Builder setShareEmoji(UMEmoji content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享微信小程序:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu5C0Fu7A0Bu5E8F2 */ public Builder setShareMin(UMMin content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享 QQ 小程序:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu5C0Fu7A0Bu5E8F2 */ public Builder setShareMin(UMQQMini content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 设置回调监听器 */ public Builder setListener(UmengShare.OnShareListener listener) { mListener = listener; return this; } /** * {@link BaseAdapter.OnItemClickListener} */ @Override public void onItemClick(RecyclerView recyclerView, View itemView, int position) { Platform platform = mAdapter.getItem(position).sharePlatform; if (platform != null) {
package com.buaa.food.ui.dialog; public final class ShareDialog { public static final class Builder extends BaseDialog.Builder<Builder> implements BaseAdapter.OnItemClickListener { private final RecyclerView mRecyclerView; private final ShareAdapter mAdapter; private final ShareAction mShareAction; private final ShareBean mCopyLink; @Nullable private UmengShare.OnShareListener mListener; public Builder(Activity activity) { super(activity); setContentView(R.layout.share_dialog); final List<ShareBean> data = new ArrayList<>(); data.add(new ShareBean(getDrawable(R.drawable.share_wechat_ic), getString(R.string.share_platform_wechat), Platform.WECHAT)); data.add(new ShareBean(getDrawable(R.drawable.share_moment_ic), getString(R.string.share_platform_moment), Platform.CIRCLE)); data.add(new ShareBean(getDrawable(R.drawable.share_qq_ic), getString(R.string.share_platform_qq), Platform.QQ)); data.add(new ShareBean(getDrawable(R.drawable.share_qzone_ic), getString(R.string.share_platform_qzone), Platform.QZONE)); mCopyLink = new ShareBean(getDrawable(R.drawable.share_link_ic), getString(R.string.share_platform_link), null); mAdapter = new ShareAdapter(activity); mAdapter.setData(data); mAdapter.setOnItemClickListener(this); mRecyclerView = findViewById(R.id.rv_share_list); mRecyclerView.setLayoutManager(new GridLayoutManager(activity, data.size())); mRecyclerView.setAdapter(mAdapter); mShareAction = new ShareAction(activity); } /** * 分享网页链接:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu7F51u9875u94FEu63A51 */ public Builder setShareLink(UMWeb content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享图片:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu56FEu72473 */ public Builder setShareImage(UMImage content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享纯文本:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu7EAFu6587u672C5 */ public Builder setShareText(String content) { mShareAction.withText(content); refreshShareOptions(); return this; } /** * 分享音乐:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu97F3u4E507 */ public Builder setShareMusic(UMusic content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享视频:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu89C6u98916 */ public Builder setShareVideo(UMVideo content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享 Gif 表情:https://developer.umeng.com/docs/128606/detail/193883#h2--gif-8 */ public Builder setShareEmoji(UMEmoji content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享微信小程序:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu5C0Fu7A0Bu5E8F2 */ public Builder setShareMin(UMMin content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 分享 QQ 小程序:https://developer.umeng.com/docs/128606/detail/193883#h2-u5206u4EABu5C0Fu7A0Bu5E8F2 */ public Builder setShareMin(UMQQMini content) { mShareAction.withMedia(content); refreshShareOptions(); return this; } /** * 设置回调监听器 */ public Builder setListener(UmengShare.OnShareListener listener) { mListener = listener; return this; } /** * {@link BaseAdapter.OnItemClickListener} */ @Override public void onItemClick(RecyclerView recyclerView, View itemView, int position) { Platform platform = mAdapter.getItem(position).sharePlatform; if (platform != null) {
UmengClient.share(getActivity(), platform, mShareAction, mListener);
4
2023-11-14 10:04:26+00:00
24k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/block/processed/BlockModel.java
[ { "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...
import useless.dragonfly.helper.ModelHelper; import useless.dragonfly.model.block.data.ModelData; import useless.dragonfly.model.block.data.PositionData; import useless.dragonfly.registries.TextureRegistry; import useless.dragonfly.utilities.NamespaceId; import javax.annotation.Nonnull; import java.util.HashMap;
16,368
package useless.dragonfly.model.block.processed; public class BlockModel { private static final HashMap<String, PositionData> defaultDisplays = new HashMap<>(); static { PositionData gui = new PositionData(); gui.rotation = new double[]{30, 225, 0}; gui.translation = new double[] {0, 0, 0}; gui.scale = new double[]{0.625, 0.625, 0.625}; PositionData ground = new PositionData(); ground.rotation = new double[]{0, 0, 0}; ground.translation = new double[] {0, 3, 0}; ground.scale = new double[]{0.25, 0.25, 0.25}; PositionData right_3rd = new PositionData(); right_3rd.rotation = new double[]{75, 45, 0}; right_3rd.translation = new double[] {0, 2.5, 0}; right_3rd.scale = new double[]{0.375, 0.375, 0.375}; PositionData right_first = new PositionData(); right_first.rotation = new double[]{0, 45, 0}; right_first.translation = new double[] {0, 0, 0}; right_first.scale = new double[]{0.4, 0.4, 0.4}; defaultDisplays.put("gui", gui); defaultDisplays.put("ground", ground); defaultDisplays.put("thirdperson_righthand", right_3rd); defaultDisplays.put("firstperson_righthand", right_first); } public BlockCube[] blockCubes = new BlockCube[0]; protected ModelData modelData; protected BlockModel parentModel; public HashMap<String, String> textureMap; public HashMap<String, PositionData> display; public final NamespaceId namespaceId; public BlockModel(NamespaceId namespaceId){ this.namespaceId = namespaceId; refreshModel(); } public void refreshModel(){ this.modelData = ModelHelper.loadBlockModel(namespaceId); textureMap = new HashMap<>(); display = new HashMap<>(); if (modelData.parent != null){ // Has parent Model String namespace; String modelName; if (modelData.parent.contains(":")){ namespace = modelData.parent.split(":")[0]; modelName = modelData.parent.split(":")[1]; } else { namespace = NamespaceId.coreNamespaceId; modelName = modelData.parent; } parentModel = ModelHelper.getOrCreateBlockModel(namespace, modelName ); textureMap.putAll(parentModel.textureMap); display.putAll(parentModel.display); } textureMap.putAll(modelData.textures); display.putAll(modelData.display); // Initialize textures for (String texture: textureMap.values()) { if (texture == null) continue;
package useless.dragonfly.model.block.processed; public class BlockModel { private static final HashMap<String, PositionData> defaultDisplays = new HashMap<>(); static { PositionData gui = new PositionData(); gui.rotation = new double[]{30, 225, 0}; gui.translation = new double[] {0, 0, 0}; gui.scale = new double[]{0.625, 0.625, 0.625}; PositionData ground = new PositionData(); ground.rotation = new double[]{0, 0, 0}; ground.translation = new double[] {0, 3, 0}; ground.scale = new double[]{0.25, 0.25, 0.25}; PositionData right_3rd = new PositionData(); right_3rd.rotation = new double[]{75, 45, 0}; right_3rd.translation = new double[] {0, 2.5, 0}; right_3rd.scale = new double[]{0.375, 0.375, 0.375}; PositionData right_first = new PositionData(); right_first.rotation = new double[]{0, 45, 0}; right_first.translation = new double[] {0, 0, 0}; right_first.scale = new double[]{0.4, 0.4, 0.4}; defaultDisplays.put("gui", gui); defaultDisplays.put("ground", ground); defaultDisplays.put("thirdperson_righthand", right_3rd); defaultDisplays.put("firstperson_righthand", right_first); } public BlockCube[] blockCubes = new BlockCube[0]; protected ModelData modelData; protected BlockModel parentModel; public HashMap<String, String> textureMap; public HashMap<String, PositionData> display; public final NamespaceId namespaceId; public BlockModel(NamespaceId namespaceId){ this.namespaceId = namespaceId; refreshModel(); } public void refreshModel(){ this.modelData = ModelHelper.loadBlockModel(namespaceId); textureMap = new HashMap<>(); display = new HashMap<>(); if (modelData.parent != null){ // Has parent Model String namespace; String modelName; if (modelData.parent.contains(":")){ namespace = modelData.parent.split(":")[0]; modelName = modelData.parent.split(":")[1]; } else { namespace = NamespaceId.coreNamespaceId; modelName = modelData.parent; } parentModel = ModelHelper.getOrCreateBlockModel(namespace, modelName ); textureMap.putAll(parentModel.textureMap); display.putAll(parentModel.display); } textureMap.putAll(modelData.textures); display.putAll(modelData.display); // Initialize textures for (String texture: textureMap.values()) { if (texture == null) continue;
TextureRegistry.softRegisterTexture(texture);
3
2023-11-16 01:10:52+00:00
24k
AntonyCheng/ai-bi
src/test/java/top/sharehome/springbootinittemplate/redisson/TestRedisson.java
[ { "identifier": "CustomizeReturnException", "path": "src/main/java/top/sharehome/springbootinittemplate/exception/customize/CustomizeReturnException.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class CustomizeReturnException extends RuntimeException {\n\n private ReturnCode ...
import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ThreadUtils; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException; import top.sharehome.springbootinittemplate.utils.redisson.cache.CacheUtils; import top.sharehome.springbootinittemplate.utils.redisson.lock.LockUtils; import top.sharehome.springbootinittemplate.utils.redisson.lock.function.SuccessFunction; import top.sharehome.springbootinittemplate.utils.redisson.lock.function.VoidFunction; import top.sharehome.springbootinittemplate.utils.redisson.rateLimit.RateLimitUtils; import java.time.Duration; import java.util.*;
15,228
package top.sharehome.springbootinittemplate.redisson; /** * 测试缓存类 * * @author AntonyCheng */ @SpringBootTest @Slf4j public class TestRedisson { /** * 测试缓存工具类 */ @Test void testCacheUtils() { // 测试字符串 CacheUtils.putString("test", "test"); System.out.println(CacheUtils.getString("test")); System.out.println(CacheUtils.existsString("test")); CacheUtils.deleteString("test"); // 测试数字 CacheUtils.putNumber("test", 9999999999L); System.out.println(CacheUtils.getNumberDoubleValue("test")); System.out.println(CacheUtils.existsNumber("test")); CacheUtils.deleteNumber("test"); // 测试List List<String> l = new ArrayList<String>() { { add("test1"); add("test2"); } }; CacheUtils.putList("test", l); System.out.println(CacheUtils.getList("test")); System.out.println(CacheUtils.existsList("test")); CacheUtils.deleteList("test"); // 测试Set Set<String> s = new HashSet<String>() { { add("test1"); add("test2"); } }; CacheUtils.putSet("test", s); System.out.println(CacheUtils.getSet("test")); System.out.println(CacheUtils.existsSet("test")); CacheUtils.deleteSet("test"); // 测试Map Map<String, String> m = new HashMap<String, String>() { { put("test1", "test1"); put("test2", "test2"); } }; CacheUtils.putMap("test", m); System.out.println(CacheUtils.getMap("test")); System.out.println(CacheUtils.existsMap("test")); CacheUtils.deleteMap("test"); // 测试使用通配符模糊操作 for (int i = 0; i < 100; i++) { HashMap<String, String> stringStringHashMap = new HashMap<>(); stringStringHashMap.put("test" + i, "test" + i); CacheUtils.put("test" + i, stringStringHashMap); } List<String> keysByPattern = CacheUtils.getKeysByPattern("test*"); Map<String, Object> keyValuesByPattern = CacheUtils.getKeyValuesByPattern("test*"); CacheUtils.deleteByPattern("test*"); } /** * 测试限流工具类 */ @Test void testRateLimitUtils() throws InterruptedException { for (int i = 0; i < 5; i++) { try { RateLimitUtils.doRateLimit("test"); System.out.println(i); } catch (CustomizeReturnException e) { System.out.println("请求太多,请稍后"); } } ThreadUtils.sleep(Duration.ofSeconds(2)); for (int i = 0; i < 10; i++) { try { RateLimitUtils.doRateLimit("test"); System.out.println(i); } catch (CustomizeReturnException e) { System.out.println("请求太多,请稍后"); } } } /** * 测试无论获取锁成功与否均无返回值的分布式锁 */ @Test void testLockUtils1() { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { int finalI = i + 1; LockUtils.lockEvent("test", (VoidFunction) () -> { System.out.println("子线程第" + finalI + "次拿到锁"); try { ThreadUtils.sleep(Duration.ofMillis(1000)); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("子线程第" + finalI + "次释放锁"); }); } } }).start(); for (int i = 0; i < 10; i++) { int finalI = i + 1; LockUtils.lockEvent("test", (VoidFunction) () -> { System.out.println("主线程第" + finalI + "次拿到锁"); try { ThreadUtils.sleep(Duration.ofMillis(1000)); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("主线程第" + finalI + "次释放锁"); }); } while (true) { } } /** * 测试无论获取锁成功与否均带有boolean类型返回值的分布式锁 * 这个和测试无论获取锁成功与否均带有自定义类型返回值的分布式锁大同小异 */ @Test void testLockUtils2() { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { int finalI = i + 1;
package top.sharehome.springbootinittemplate.redisson; /** * 测试缓存类 * * @author AntonyCheng */ @SpringBootTest @Slf4j public class TestRedisson { /** * 测试缓存工具类 */ @Test void testCacheUtils() { // 测试字符串 CacheUtils.putString("test", "test"); System.out.println(CacheUtils.getString("test")); System.out.println(CacheUtils.existsString("test")); CacheUtils.deleteString("test"); // 测试数字 CacheUtils.putNumber("test", 9999999999L); System.out.println(CacheUtils.getNumberDoubleValue("test")); System.out.println(CacheUtils.existsNumber("test")); CacheUtils.deleteNumber("test"); // 测试List List<String> l = new ArrayList<String>() { { add("test1"); add("test2"); } }; CacheUtils.putList("test", l); System.out.println(CacheUtils.getList("test")); System.out.println(CacheUtils.existsList("test")); CacheUtils.deleteList("test"); // 测试Set Set<String> s = new HashSet<String>() { { add("test1"); add("test2"); } }; CacheUtils.putSet("test", s); System.out.println(CacheUtils.getSet("test")); System.out.println(CacheUtils.existsSet("test")); CacheUtils.deleteSet("test"); // 测试Map Map<String, String> m = new HashMap<String, String>() { { put("test1", "test1"); put("test2", "test2"); } }; CacheUtils.putMap("test", m); System.out.println(CacheUtils.getMap("test")); System.out.println(CacheUtils.existsMap("test")); CacheUtils.deleteMap("test"); // 测试使用通配符模糊操作 for (int i = 0; i < 100; i++) { HashMap<String, String> stringStringHashMap = new HashMap<>(); stringStringHashMap.put("test" + i, "test" + i); CacheUtils.put("test" + i, stringStringHashMap); } List<String> keysByPattern = CacheUtils.getKeysByPattern("test*"); Map<String, Object> keyValuesByPattern = CacheUtils.getKeyValuesByPattern("test*"); CacheUtils.deleteByPattern("test*"); } /** * 测试限流工具类 */ @Test void testRateLimitUtils() throws InterruptedException { for (int i = 0; i < 5; i++) { try { RateLimitUtils.doRateLimit("test"); System.out.println(i); } catch (CustomizeReturnException e) { System.out.println("请求太多,请稍后"); } } ThreadUtils.sleep(Duration.ofSeconds(2)); for (int i = 0; i < 10; i++) { try { RateLimitUtils.doRateLimit("test"); System.out.println(i); } catch (CustomizeReturnException e) { System.out.println("请求太多,请稍后"); } } } /** * 测试无论获取锁成功与否均无返回值的分布式锁 */ @Test void testLockUtils1() { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { int finalI = i + 1; LockUtils.lockEvent("test", (VoidFunction) () -> { System.out.println("子线程第" + finalI + "次拿到锁"); try { ThreadUtils.sleep(Duration.ofMillis(1000)); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("子线程第" + finalI + "次释放锁"); }); } } }).start(); for (int i = 0; i < 10; i++) { int finalI = i + 1; LockUtils.lockEvent("test", (VoidFunction) () -> { System.out.println("主线程第" + finalI + "次拿到锁"); try { ThreadUtils.sleep(Duration.ofMillis(1000)); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("主线程第" + finalI + "次释放锁"); }); } while (true) { } } /** * 测试无论获取锁成功与否均带有boolean类型返回值的分布式锁 * 这个和测试无论获取锁成功与否均带有自定义类型返回值的分布式锁大同小异 */ @Test void testLockUtils2() { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { int finalI = i + 1;
boolean result = LockUtils.lockEvent("test", (SuccessFunction) () -> {
3
2023-11-12 07:49:59+00:00
24k
Shushandr/offroad
src/net/osmand/plus/render/TextRenderer.java
[ { "identifier": "PlatformUtil", "path": "src/net/osmand/PlatformUtil.java", "snippet": "public class PlatformUtil {\n\t\n\tpublic static Log getLog(Class<?> cl){\n\t\treturn LogFactory.getLog(cl);\n\t}\n\t\n\tpublic static XmlPullParser newXMLPullParser() throws XmlPullParserException{\n\t\treturn new o...
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.commons.logging.Log; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TIntObjectProcedure; import net.osmand.PlatformUtil; import net.osmand.binary.BinaryMapDataObject; import net.osmand.binary.BinaryMapIndexReader.TagValuePair; import net.osmand.data.QuadRect; import net.osmand.data.QuadTree; import net.osmand.plus.render.OsmandRenderer.RenderingContext; import net.osmand.plus.render.OsmandRenderer.TextInfo; import net.osmand.render.RenderingRuleSearchRequest; import net.osmand.render.RenderingRulesStorage; import net.osmand.util.Algorithms; import net.sf.junidecode.Junidecode; import net.sourceforge.offroad.TextStroke; import net.sourceforge.offroad.ui.ColorUtils;
18,283
package net.osmand.plus.render; public class TextRenderer { private static final int MINIMAL_DISTANCE_BETWEEN_SHIELDS_IN_PIXEL = 200; private final static Log log = PlatformUtil.getLog(TextRenderer.class); // private Paint paintText; // private Paint paintIcon; // private Typeface defaultTypeface; // private Typeface boldItalicTypeface; // private Typeface italicTypeface; // private Typeface boldTypeface; static class TextDrawInfo { public TextDrawInfo(String text) { this.text = text; } String text = null; Path2D drawOnPath = null; QuadRect bounds = null; float vOffset = 0; float centerX = 0; float pathRotate = 0; float centerY = 0; float textSize = 0; float minDistance = 0; int textColor = Color.BLACK.getRGB(); int textShadow = 0; int textWrap = 0; boolean bold = false; boolean italic = false; String shieldRes = null; String shieldResIcon = null; int textOrder = 100; int textShadowColor = Color.WHITE.getRGB();
package net.osmand.plus.render; public class TextRenderer { private static final int MINIMAL_DISTANCE_BETWEEN_SHIELDS_IN_PIXEL = 200; private final static Log log = PlatformUtil.getLog(TextRenderer.class); // private Paint paintText; // private Paint paintIcon; // private Typeface defaultTypeface; // private Typeface boldItalicTypeface; // private Typeface italicTypeface; // private Typeface boldTypeface; static class TextDrawInfo { public TextDrawInfo(String text) { this.text = text; } String text = null; Path2D drawOnPath = null; QuadRect bounds = null; float vOffset = 0; float centerX = 0; float pathRotate = 0; float centerY = 0; float textSize = 0; float minDistance = 0; int textColor = Color.BLACK.getRGB(); int textShadow = 0; int textWrap = 0; boolean bold = false; boolean italic = false; String shieldRes = null; String shieldResIcon = null; int textOrder = 100; int textShadowColor = Color.WHITE.getRGB();
public void fillProperties(RenderingContext rc, RenderingRuleSearchRequest render, float centerX, float centerY) {
5
2023-11-15 05:04:55+00:00
24k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/service/impl/HrmInsuranceSchemeServiceImpl.java
[ { "identifier": "OperationLog", "path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperationLog.java", "snippet": "@Getter\n@Setter\npublic class OperationLog {\n //操作对象\n private Object operationObject;\n //操作详情\n private String operationInfo;\n\n private BehaviorEnu...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.http.HttpUtil; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import com.aliyun.openservices.shade.com.google.common.collect.Range; import com.kakarote.common.log.entity.OperationLog; import com.kakarote.common.log.enums.BehaviorEnum; import com.kakarote.core.common.cache.HrmCacheKey; import com.kakarote.core.entity.BasePage; import com.kakarote.core.entity.PageEntity; import com.kakarote.core.exception.CrmException; import com.kakarote.core.redis.Redis; import com.kakarote.core.servlet.BaseServiceImpl; import com.kakarote.core.utils.BaseUtil; import com.kakarote.core.utils.TransferUtil; import com.kakarote.hrm.common.HrmCodeEnum; import com.kakarote.hrm.common.LanguageFieldUtil; import com.kakarote.hrm.constant.IsEnum; import com.kakarote.hrm.entity.BO.AddInsuranceSchemeBO; import com.kakarote.hrm.entity.BO.QueryInsuranceScaleBO; import com.kakarote.hrm.entity.BO.QueryInsuranceTypeBO; import com.kakarote.hrm.entity.PO.HrmEmployeeSocialSecurityInfo; import com.kakarote.hrm.entity.PO.HrmInsuranceMonthEmpRecord; import com.kakarote.hrm.entity.PO.HrmInsuranceProject; import com.kakarote.hrm.entity.PO.HrmInsuranceScheme; import com.kakarote.hrm.entity.VO.InsuranceSchemeListVO; import com.kakarote.hrm.entity.VO.InsuranceSchemeVO; import com.kakarote.hrm.mapper.HrmInsuranceSchemeMapper; import com.kakarote.hrm.service.IHrmEmployeeSocialSecurityService; import com.kakarote.hrm.service.IHrmInsuranceMonthEmpRecordService; import com.kakarote.hrm.service.IHrmInsuranceProjectService; import com.kakarote.hrm.service.IHrmInsuranceSchemeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
19,606
package com.kakarote.hrm.service.impl; /** * <p> * 社保方案表 服务实现类 * </p> * * @author huangmingbo * @since 2020-05-12 */ @Service public class HrmInsuranceSchemeServiceImpl extends BaseServiceImpl<HrmInsuranceSchemeMapper, HrmInsuranceScheme> implements IHrmInsuranceSchemeService { @Autowired private IHrmInsuranceProjectService insuranceProjectService; @Autowired private IHrmEmployeeSocialSecurityService employeeSocialSecurityService; @Autowired private HrmInsuranceSchemeMapper insuranceSchemeMapper; @Autowired private IHrmInsuranceMonthEmpRecordService insuranceMonthEmpRecordService; @Autowired private Redis redis; @Override public OperationLog setInsuranceScheme(AddInsuranceSchemeBO addInsuranceSchemeBO) { HrmInsuranceScheme insuranceScheme = BeanUtil.copyProperties(addInsuranceSchemeBO, HrmInsuranceScheme.class); OperationLog operationLog = new OperationLog(); if (insuranceScheme.getSchemeId() != null) { Long schemeId = insuranceScheme.getSchemeId(); lambdaUpdate().set(HrmInsuranceScheme::getIsDel, IsEnum.YES.getValue()).eq(HrmInsuranceScheme::getSchemeId, schemeId).update(); insuranceProjectService.lambdaUpdate().set(HrmInsuranceProject::getIsDel, IsEnum.YES.getValue()).eq(HrmInsuranceProject::getSchemeId, schemeId).update(); insuranceScheme.setSchemeId(null); save(insuranceScheme); //把使用该社保方案的员工更新新的社保方案 employeeSocialSecurityService.lambdaUpdate().set(HrmEmployeeSocialSecurityInfo::getSchemeId, insuranceScheme.getSchemeId()).eq(HrmEmployeeSocialSecurityInfo::getSchemeId, schemeId).update();
package com.kakarote.hrm.service.impl; /** * <p> * 社保方案表 服务实现类 * </p> * * @author huangmingbo * @since 2020-05-12 */ @Service public class HrmInsuranceSchemeServiceImpl extends BaseServiceImpl<HrmInsuranceSchemeMapper, HrmInsuranceScheme> implements IHrmInsuranceSchemeService { @Autowired private IHrmInsuranceProjectService insuranceProjectService; @Autowired private IHrmEmployeeSocialSecurityService employeeSocialSecurityService; @Autowired private HrmInsuranceSchemeMapper insuranceSchemeMapper; @Autowired private IHrmInsuranceMonthEmpRecordService insuranceMonthEmpRecordService; @Autowired private Redis redis; @Override public OperationLog setInsuranceScheme(AddInsuranceSchemeBO addInsuranceSchemeBO) { HrmInsuranceScheme insuranceScheme = BeanUtil.copyProperties(addInsuranceSchemeBO, HrmInsuranceScheme.class); OperationLog operationLog = new OperationLog(); if (insuranceScheme.getSchemeId() != null) { Long schemeId = insuranceScheme.getSchemeId(); lambdaUpdate().set(HrmInsuranceScheme::getIsDel, IsEnum.YES.getValue()).eq(HrmInsuranceScheme::getSchemeId, schemeId).update(); insuranceProjectService.lambdaUpdate().set(HrmInsuranceProject::getIsDel, IsEnum.YES.getValue()).eq(HrmInsuranceProject::getSchemeId, schemeId).update(); insuranceScheme.setSchemeId(null); save(insuranceScheme); //把使用该社保方案的员工更新新的社保方案 employeeSocialSecurityService.lambdaUpdate().set(HrmEmployeeSocialSecurityInfo::getSchemeId, insuranceScheme.getSchemeId()).eq(HrmEmployeeSocialSecurityInfo::getSchemeId, schemeId).update();
insuranceMonthEmpRecordService.lambdaUpdate().set(HrmInsuranceMonthEmpRecord::getSchemeId, insuranceScheme.getSchemeId()).eq(HrmInsuranceMonthEmpRecord::getSchemeId, schemeId).update();
17
2023-10-17 05:49:52+00:00
24k
ballerina-platform/module-ballerinax-copybook
commons/src/main/java/io/ballerina/lib/copybook/commons/schema/SchemaBuilder.java
[ { "identifier": "CopybookVisitor", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/generated/CopybookVisitor.java", "snippet": "public interface CopybookVisitor<T> extends ParseTreeVisitor<T> {\n\t/**\n\t * Visit a parse tree produced by {@link CopybookParser#startRule}.\n\t * @param ct...
import io.ballerina.lib.copybook.commons.generated.CopybookVisitor; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.RuleNode; import org.antlr.v4.runtime.tree.TerminalNode; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.BooleanLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CicsDfhRespLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CicsDfhValueLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CobolWordContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.ConditionNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataBlankWhenZeroClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryClausesContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat1Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat2Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat3Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataExternalClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataGlobalClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataJustifiedClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursSortContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursToContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataPictureClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataRedefinesClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataRenamesClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataSignClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataSynchronizedClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataUsageClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalFromContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalToContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.FigurativeConstantContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IdentifierContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IndexNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IntegerLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.LiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.NumericLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureCardinalityContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureCharsContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureStringContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.QualifiedDataNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.StartRuleContext;
20,376
} return parent; } @Override public CopybookNode visitDataDescriptionEntryFormat2(DataDescriptionEntryFormat2Context ctx) { return null; } @Override public CopybookNode visitDataDescriptionEntryFormat3(DataDescriptionEntryFormat3Context ctx) { return null; } @Override public CopybookNode visitDataBlankWhenZeroClause(DataBlankWhenZeroClauseContext ctx) { return null; } @Override public CopybookNode visitDataExternalClause(DataExternalClauseContext ctx) { return null; } @Override public CopybookNode visitDataGlobalClause(DataGlobalClauseContext ctx) { return null; } @Override public CopybookNode visitDataJustifiedClause(DataJustifiedClauseContext ctx) { return null; } @Override public CopybookNode visitDataOccursClause(DataOccursClauseContext ctx) { return null; } @Override public CopybookNode visitDataOccursTo(DataOccursToContext ctx) { return null; } @Override public CopybookNode visitDataOccursSort(DataOccursSortContext ctx) { return null; } @Override public CopybookNode visitDataPictureClause(DataPictureClauseContext ctx) { return null; } @Override public CopybookNode visitPictureString(PictureStringContext ctx) { return null; } @Override public CopybookNode visitPictureChars(PictureCharsContext ctx) { return null; } @Override public CopybookNode visitPictureCardinality(PictureCardinalityContext ctx) { return null; } @Override public CopybookNode visitDataRedefinesClause(DataRedefinesClauseContext ctx) { return null; } @Override public CopybookNode visitDataRenamesClause(DataRenamesClauseContext ctx) { return null; } @Override public CopybookNode visitDataSignClause(DataSignClauseContext ctx) { return null; } @Override public CopybookNode visitDataSynchronizedClause(DataSynchronizedClauseContext ctx) { return null; } @Override public CopybookNode visitDataUsageClause(DataUsageClauseContext ctx) { return null; } @Override public CopybookNode visitDataValueClause(DataValueClauseContext ctx) { return null; } @Override public CopybookNode visitDataValueInterval(DataValueIntervalContext ctx) { return null; } @Override public CopybookNode visitDataValueIntervalFrom(DataValueIntervalFromContext ctx) { return null; } @Override public CopybookNode visitDataValueIntervalTo(DataValueIntervalToContext ctx) { return null; } @Override public CopybookNode visitIdentifier(IdentifierContext ctx) { return null; } @Override
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.copybook.commons.schema; class SchemaBuilder implements CopybookVisitor<CopybookNode> { private final Schema schema = new Schema(); private GroupItem possibleParent; private final Set<String> redefinedItemNames = new HashSet<>(); private final List<String> errors = new ArrayList<>(); Schema getSchema() { return this.schema; } @Override public CopybookNode visitStartRule(StartRuleContext ctx) { this.possibleParent = null; visitDataDescription(ctx.dataDescription()); for (CopybookNode typedef : this.schema.getTypeDefinitions()) { addRedefinedItems(typedef); } this.schema.addErrors(this.errors); return null; } private void addRedefinedItems(CopybookNode item) { if (this.redefinedItemNames.contains(item.getName())) { this.schema.addRedefinedItem(item); return; } if (item instanceof GroupItem groupItem) { groupItem.getChildren().forEach(this::addRedefinedItems); } } @Override public CopybookNode visitDataDescription(DataDescriptionContext ctx) { for (int i = 0; i < ctx.getChildCount(); i++) { CopybookNode copybookNode = visitDataDescriptionEntry(ctx.dataDescriptionEntry(i)); if (copybookNode instanceof GroupItem groupItem) { this.possibleParent = groupItem; } if (isRootLevelNode(copybookNode)) { this.schema.addTypeDefinition(copybookNode); } } return null; } private boolean isRootLevelNode(CopybookNode copybookNode) { return copybookNode != null && copybookNode.getLevel() == 1; } @Override public CopybookNode visitDataDescriptionEntry(DataDescriptionEntryContext ctx) { if (ctx.dataDescriptionEntryFormat1() != null) { return visitDataDescriptionEntryFormat1(ctx.dataDescriptionEntryFormat1()); } // skipping level 66 and 88 return null; } @Override public CopybookNode visitDataDescriptionEntryFormat1(DataDescriptionEntryFormat1Context ctx) { if (ctx.LEVEL_NUMBER_77() != null) { // skipping level 77 return null; } boolean redefines = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0) != null; String redefinedItemName = null; if (redefines) { redefinedItemName = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0).dataName().getText(); this.redefinedItemNames.add(redefinedItemName); } int level = Integer.parseInt(ctx.INTEGERLITERAL().getText()); String name = ctx.dataName() != null ? ctx.dataName().getText() : ctx.FILLER().getText(); DataPictureClauseContext pictureClause = ctx.dataDescriptionEntryClauses().dataPictureClause(0); DataOccursClauseContext occursClause = ctx.dataDescriptionEntryClauses().dataOccursClause(0); int occurs = Utils.getOccurringCount(occursClause); if (pictureClause == null || pictureClause.pictureString() == null) { return new GroupItem(level, name, occurs, redefinedItemName, getParent(level)); } PictureStringContext pictureType = pictureClause.pictureString(); validatePicture(pictureType); return new DataItem(level, name, Utils.getPictureString(pictureType), Utils.isNumeric(pictureType), Utils.getReadLength(pictureType), occurs, Utils.getFloatingPointLength(pictureType), redefinedItemName, getParent(level)); } private void validatePicture(PictureStringContext pictureType) { String pictureString = Utils.getPictureString(pictureType); if (PictureStringValidator.isSupportedPictureString(pictureString)) { return; } String errorMsg = "Unsupported picture string '" + pictureString + "' found in copybook schema"; this.addError(pictureType.start.getLine(), pictureType.start.getCharPositionInLine(), errorMsg); } private void addError(int line, int charPositionInLine, String msg) { this.errors.add("Error at line " + line + ", column " + charPositionInLine + ": " + msg); } @Override public CopybookNode visitDataDescriptionEntryClauses(DataDescriptionEntryClausesContext ctx) { return null; } private GroupItem getParent(int currentLevel) { GroupItem parent = this.possibleParent; while (parent != null && parent.getLevel() >= currentLevel) { parent = parent.getParent(); } return parent; } @Override public CopybookNode visitDataDescriptionEntryFormat2(DataDescriptionEntryFormat2Context ctx) { return null; } @Override public CopybookNode visitDataDescriptionEntryFormat3(DataDescriptionEntryFormat3Context ctx) { return null; } @Override public CopybookNode visitDataBlankWhenZeroClause(DataBlankWhenZeroClauseContext ctx) { return null; } @Override public CopybookNode visitDataExternalClause(DataExternalClauseContext ctx) { return null; } @Override public CopybookNode visitDataGlobalClause(DataGlobalClauseContext ctx) { return null; } @Override public CopybookNode visitDataJustifiedClause(DataJustifiedClauseContext ctx) { return null; } @Override public CopybookNode visitDataOccursClause(DataOccursClauseContext ctx) { return null; } @Override public CopybookNode visitDataOccursTo(DataOccursToContext ctx) { return null; } @Override public CopybookNode visitDataOccursSort(DataOccursSortContext ctx) { return null; } @Override public CopybookNode visitDataPictureClause(DataPictureClauseContext ctx) { return null; } @Override public CopybookNode visitPictureString(PictureStringContext ctx) { return null; } @Override public CopybookNode visitPictureChars(PictureCharsContext ctx) { return null; } @Override public CopybookNode visitPictureCardinality(PictureCardinalityContext ctx) { return null; } @Override public CopybookNode visitDataRedefinesClause(DataRedefinesClauseContext ctx) { return null; } @Override public CopybookNode visitDataRenamesClause(DataRenamesClauseContext ctx) { return null; } @Override public CopybookNode visitDataSignClause(DataSignClauseContext ctx) { return null; } @Override public CopybookNode visitDataSynchronizedClause(DataSynchronizedClauseContext ctx) { return null; } @Override public CopybookNode visitDataUsageClause(DataUsageClauseContext ctx) { return null; } @Override public CopybookNode visitDataValueClause(DataValueClauseContext ctx) { return null; } @Override public CopybookNode visitDataValueInterval(DataValueIntervalContext ctx) { return null; } @Override public CopybookNode visitDataValueIntervalFrom(DataValueIntervalFromContext ctx) { return null; } @Override public CopybookNode visitDataValueIntervalTo(DataValueIntervalToContext ctx) { return null; } @Override public CopybookNode visitIdentifier(IdentifierContext ctx) { return null; } @Override
public CopybookNode visitQualifiedDataName(QualifiedDataNameContext ctx) {
39
2023-10-24 04:51:53+00:00
24k
zhaoeryu/eu-backend
eu-admin/src/main/java/cn/eu/security/controller/AuthController.java
[ { "identifier": "Constants", "path": "eu-common-core/src/main/java/cn/eu/common/constants/Constants.java", "snippet": "public class Constants {\n\n /** 当前登录账号是否管理的字段KEY */\n public static final String IS_ADMIN_KEY = \"isAdmin\";\n /** 当前登录账号信息的字段KEY */\n public static final String USER_KEY =...
import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.annotation.SaIgnore; import cn.dev33.satoken.session.SaSession; import cn.dev33.satoken.session.TokenSign; import cn.dev33.satoken.stp.StpUtil; import cn.eu.common.annotation.Log; import cn.eu.common.constants.Constants; import cn.eu.common.enums.BusinessType; import cn.eu.common.model.PageResult; import cn.eu.common.model.ResultBody; import cn.eu.common.utils.RedisUtil; import cn.eu.security.SecurityUtil; import cn.eu.security.model.AuthUser; import cn.eu.security.model.LoginBody; import cn.eu.security.model.OnlineUserVo; import cn.eu.security.service.LoginService; import cn.eu.system.domain.SysUser; import cn.eu.system.service.ISysUserService; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.PageUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.wf.captcha.ArithmeticCaptcha; 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.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
17,888
package cn.eu.security.controller; /** * @author zhaoeryu * @since 2023/6/3 */ @Slf4j @RequestMapping("/auth") @RestController public class AuthController { @Autowired LoginService loginService; @Autowired ISysUserService sysUserService; @Autowired RedisUtil redisUtil; @Log(title = "登录", businessType = BusinessType.LOGIN, isSaveResponseData = false, excludeParamNames = { "password" }) @SaIgnore @PostMapping("/login") public ResultBody login(@Validated @RequestBody LoginBody loginBody) { String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getUuid(), loginBody.getVerifyCode()); return ResultBody.ok().data(token); } @GetMapping("/info") public ResultBody info() { AuthUser user = SecurityUtil.getLoginUser(); List<String> permissions = StpUtil.getPermissionList(); List<String> roles = StpUtil.getRoleList(); Map<String, Object> respMap = new HashMap<>(); respMap.put("user", user); respMap.put("permissions", permissions); respMap.put("roles", roles); // 更新用户活跃时间 LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<SysUser>() .eq(SysUser::getId, StpUtil.getLoginIdAsString()) .set(SysUser::getLastActiveTime, LocalDateTime.now()); sysUserService.update(updateWrapper); return ResultBody.ok().data(respMap); } @Log(title = "登出", businessType = BusinessType.LOGOUT) @SaIgnore @PostMapping("/logout") public ResultBody logout() { StpUtil.logout(); return ResultBody.ok(); } @SaIgnore @GetMapping("/captcha") public ResultBody captcha() { String uuid = IdUtil.fastSimpleUUID(); // 算术类型 ArithmeticCaptcha captcha = new ArithmeticCaptcha(150, 38); // 几位数运算,默认是两位 captcha.setLen(2); // 获取运算的公式:3+2=? captcha.getArithmeticString(); // 获取运算的结果:5 captcha.text(); // 保存验证码到redis redisUtil.setEx(Constants.CAPTCHA_REDIS_KEY + uuid, captcha.text(), Constants.CAPTCHA_EXPIRATION, TimeUnit.SECONDS); log.info("uuid: {}, captcha: {}", uuid, captcha.text()); return ResultBody.ok() .putValue("uuid", uuid) .putValue("img", captcha.toBase64()); } /** * 在线用户列表 */ @Log(title = "查看在线用户列表", businessType = BusinessType.QUERY, isSaveResponseData = false) @SaCheckPermission("monitor:online:list") @GetMapping("/online") public ResultBody online(@RequestParam(required = false, value = "nickname") String nickname, @PageableDefault(page = 1) Pageable pageable) { // 获取所有已登录的会话id(如果系统使用的用户比较多,此处会有内存压力,这些限制最多99条数据) List<String> sessionIdList = StpUtil.searchSessionId("", 0, 99, true); List<OnlineUserVo> list = new ArrayList<>(); for (String sessionId : sessionIdList) { // 根据会话id,查询对应的 SaSession 对象,此处一个 SaSession 对象即代表一个登录的账号 SaSession session = StpUtil.getSessionBySessionId(sessionId); AuthUser authUser = SecurityUtil.getLoginUserBySaSession(session); OnlineUserVo onlineUserVo = new OnlineUserVo(); onlineUserVo.setId(authUser.getUserId()); onlineUserVo.setUsername(authUser.getUsername()); onlineUserVo.setNickname(authUser.getNickname()); onlineUserVo.setDeptName(authUser.getDeptName()); onlineUserVo.setLoginIp(authUser.getLoginIp()); onlineUserVo.setLoginRegion(authUser.getLoginRegion()); onlineUserVo.setLoginTime(authUser.getLoginTime()); onlineUserVo.setBrowser(authUser.getBrowser()); onlineUserVo.setOs(authUser.getOs()); list.add(onlineUserVo); } // 筛选数据 if (StrUtil.isNotBlank(nickname)) { list = list.stream().filter(user -> user.getNickname().contains(nickname)).collect(Collectors.toList()); } // 分页处理 long total = list.size(); int fromIndex = (pageable.getPageNumber() - 1) * pageable.getPageSize(); int toIndex = (pageable.getPageNumber() - 1) * pageable.getPageSize() + pageable.getPageSize(); if (fromIndex > total) { list = new ArrayList<>(); } else if (toIndex >= total) { list = list.subList(fromIndex, (int)total); } else { list = list.subList(fromIndex, toIndex); }
package cn.eu.security.controller; /** * @author zhaoeryu * @since 2023/6/3 */ @Slf4j @RequestMapping("/auth") @RestController public class AuthController { @Autowired LoginService loginService; @Autowired ISysUserService sysUserService; @Autowired RedisUtil redisUtil; @Log(title = "登录", businessType = BusinessType.LOGIN, isSaveResponseData = false, excludeParamNames = { "password" }) @SaIgnore @PostMapping("/login") public ResultBody login(@Validated @RequestBody LoginBody loginBody) { String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getUuid(), loginBody.getVerifyCode()); return ResultBody.ok().data(token); } @GetMapping("/info") public ResultBody info() { AuthUser user = SecurityUtil.getLoginUser(); List<String> permissions = StpUtil.getPermissionList(); List<String> roles = StpUtil.getRoleList(); Map<String, Object> respMap = new HashMap<>(); respMap.put("user", user); respMap.put("permissions", permissions); respMap.put("roles", roles); // 更新用户活跃时间 LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<SysUser>() .eq(SysUser::getId, StpUtil.getLoginIdAsString()) .set(SysUser::getLastActiveTime, LocalDateTime.now()); sysUserService.update(updateWrapper); return ResultBody.ok().data(respMap); } @Log(title = "登出", businessType = BusinessType.LOGOUT) @SaIgnore @PostMapping("/logout") public ResultBody logout() { StpUtil.logout(); return ResultBody.ok(); } @SaIgnore @GetMapping("/captcha") public ResultBody captcha() { String uuid = IdUtil.fastSimpleUUID(); // 算术类型 ArithmeticCaptcha captcha = new ArithmeticCaptcha(150, 38); // 几位数运算,默认是两位 captcha.setLen(2); // 获取运算的公式:3+2=? captcha.getArithmeticString(); // 获取运算的结果:5 captcha.text(); // 保存验证码到redis redisUtil.setEx(Constants.CAPTCHA_REDIS_KEY + uuid, captcha.text(), Constants.CAPTCHA_EXPIRATION, TimeUnit.SECONDS); log.info("uuid: {}, captcha: {}", uuid, captcha.text()); return ResultBody.ok() .putValue("uuid", uuid) .putValue("img", captcha.toBase64()); } /** * 在线用户列表 */ @Log(title = "查看在线用户列表", businessType = BusinessType.QUERY, isSaveResponseData = false) @SaCheckPermission("monitor:online:list") @GetMapping("/online") public ResultBody online(@RequestParam(required = false, value = "nickname") String nickname, @PageableDefault(page = 1) Pageable pageable) { // 获取所有已登录的会话id(如果系统使用的用户比较多,此处会有内存压力,这些限制最多99条数据) List<String> sessionIdList = StpUtil.searchSessionId("", 0, 99, true); List<OnlineUserVo> list = new ArrayList<>(); for (String sessionId : sessionIdList) { // 根据会话id,查询对应的 SaSession 对象,此处一个 SaSession 对象即代表一个登录的账号 SaSession session = StpUtil.getSessionBySessionId(sessionId); AuthUser authUser = SecurityUtil.getLoginUserBySaSession(session); OnlineUserVo onlineUserVo = new OnlineUserVo(); onlineUserVo.setId(authUser.getUserId()); onlineUserVo.setUsername(authUser.getUsername()); onlineUserVo.setNickname(authUser.getNickname()); onlineUserVo.setDeptName(authUser.getDeptName()); onlineUserVo.setLoginIp(authUser.getLoginIp()); onlineUserVo.setLoginRegion(authUser.getLoginRegion()); onlineUserVo.setLoginTime(authUser.getLoginTime()); onlineUserVo.setBrowser(authUser.getBrowser()); onlineUserVo.setOs(authUser.getOs()); list.add(onlineUserVo); } // 筛选数据 if (StrUtil.isNotBlank(nickname)) { list = list.stream().filter(user -> user.getNickname().contains(nickname)).collect(Collectors.toList()); } // 分页处理 long total = list.size(); int fromIndex = (pageable.getPageNumber() - 1) * pageable.getPageSize(); int toIndex = (pageable.getPageNumber() - 1) * pageable.getPageSize() + pageable.getPageSize(); if (fromIndex > total) { list = new ArrayList<>(); } else if (toIndex >= total) { list = list.subList(fromIndex, (int)total); } else { list = list.subList(fromIndex, toIndex); }
return ResultBody.ok().data(PageResult.of(list, total));
2
2023-10-20 07:08:37+00:00
24k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/recipe/machineRecipe/StellarForgeRecipePool.java
[ { "identifier": "copyAmount", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/Utils.java", "snippet": "public static ItemStack copyAmount(int aAmount, ItemStack aStack) {\n ItemStack rStack = aStack.copy();\n if (isStackInvalid(rStack)) return null;\n // if (aAmount > 64) aAmount = 64...
import static com.Nxer.TwistSpaceTechnology.util.Utils.copyAmount; import static com.Nxer.TwistSpaceTechnology.util.Utils.fluidStackEqualFuzzy; import static com.Nxer.TwistSpaceTechnology.util.Utils.itemStackArrayEqualFuzzy; import static com.Nxer.TwistSpaceTechnology.util.Utils.metaItemEqual; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import com.Nxer.TwistSpaceTechnology.common.recipeMap.GTCMRecipe; import com.Nxer.TwistSpaceTechnology.config.Config; import com.Nxer.TwistSpaceTechnology.recipe.IRecipePool; import com.Nxer.TwistSpaceTechnology.util.rewrites.TST_ItemID; import com.github.bartimaeusnek.bartworks.system.material.WerkstoffLoader; import com.google.common.collect.Sets; import gregtech.api.enums.GT_Values; import gregtech.api.enums.Materials; import gregtech.api.enums.OrePrefixes; import gregtech.api.recipe.RecipeMaps; import gregtech.api.util.GT_Recipe; import gregtech.api.util.GT_RecipeBuilder; import gregtech.api.util.GT_Utility;
18,824
package com.Nxer.TwistSpaceTechnology.recipe.machineRecipe; public class StellarForgeRecipePool implements IRecipePool { public static final boolean OutputMoltenFluidInsteadIngotInStellarForgeRecipe = Config.OutputMoltenFluidInsteadIngotInStellarForgeRecipe; public static final HashSet<String> IngotHotOreDictNames = new HashSet<>(); public static final HashSet<String> IngotOreDictNames = new HashSet<>(); public static final HashSet<TST_ItemID> IngotHots = new HashSet<>(); public static final HashSet<TST_ItemID> Ingots = new HashSet<>(); public static final HashMap<TST_ItemID, ItemStack> IngotHotToIngot = new HashMap<>(); public static final HashSet<TST_ItemID> SpecialRecipeOutputs = new HashSet<>(); public void initData() { // for (String name : OreDictionary.getOreNames()) { if (name.startsWith("ingotHot")) { IngotHotOreDictNames.add(name); for (ItemStack items : OreDictionary.getOres(name)) { IngotHots.add(TST_ItemID.createNoNBT(items)); } } else if (name.startsWith("ingot")) { IngotOreDictNames.add(name); for (ItemStack items : OreDictionary.getOres(name)) { Ingots.add(TST_ItemID.createNoNBT(items)); } } } // iterate Vacuum Freezer recipes for (GT_Recipe recipeFreezer : RecipeMaps.vacuumFreezerRecipes.getAllRecipes()) { if (recipeFreezer.mInputs == null || recipeFreezer.mInputs.length < 1 || recipeFreezer.mOutputs == null || recipeFreezer.mOutputs.length < 1) continue; ItemStack input = recipeFreezer.mInputs[0].copy(); // check input is ingotHot // if (!IngotHots.contains(copyAmount(1, input))) continue; ItemStack outputIngot = recipeFreezer.mOutputs[0].copy(); // add ingotHot - ingot to map IngotHotToIngot.put(TST_ItemID.createNoNBT(input), outputIngot); } // add SpecialRecipeOutputs SpecialRecipeOutputs.add(TST_ItemID.create(WerkstoffLoader.CubicZirconia.get(OrePrefixes.gemFlawed, 1))); } public void prepareEBFRecipes() { Set<Fluid> protectionGas = Sets.newHashSet( Materials.Hydrogen.mGas, Materials.Oxygen.mGas, Materials.Nitrogen.mGas, WerkstoffLoader.Xenon.getFluidOrGas(1) .getFluid(), WerkstoffLoader.Oganesson.getFluidOrGas(1) .getFluid(), WerkstoffLoader.Krypton.getFluidOrGas(1) .getFluid(), WerkstoffLoader.Neon.getFluidOrGas(1) .getFluid(), Materials.Radon.mGas, Materials.Argon.mGas, Materials.Helium.mGas); for (GT_Recipe recipe : RecipeMaps.blastFurnaceRecipes.getAllRecipes()) { if (recipe.mOutputs.length == 1 && SpecialRecipeOutputs.contains(TST_ItemID.create(recipe.mOutputs[0]))) continue; Set<ItemStack> inputItems = new HashSet<>(); Set<FluidStack> inputFluids = new HashSet<>(); Set<ItemStack> outputItems = new HashSet<>(); Set<FluidStack> outputFluids = new HashSet<>(); // process Item input byte integrateNum = 0; for (ItemStack inputs : recipe.mInputs) { if (metaItemEqual(inputs, GT_Utility.getIntegratedCircuit(1))) { integrateNum = 1; continue; } if (metaItemEqual(inputs, GT_Utility.getIntegratedCircuit(11))) { integrateNum = 11; continue; } inputItems.add(inputs.copy()); } // process Item output for (ItemStack outputs : recipe.mOutputs) { TST_ItemID outputItemID = TST_ItemID.createNoNBT(outputs); if (IngotHots.contains(outputItemID)) { // if this output item is Hot Ingot ItemStack normalIngot = IngotHotToIngot.get(outputItemID); if (OutputMoltenFluidInsteadIngotInStellarForgeRecipe) { FluidStack fluidStack = getMoltenFluids(normalIngot, outputs.stackSize); if (fluidStack != null) { outputFluids.add(fluidStack); } } else { ItemStack out = normalIngot.copy(); out.stackSize = outputs.stackSize; outputItems.add(out); } } else if (Ingots.contains(outputItemID)) { // if this output item is normal Ingot if (OutputMoltenFluidInsteadIngotInStellarForgeRecipe) {
package com.Nxer.TwistSpaceTechnology.recipe.machineRecipe; public class StellarForgeRecipePool implements IRecipePool { public static final boolean OutputMoltenFluidInsteadIngotInStellarForgeRecipe = Config.OutputMoltenFluidInsteadIngotInStellarForgeRecipe; public static final HashSet<String> IngotHotOreDictNames = new HashSet<>(); public static final HashSet<String> IngotOreDictNames = new HashSet<>(); public static final HashSet<TST_ItemID> IngotHots = new HashSet<>(); public static final HashSet<TST_ItemID> Ingots = new HashSet<>(); public static final HashMap<TST_ItemID, ItemStack> IngotHotToIngot = new HashMap<>(); public static final HashSet<TST_ItemID> SpecialRecipeOutputs = new HashSet<>(); public void initData() { // for (String name : OreDictionary.getOreNames()) { if (name.startsWith("ingotHot")) { IngotHotOreDictNames.add(name); for (ItemStack items : OreDictionary.getOres(name)) { IngotHots.add(TST_ItemID.createNoNBT(items)); } } else if (name.startsWith("ingot")) { IngotOreDictNames.add(name); for (ItemStack items : OreDictionary.getOres(name)) { Ingots.add(TST_ItemID.createNoNBT(items)); } } } // iterate Vacuum Freezer recipes for (GT_Recipe recipeFreezer : RecipeMaps.vacuumFreezerRecipes.getAllRecipes()) { if (recipeFreezer.mInputs == null || recipeFreezer.mInputs.length < 1 || recipeFreezer.mOutputs == null || recipeFreezer.mOutputs.length < 1) continue; ItemStack input = recipeFreezer.mInputs[0].copy(); // check input is ingotHot // if (!IngotHots.contains(copyAmount(1, input))) continue; ItemStack outputIngot = recipeFreezer.mOutputs[0].copy(); // add ingotHot - ingot to map IngotHotToIngot.put(TST_ItemID.createNoNBT(input), outputIngot); } // add SpecialRecipeOutputs SpecialRecipeOutputs.add(TST_ItemID.create(WerkstoffLoader.CubicZirconia.get(OrePrefixes.gemFlawed, 1))); } public void prepareEBFRecipes() { Set<Fluid> protectionGas = Sets.newHashSet( Materials.Hydrogen.mGas, Materials.Oxygen.mGas, Materials.Nitrogen.mGas, WerkstoffLoader.Xenon.getFluidOrGas(1) .getFluid(), WerkstoffLoader.Oganesson.getFluidOrGas(1) .getFluid(), WerkstoffLoader.Krypton.getFluidOrGas(1) .getFluid(), WerkstoffLoader.Neon.getFluidOrGas(1) .getFluid(), Materials.Radon.mGas, Materials.Argon.mGas, Materials.Helium.mGas); for (GT_Recipe recipe : RecipeMaps.blastFurnaceRecipes.getAllRecipes()) { if (recipe.mOutputs.length == 1 && SpecialRecipeOutputs.contains(TST_ItemID.create(recipe.mOutputs[0]))) continue; Set<ItemStack> inputItems = new HashSet<>(); Set<FluidStack> inputFluids = new HashSet<>(); Set<ItemStack> outputItems = new HashSet<>(); Set<FluidStack> outputFluids = new HashSet<>(); // process Item input byte integrateNum = 0; for (ItemStack inputs : recipe.mInputs) { if (metaItemEqual(inputs, GT_Utility.getIntegratedCircuit(1))) { integrateNum = 1; continue; } if (metaItemEqual(inputs, GT_Utility.getIntegratedCircuit(11))) { integrateNum = 11; continue; } inputItems.add(inputs.copy()); } // process Item output for (ItemStack outputs : recipe.mOutputs) { TST_ItemID outputItemID = TST_ItemID.createNoNBT(outputs); if (IngotHots.contains(outputItemID)) { // if this output item is Hot Ingot ItemStack normalIngot = IngotHotToIngot.get(outputItemID); if (OutputMoltenFluidInsteadIngotInStellarForgeRecipe) { FluidStack fluidStack = getMoltenFluids(normalIngot, outputs.stackSize); if (fluidStack != null) { outputFluids.add(fluidStack); } } else { ItemStack out = normalIngot.copy(); out.stackSize = outputs.stackSize; outputItems.add(out); } } else if (Ingots.contains(outputItemID)) { // if this output item is normal Ingot if (OutputMoltenFluidInsteadIngotInStellarForgeRecipe) {
FluidStack fluidStack = getMoltenFluids(copyAmount(1, outputs), outputs.stackSize);
0
2023-10-16 09:57:15+00:00
24k
wyjsonGo/GoRouter
GoRouter-Api/src/main/java/com/wyjson/router/GoRouter.java
[ { "identifier": "GoCallback", "path": "GoRouter-Api/src/main/java/com/wyjson/router/callback/GoCallback.java", "snippet": "public interface GoCallback {\n\n /**\n * 当找到目的地的回调\n *\n * @param card\n */\n void onFound(Card card);\n\n /**\n * 迷路后的回调。\n *\n * @param card\...
import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityOptionsCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Observer; import com.wyjson.router.callback.GoCallback; import com.wyjson.router.callback.InterceptorCallback; import com.wyjson.router.core.ApplicationModuleCenter; import com.wyjson.router.core.EventCenter; import com.wyjson.router.core.InterceptorCenter; import com.wyjson.router.core.InterceptorServiceImpl; import com.wyjson.router.core.RouteCenter; import com.wyjson.router.core.RouteModuleCenter; import com.wyjson.router.core.ServiceCenter; import com.wyjson.router.core.interfaces.IInterceptorService; import com.wyjson.router.exception.NoFoundRouteException; import com.wyjson.router.exception.ParamException; import com.wyjson.router.exception.RouterException; import com.wyjson.router.interfaces.IApplicationModule; import com.wyjson.router.interfaces.IDegradeService; import com.wyjson.router.interfaces.IInterceptor; import com.wyjson.router.interfaces.IPretreatmentService; import com.wyjson.router.interfaces.IService; import com.wyjson.router.logger.DefaultLogger; import com.wyjson.router.logger.ILogger; import com.wyjson.router.model.Card; import com.wyjson.router.module.interfaces.IRouteModuleGroup; import com.wyjson.router.thread.DefaultPoolExecutor; import com.wyjson.router.utils.TextUtils; import java.util.concurrent.ThreadPoolExecutor;
14,761
package com.wyjson.router; public final class GoRouter { private final Handler mHandler = new Handler(Looper.getMainLooper()); private volatile static ThreadPoolExecutor executor = DefaultPoolExecutor.getInstance(); public static ILogger logger = new DefaultLogger(); private volatile static boolean isDebug = false; private static Application mApplication; private GoRouter() { InterceptorCenter.clearInterceptors();
package com.wyjson.router; public final class GoRouter { private final Handler mHandler = new Handler(Looper.getMainLooper()); private volatile static ThreadPoolExecutor executor = DefaultPoolExecutor.getInstance(); public static ILogger logger = new DefaultLogger(); private volatile static boolean isDebug = false; private static Application mApplication; private GoRouter() { InterceptorCenter.clearInterceptors();
ServiceCenter.addService(InterceptorServiceImpl.class);
8
2023-10-18 13:52:07+00:00
24k
trpc-group/trpc-java
trpc-spring-support/trpc-spring-cloud-gateway/src/test/java/com/tencent/trpc/spring/cloud/gateway/filter/test/server/HelloServiceImpl.java
[ { "identifier": "Logger", "path": "trpc-core/src/main/java/com/tencent/trpc/core/logger/Logger.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic interface Logger {\n\n void trace(String msg);\n\n void trace(String format, Object... argArray);\n\n void trace(String msg, Throwable e);\n...
import com.tencent.trpc.core.logger.Logger; import com.tencent.trpc.core.logger.LoggerFactory; import com.tencent.trpc.core.rpc.RpcContext; import com.tencent.trpc.core.rpc.RpcServerContext; import com.tencent.trpc.spring.cloud.gateway.filter.test.server.Hello.HelloReq; import com.tencent.trpc.spring.cloud.gateway.filter.test.server.Hello.HelloRsp; import org.springframework.stereotype.Service;
14,576
/* * 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.spring.cloud.gateway.filter.test.server; @Service public class HelloServiceImpl implements HelloAPI { private static final Logger logger = LoggerFactory.getLogger(HelloServiceImpl.class); @Override
/* * 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.spring.cloud.gateway.filter.test.server; @Service public class HelloServiceImpl implements HelloAPI { private static final Logger logger = LoggerFactory.getLogger(HelloServiceImpl.class); @Override
public HelloRsp sayHello(RpcContext context, HelloReq request) {
4
2023-10-19 10:54:11+00:00
24k
eclipse-jgit/jgit
org.eclipse.jgit/src/org/eclipse/jgit/transport/ProtocolV0Parser.java
[ { "identifier": "OPTION_FILTER", "path": "org.eclipse.jgit/src/org/eclipse/jgit/transport/GitProtocolConstants.java", "snippet": "public static final String OPTION_FILTER = \"filter\"; //$NON-NLS-1$" }, { "identifier": "PACKET_DEEPEN", "path": "org.eclipse.jgit/src/org/eclipse/jgit/transport...
import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_FILTER; import static org.eclipse.jgit.transport.GitProtocolConstants.PACKET_DEEPEN; import static org.eclipse.jgit.transport.GitProtocolConstants.PACKET_DEEPEN_NOT; import static org.eclipse.jgit.transport.GitProtocolConstants.PACKET_DEEPEN_SINCE; import static org.eclipse.jgit.transport.GitProtocolConstants.PACKET_SHALLOW; import static org.eclipse.jgit.transport.GitProtocolConstants.PACKET_WANT; import java.io.EOFException; import java.io.IOException; import java.text.MessageFormat; import org.eclipse.jgit.errors.PackProtocolException; import org.eclipse.jgit.internal.JGitText; import org.eclipse.jgit.internal.transport.parser.FirstWant; import org.eclipse.jgit.lib.ObjectId;
15,346
/* * Copyright (C) 2018, 2022 Google LLC. 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.transport; /** * Parser for git protocol versions 0 and 1. * * It reads the lines coming through the {@link PacketLineIn} and builds a * {@link FetchV0Request} object. * * It requires a transferConfig object to know if the server supports filters. */ final class ProtocolV0Parser { private final TransferConfig transferConfig; ProtocolV0Parser(TransferConfig transferConfig) { this.transferConfig = transferConfig; } /** * Parse an incoming protocol v1 upload request arguments from the wire. * * The incoming PacketLineIn is consumed until an END line, but the caller * is responsible for closing it (if needed). * * @param pckIn * incoming lines. This method will read until an END line. * @return a FetchV0Request with the data received in the wire. * @throws PackProtocolException * if a protocol occurred * @throws IOException * if an IO error occurred */ FetchV0Request recvWants(PacketLineIn pckIn) throws PackProtocolException, IOException { FetchV0Request.Builder reqBuilder = new FetchV0Request.Builder(); boolean isFirst = true; boolean filterReceived = false; for (;;) { String line; try { line = pckIn.readString(); } catch (EOFException eof) { if (isFirst) { break; } throw eof; } if (PacketLineIn.isEnd(line)) { break; } if (line.startsWith(PACKET_DEEPEN)) { int depth = Integer .parseInt(line.substring(PACKET_DEEPEN.length())); if (depth <= 0) { throw new PackProtocolException( MessageFormat.format(JGitText.get().invalidDepth, Integer.valueOf(depth))); } if (reqBuilder.getDeepenSince() != 0) { throw new PackProtocolException( JGitText.get().deepenSinceWithDeepen); } if (reqBuilder.hasDeepenNots()) { throw new PackProtocolException( JGitText.get().deepenNotWithDeepen); } reqBuilder.setDepth(depth); continue; } if (line.startsWith(PACKET_DEEPEN_NOT)) { reqBuilder.addDeepenNot( line.substring(PACKET_DEEPEN_NOT.length())); if (reqBuilder.getDepth() != 0) { throw new PackProtocolException( JGitText.get().deepenNotWithDeepen); } continue; } if (line.startsWith(PACKET_DEEPEN_SINCE)) { // TODO: timestamps should be long int ts = Integer .parseInt(line.substring(PACKET_DEEPEN_SINCE.length())); if (ts <= 0) { throw new PackProtocolException(MessageFormat .format(JGitText.get().invalidTimestamp, line)); } if (reqBuilder.getDepth() != 0) { throw new PackProtocolException( JGitText.get().deepenSinceWithDeepen); } reqBuilder.setDeepenSince(ts); continue; }
/* * Copyright (C) 2018, 2022 Google LLC. 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.transport; /** * Parser for git protocol versions 0 and 1. * * It reads the lines coming through the {@link PacketLineIn} and builds a * {@link FetchV0Request} object. * * It requires a transferConfig object to know if the server supports filters. */ final class ProtocolV0Parser { private final TransferConfig transferConfig; ProtocolV0Parser(TransferConfig transferConfig) { this.transferConfig = transferConfig; } /** * Parse an incoming protocol v1 upload request arguments from the wire. * * The incoming PacketLineIn is consumed until an END line, but the caller * is responsible for closing it (if needed). * * @param pckIn * incoming lines. This method will read until an END line. * @return a FetchV0Request with the data received in the wire. * @throws PackProtocolException * if a protocol occurred * @throws IOException * if an IO error occurred */ FetchV0Request recvWants(PacketLineIn pckIn) throws PackProtocolException, IOException { FetchV0Request.Builder reqBuilder = new FetchV0Request.Builder(); boolean isFirst = true; boolean filterReceived = false; for (;;) { String line; try { line = pckIn.readString(); } catch (EOFException eof) { if (isFirst) { break; } throw eof; } if (PacketLineIn.isEnd(line)) { break; } if (line.startsWith(PACKET_DEEPEN)) { int depth = Integer .parseInt(line.substring(PACKET_DEEPEN.length())); if (depth <= 0) { throw new PackProtocolException( MessageFormat.format(JGitText.get().invalidDepth, Integer.valueOf(depth))); } if (reqBuilder.getDeepenSince() != 0) { throw new PackProtocolException( JGitText.get().deepenSinceWithDeepen); } if (reqBuilder.hasDeepenNots()) { throw new PackProtocolException( JGitText.get().deepenNotWithDeepen); } reqBuilder.setDepth(depth); continue; } if (line.startsWith(PACKET_DEEPEN_NOT)) { reqBuilder.addDeepenNot( line.substring(PACKET_DEEPEN_NOT.length())); if (reqBuilder.getDepth() != 0) { throw new PackProtocolException( JGitText.get().deepenNotWithDeepen); } continue; } if (line.startsWith(PACKET_DEEPEN_SINCE)) { // TODO: timestamps should be long int ts = Integer .parseInt(line.substring(PACKET_DEEPEN_SINCE.length())); if (ts <= 0) { throw new PackProtocolException(MessageFormat .format(JGitText.get().invalidTimestamp, line)); } if (reqBuilder.getDepth() != 0) { throw new PackProtocolException( JGitText.get().deepenSinceWithDeepen); } reqBuilder.setDeepenSince(ts); continue; }
if (line.startsWith(PACKET_SHALLOW)) {
4
2023-10-20 15:09:17+00:00
24k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/ProviderRecyclerListFragment.java
[ { "identifier": "Utils", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/Utils.java", "snippet": "public class Utils {\n private static final String TAG = \"Utils\";\n //\tpublic final static String ACTION_RECEIVER_CHANGED=\"cn.wq.myandroidtoolspro.receiver_changed\";\n//\tprivate final ...
import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.ColorRes; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SwitchCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.Utils; import cn.wq.myandroidtoolspro.model.ComponentEntry; import cn.wq.myandroidtoolspro.model.ComponentModel; import cn.wq.myandroidtoolspro.recyclerview.adapter.AbstractComponentAdapter; import cn.wq.myandroidtoolspro.recyclerview.toolbar.MultiSectionWithToolbarRecyclerFragment; import cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectableViewHolder; import cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectionUtils;
15,704
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ProviderRecyclerListFragment extends MultiSectionWithToolbarRecyclerFragment { private ProviderAdapter mAdapter; private String packageName; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } public static ProviderRecyclerListFragment newInstance(Bundle bundle) { ProviderRecyclerListFragment f = new ProviderRecyclerListFragment(); f.setArguments(bundle); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle data = getArguments(); packageName = data.getString("packageName"); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setToolbarLogo(packageName); } @Override protected AbstractComponentAdapter<ComponentEntry> generateAdapter() { mAdapter = new ProviderAdapter(mContext); return mAdapter; } @Override protected void reloadData(Integer... checkedItemPositions) { mAdapter.setData(loadData()); } @Override protected boolean disableByIfw(Integer... positions) { return false; } @Override protected List<ComponentEntry> loadData() { List<ComponentEntry> result = new ArrayList<>(); PackageManager pm = mContext.getPackageManager(); List<ComponentModel> models=Utils.getComponentModels(mContext,packageName,3); for(ComponentModel model:models){ if(model==null){ continue; } ComponentEntry entry=new ComponentEntry(); entry.packageName=model.packageName; entry.className=model.className; entry.enabled=Utils.isComponentEnabled(model, pm); result.add(entry); } Collections.sort(result, new Comparator<ComponentEntry>() { @Override public int compare(ComponentEntry lhs, ComponentEntry rhs) { String l = lhs.className.substring( lhs.className.lastIndexOf(".") + 1); String r = rhs.className.substring( rhs.className.lastIndexOf(".") + 1); return l.compareTo(r); } }); return result; } private class ProviderAdapter extends AbstractComponentAdapter<ComponentEntry> { ProviderAdapter(Context context) { super(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new BaseComponentViewHolder(LayoutInflater.from(mContext) .inflate(R.layout.item_component_list, parent, false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { BaseComponentViewHolder vHolder= (BaseComponentViewHolder) holder; ComponentEntry entry = getItem(position); if (getIsFullName()) { vHolder.name.setText(entry.className); } else { vHolder.name.setText(entry.className.substring(entry.className .lastIndexOf(".") + 1)); } vHolder.checkBox.setChecked(entry.enabled); vHolder.name.setTextColor(entry.enabled ? primaryTextColor : redTextColor); vHolder.setSelected(getMultiController().isSelectedAtPosition(position)); } } private class BaseComponentViewHolder extends MultiSelectableViewHolder { TextView name; SwitchCompat checkBox; BaseComponentViewHolder(View itemView) { super(itemView); name = (TextView) itemView.findViewById(R.id.name); checkBox=(SwitchCompat)itemView.findViewById(R.id.checkbox); } @Override
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ProviderRecyclerListFragment extends MultiSectionWithToolbarRecyclerFragment { private ProviderAdapter mAdapter; private String packageName; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } public static ProviderRecyclerListFragment newInstance(Bundle bundle) { ProviderRecyclerListFragment f = new ProviderRecyclerListFragment(); f.setArguments(bundle); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle data = getArguments(); packageName = data.getString("packageName"); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setToolbarLogo(packageName); } @Override protected AbstractComponentAdapter<ComponentEntry> generateAdapter() { mAdapter = new ProviderAdapter(mContext); return mAdapter; } @Override protected void reloadData(Integer... checkedItemPositions) { mAdapter.setData(loadData()); } @Override protected boolean disableByIfw(Integer... positions) { return false; } @Override protected List<ComponentEntry> loadData() { List<ComponentEntry> result = new ArrayList<>(); PackageManager pm = mContext.getPackageManager(); List<ComponentModel> models=Utils.getComponentModels(mContext,packageName,3); for(ComponentModel model:models){ if(model==null){ continue; } ComponentEntry entry=new ComponentEntry(); entry.packageName=model.packageName; entry.className=model.className; entry.enabled=Utils.isComponentEnabled(model, pm); result.add(entry); } Collections.sort(result, new Comparator<ComponentEntry>() { @Override public int compare(ComponentEntry lhs, ComponentEntry rhs) { String l = lhs.className.substring( lhs.className.lastIndexOf(".") + 1); String r = rhs.className.substring( rhs.className.lastIndexOf(".") + 1); return l.compareTo(r); } }); return result; } private class ProviderAdapter extends AbstractComponentAdapter<ComponentEntry> { ProviderAdapter(Context context) { super(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new BaseComponentViewHolder(LayoutInflater.from(mContext) .inflate(R.layout.item_component_list, parent, false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { BaseComponentViewHolder vHolder= (BaseComponentViewHolder) holder; ComponentEntry entry = getItem(position); if (getIsFullName()) { vHolder.name.setText(entry.className); } else { vHolder.name.setText(entry.className.substring(entry.className .lastIndexOf(".") + 1)); } vHolder.checkBox.setChecked(entry.enabled); vHolder.name.setTextColor(entry.enabled ? primaryTextColor : redTextColor); vHolder.setSelected(getMultiController().isSelectedAtPosition(position)); } } private class BaseComponentViewHolder extends MultiSelectableViewHolder { TextView name; SwitchCompat checkBox; BaseComponentViewHolder(View itemView) { super(itemView); name = (TextView) itemView.findViewById(R.id.name); checkBox=(SwitchCompat)itemView.findViewById(R.id.checkbox); } @Override
public MultiSelectionUtils.Controller loadMultiController() {
6
2023-10-18 14:32:49+00:00
24k
A1anSong/jd_unidbg
unidbg-api/src/main/java/com/github/unidbg/arm/AbstractARMDebugger.java
[ { "identifier": "AssemblyCodeDumper", "path": "unidbg-api/src/main/java/com/github/unidbg/AssemblyCodeDumper.java", "snippet": "public class AssemblyCodeDumper implements CodeHook, TraceHook {\n\n private final Emulator<?> emulator;\n\n public AssemblyCodeDumper(Emulator<?> emulator, long begin, l...
import capstone.api.Instruction; import capstone.api.RegsAccess; import com.github.unidbg.AssemblyCodeDumper; import com.github.unidbg.Emulator; import com.github.unidbg.Family; import com.github.unidbg.Module; import com.github.unidbg.Symbol; import com.github.unidbg.TraceMemoryHook; import com.github.unidbg.Utils; import com.github.unidbg.arm.backend.Backend; import com.github.unidbg.arm.backend.BlockHook; import com.github.unidbg.arm.backend.ReadHook; import com.github.unidbg.arm.backend.UnHook; import com.github.unidbg.arm.backend.WriteHook; import com.github.unidbg.debugger.BreakPoint; import com.github.unidbg.debugger.BreakPointCallback; import com.github.unidbg.debugger.DebugListener; import com.github.unidbg.debugger.DebugRunnable; import com.github.unidbg.debugger.Debugger; import com.github.unidbg.debugger.FunctionCallListener; import com.github.unidbg.memory.MemRegion; import com.github.unidbg.memory.Memory; import com.github.unidbg.memory.MemoryMap; import com.github.unidbg.pointer.UnidbgPointer; import com.github.unidbg.thread.Task; import com.github.unidbg.unix.struct.StdString; import com.github.unidbg.unwind.Unwinder; import com.github.unidbg.utils.Inspector; import com.github.zhkl0228.demumble.DemanglerFactory; import com.github.zhkl0228.demumble.GccDemangler; import com.sun.jna.Pointer; import keystone.Keystone; import keystone.KeystoneEncoded; import keystone.exceptions.AssembleFailedKeystoneException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import unicorn.Arm64Const; import unicorn.ArmConst; import unicorn.UnicornConst; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern;
17,581
package com.github.unidbg.arm; public abstract class AbstractARMDebugger implements Debugger { private static final Log log = LogFactory.getLog(AbstractARMDebugger.class); private final Map<Long, BreakPoint> breakMap = new LinkedHashMap<>(); protected final Emulator<?> emulator; protected AbstractARMDebugger(Emulator<?> emulator) { this.emulator = emulator; } private final List<UnHook> unHookList = new ArrayList<>(); @Override public void onAttach(UnHook unHook) { unHookList.add(unHook); } @Override public void detach() { for (Iterator<UnHook> iterator = unHookList.iterator(); iterator.hasNext(); ) { iterator.next().unhook(); iterator.remove(); } } @Override public final BreakPoint addBreakPoint(Module module, String symbol) {
package com.github.unidbg.arm; public abstract class AbstractARMDebugger implements Debugger { private static final Log log = LogFactory.getLog(AbstractARMDebugger.class); private final Map<Long, BreakPoint> breakMap = new LinkedHashMap<>(); protected final Emulator<?> emulator; protected AbstractARMDebugger(Emulator<?> emulator) { this.emulator = emulator; } private final List<UnHook> unHookList = new ArrayList<>(); @Override public void onAttach(UnHook unHook) { unHookList.add(unHook); } @Override public void detach() { for (Iterator<UnHook> iterator = unHookList.iterator(); iterator.hasNext(); ) { iterator.next().unhook(); iterator.remove(); } } @Override public final BreakPoint addBreakPoint(Module module, String symbol) {
Symbol sym = module.findSymbolByName(symbol, false);
4
2023-10-17 06:13:28+00:00
24k
robaho/httpserver
src/test/java/jdk/test/lib/process/ProcessTools.java
[ { "identifier": "JDKToolFinder", "path": "src/test/java/jdk/test/lib/JDKToolFinder.java", "snippet": "public final class JDKToolFinder {\n\n private JDKToolFinder() {\n }\n\n /**\n * Returns the full path to an executable in jdk/bin based on System\n * property {@code test.jdk} or {@cod...
import jdk.test.lib.JDKToolFinder; import jdk.test.lib.Platform; import jdk.test.lib.Utils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.lang.Thread.State; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors;
15,136
var fileName = String.format("pid-%d-output.log", p.pid()); var processOutput = getProcessLog(pb, output); AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> { Files.writeString(Path.of(fileName), processOutput); return null; }); System.out.printf( "Output and diagnostic info for process %d " + "was saved into '%s'%n", p.pid(), fileName); } return output; } catch (Throwable t) { if (p != null) { p.destroyForcibly().waitFor(); } failed = true; System.out.println("executeProcess() failed: " + t); throw t; } finally { if (failed) { System.err.println(getProcessLog(pb, output)); } } } /** * Executes a process, waits for it to finish and returns the process output. * <p> * The process will have exited before this method returns. * * @param cmds The command line to execute. * @return The output from the process. */ public static OutputAnalyzer executeProcess(String... cmds) throws Throwable { return executeProcess(new ProcessBuilder(cmds)); } /** * Used to log command line, stdout, stderr and exit code from an executed process. * * @param pb The executed process. * @param output The output from the process. */ public static String getProcessLog(ProcessBuilder pb, OutputAnalyzer output) { String stderr = output == null ? "null" : output.getStderr(); String stdout = output == null ? "null" : output.getStdout(); String exitValue = output == null ? "null" : Integer.toString(output.getExitValue()); return String.format("--- ProcessLog ---%n" + "cmd: %s%n" + "exitvalue: %s%n" + "stderr: %s%n" + "stdout: %s%n", getCommandLine(pb), exitValue, stderr, stdout); } /** * @return The full command line for the ProcessBuilder. */ public static String getCommandLine(ProcessBuilder pb) { if (pb == null) { return "null"; } StringBuilder cmd = new StringBuilder(); for (String s : pb.command()) { cmd.append(s).append(" "); } return cmd.toString().trim(); } /** * Executes a process, waits for it to finish, prints the process output * to stdout, and returns the process output. * <p> * The process will have exited before this method returns. * * @param cmds The command line to execute. * @return The {@linkplain OutputAnalyzer} instance wrapping the process. */ public static OutputAnalyzer executeCommand(String... cmds) throws Throwable { String cmdLine = String.join(" ", cmds); System.out.println("Command line: [" + cmdLine + "]"); OutputAnalyzer analyzer = ProcessTools.executeProcess(cmds); System.out.println(analyzer.getOutput()); return analyzer; } /** * Executes a process, waits for it to finish, prints the process output * to stdout and returns the process output. * <p> * The process will have exited before this method returns. * * @param pb The ProcessBuilder to execute. * @return The {@linkplain OutputAnalyzer} instance wrapping the process. */ public static OutputAnalyzer executeCommand(ProcessBuilder pb) throws Throwable { String cmdLine = pb.command().stream() .map(x -> (x.contains(" ") || x.contains("$")) ? ("'" + x + "'") : x) .collect(Collectors.joining(" ")); System.out.println("Command line: [" + cmdLine + "]"); OutputAnalyzer analyzer = ProcessTools.executeProcess(pb); System.out.println(analyzer.getOutput()); return analyzer; } /** * Helper method to create a process builder for launching native executable * test that uses/loads JVM. * * @param executableName The name of an executable to be launched. * @param args Arguments for the executable. * @return New ProcessBuilder instance representing the command. */ public static ProcessBuilder createNativeTestProcessBuilder(String executableName, String... args) throws Exception {
/* * Copyright (c) 2013, 2023, 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. * * 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 jdk.test.lib.process; public final class ProcessTools { private static final class LineForwarder extends StreamPumper.LinePump { private final PrintStream ps; private final String prefix; LineForwarder(String prefix, PrintStream os) { this.ps = os; this.prefix = prefix; } @Override protected void processLine(String line) { ps.println("[" + prefix + "] " + line); } } private ProcessTools() { } /** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * Same as * {@linkplain #startProcess(String, ProcessBuilder, Consumer, Predicate, long, TimeUnit) startProcess} * {@code (name, processBuilder, null, null, -1, TimeUnit.NANOSECONDS)} * </p> * @param name The process name * @param processBuilder The process builder * @return Returns the initialized process * @throws IOException */ public static Process startProcess(String name, ProcessBuilder processBuilder) throws IOException { return startProcess(name, processBuilder, (Consumer<String>) null); } /** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * Same as * {@linkplain #startProcess(String, ProcessBuilder, Consumer, Predicate, long, TimeUnit) startProcess} * {@code (name, processBuilder, consumer, null, -1, TimeUnit.NANOSECONDS)} * </p> * * @param name The process name * @param processBuilder The process builder * @param consumer {@linkplain Consumer} instance to process the in-streams * @return Returns the initialized process * @throws IOException */ @SuppressWarnings("overloads") public static Process startProcess(String name, ProcessBuilder processBuilder, Consumer<String> consumer) throws IOException { try { return startProcess(name, processBuilder, consumer, null, -1, TimeUnit.NANOSECONDS); } catch (InterruptedException | TimeoutException | CancellationException e) { // will never happen throw new RuntimeException(e); } } /** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * Same as * {@linkplain #startProcess(String, ProcessBuilder, Consumer, Predicate, long, TimeUnit) startProcess} * {@code (name, processBuilder, null, linePredicate, timeout, unit)} * </p> * * @param name The process name * @param processBuilder The process builder * @param linePredicate The {@linkplain Predicate} to use on the STDOUT and STDERR. * Used to determine the moment the target app is * properly warmed-up. * It can be null - in that case the warmup is skipped. * @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever * @param unit The timeout {@linkplain TimeUnit} * @return Returns the initialized {@linkplain Process} * @throws IOException * @throws InterruptedException * @throws TimeoutException */ public static Process startProcess(String name, ProcessBuilder processBuilder, final Predicate<String> linePredicate, long timeout, TimeUnit unit) throws IOException, InterruptedException, TimeoutException { return startProcess(name, processBuilder, null, linePredicate, timeout, unit); } /* BufferOutputStream and BufferInputStream allow to re-use p.getInputStream() amd p.getOutputStream() of processes started with ProcessTools.startProcess(...). Implementation cashes ALL process output and allow to read it through InputStream. The stream uses Future<Void> task from StreamPumper.process() to check if output is complete. */ private static class BufferOutputStream extends ByteArrayOutputStream { private int current = 0; final private Process p; private Future<Void> task; public BufferOutputStream(Process p) { this.p = p; } synchronized void setTask(Future<Void> task) { this.task = task; } synchronized int readNext() { if (current > count) { throw new RuntimeException("Shouldn't ever happen. start: " + current + " count: " + count + " buffer: " + this); } while (current == count) { if (!p.isAlive() && (task != null)) { try { task.get(10, TimeUnit.MILLISECONDS); if (current == count) { return -1; } } catch (TimeoutException e) { // continue execution, so wait() give a chance to write } catch (InterruptedException | ExecutionException e) { return -1; } } try { wait(1); } catch (InterruptedException ie) { return -1; } } return this.buf[current++]; } } private static class BufferInputStream extends InputStream { private final BufferOutputStream buffer; public BufferInputStream(Process p) { buffer = new BufferOutputStream(p); } BufferOutputStream getOutputStream() { return buffer; } @Override public int read() throws IOException { return buffer.readNext(); } } /** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * It is possible to wait for the process to get to a warmed-up state * via {@linkplain Predicate} condition on the STDOUT/STDERR and monitor the * in-streams via the provided {@linkplain Consumer} * </p> * * @param name The process name * @param processBuilder The process builder * @param lineConsumer The {@linkplain Consumer} the lines will be forwarded to * @param linePredicate The {@linkplain Predicate} to use on the STDOUT and STDERR. * Used to determine the moment the target app is * properly warmed-up. * It can be null - in that case the warmup is skipped. * @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever * @param unit The timeout {@linkplain TimeUnit} * @return Returns the initialized {@linkplain Process} * @throws IOException * @throws InterruptedException * @throws TimeoutException */ public static Process startProcess(String name, ProcessBuilder processBuilder, final Consumer<String> lineConsumer, final Predicate<String> linePredicate, long timeout, TimeUnit unit) throws IOException, InterruptedException, TimeoutException { System.out.println("[" + name + "]:" + String.join(" ", processBuilder.command())); Process p = privilegedStart(processBuilder); StreamPumper stdout = new StreamPumper(p.getInputStream()); StreamPumper stderr = new StreamPumper(p.getErrorStream()); stdout.addPump(new LineForwarder(name, System.out)); stderr.addPump(new LineForwarder(name, System.err)); BufferInputStream stdOut = new BufferInputStream(p); BufferInputStream stdErr = new BufferInputStream(p); stdout.addOutputStream(stdOut.getOutputStream()); stderr.addOutputStream(stdErr.getOutputStream()); if (lineConsumer != null) { StreamPumper.LinePump pump = new StreamPumper.LinePump() { @Override protected void processLine(String line) { lineConsumer.accept(line); } }; stdout.addPump(pump); stderr.addPump(pump); } CountDownLatch latch = new CountDownLatch(1); if (linePredicate != null) { StreamPumper.LinePump pump = new StreamPumper.LinePump() { // synchronization between stdout and stderr pumps private final Object sync = new Object(); @Override protected void processLine(String line) { synchronized (sync) { if (latch.getCount() > 0 && linePredicate.test(line)) { latch.countDown(); } } } }; stdout.addPump(pump); stderr.addPump(pump); } else { latch.countDown(); } final Future<Void> stdoutTask = stdout.process(); final Future<Void> stderrTask = stderr.process(); stdOut.getOutputStream().setTask(stdoutTask); stdErr.getOutputStream().setTask(stderrTask); try { if (timeout > -1) { long timeoutMs = timeout == 0 ? -1: unit.toMillis(Utils.adjustTimeout(timeout)); // Every second check if line is printed and if process is still alive Utils.waitForCondition(() -> latch.getCount() == 0 || !p.isAlive(), timeoutMs , 1000); if (latch.getCount() > 0) { if (!p.isAlive()) { // Give some extra time for the StreamPumper to run after the process completed Thread.sleep(1000); if (latch.getCount() > 0) { throw new RuntimeException("Started process " + name + " terminated before producing the expected output."); } } else { throw new TimeoutException(); } } } } catch (TimeoutException | RuntimeException | InterruptedException e) { System.err.println("Failed to start a process (thread dump follows)"); for (Map.Entry<Thread, StackTraceElement[]> s : Thread.getAllStackTraces().entrySet()) { printStack(s.getKey(), s.getValue()); } if (p.isAlive()) { p.destroyForcibly(); } stdoutTask.cancel(true); stderrTask.cancel(true); throw e; } return new ProcessImpl(p, stdoutTask, stderrTask, stdOut, stdErr); } /** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * It is possible to wait for the process to get to a warmed-up state * via {@linkplain Predicate} condition on the STDOUT/STDERR. * The warm-up will wait indefinitely. * </p> * * @param name The process name * @param processBuilder The process builder * @param linePredicate The {@linkplain Predicate} to use on the STDOUT and STDERR. * Used to determine the moment the target app is * properly warmed-up. * It can be null - in that case the warmup is skipped. * @return Returns the initialized {@linkplain Process} * @throws IOException * @throws InterruptedException * @throws TimeoutException */ @SuppressWarnings("overloads") public static Process startProcess(String name, ProcessBuilder processBuilder, final Predicate<String> linePredicate) throws IOException, InterruptedException, TimeoutException { return startProcess(name, processBuilder, linePredicate, 0, TimeUnit.SECONDS); } /** * Get the process id of the current running Java process * * @return Process id */ public static long getProcessId() throws Exception { return ProcessHandle.current().pid(); } /** * Create ProcessBuilder using the java launcher from the jdk to be tested. * * @param command Arguments to pass to the java command. * @return The ProcessBuilder instance representing the java command. */ public static ProcessBuilder createJavaProcessBuilder(List<String> command) { return createJavaProcessBuilder(command.toArray(String[]::new)); } /* Convert arguments for tests running with virtual threads main wrapper When test is executed with process wrapper the line is changed from java <jvm-args> <test-class> <test-args> to java <jvm-args> -Dmain.wrapper=<wrapper-name> jdk.test.lib.process.ProcessTools <wrapper-name> <test-class> <test-args> */ private static List<String> addMainWrapperArgs(String mainWrapper, List<String> command) { final List<String> unsupportedArgs = List.of( "-jar", "-cp", "-classpath", "--class-path", "--describe-module", "-d", "--dry-run", "--list-modules","--validate-modules", "-m", "--module", "-version"); final List<String> doubleWordArgs = List.of( "--add-opens", "--upgrade-module-path", "--add-modules", "--add-exports", "--limit-modules", "--add-reads", "--patch-module", "--module-path", "-p"); ArrayList<String> args = new ArrayList<>(); boolean expectSecondArg = false; boolean isWrapperClassAdded = false; for (String cmd : command) { if (isWrapperClassAdded) { args.add(cmd); continue; } if (expectSecondArg) { expectSecondArg = false; args.add(cmd); continue; } if (unsupportedArgs.contains(cmd)) { return command; } if (doubleWordArgs.contains(cmd)) { expectSecondArg = true; args.add(cmd); continue; } if (expectSecondArg) { continue; } // command-line or name command-line file if (cmd.startsWith("-") || cmd.startsWith("@")) { args.add(cmd); continue; } // if command is like 'java source.java' then return if (cmd.endsWith(".java")) { return command; } // Some tests might check property to understand // if virtual threads are tested args.add("-Dmain.wrapper=" + mainWrapper); args.add("jdk.test.lib.process.ProcessTools"); args.add(mainWrapper); isWrapperClassAdded = true; args.add(cmd); } return args; } /** * Create ProcessBuilder using the java launcher from the jdk to be tested. * * @param command Arguments to pass to the java command. * @return The ProcessBuilder instance representing the java command. */ public static ProcessBuilder createJavaProcessBuilder(String... command) { String javapath = JDKToolFinder.getJDKTool("java"); ArrayList<String> args = new ArrayList<>(); args.add(javapath); String noCPString = System.getProperty("test.noclasspath", "false"); boolean noCP = Boolean.valueOf(noCPString); if (!noCP) { args.add("-cp"); args.add(System.getProperty("java.class.path")); } String mainWrapper = System.getProperty("main.wrapper"); if (mainWrapper != null) { args.addAll(addMainWrapperArgs(mainWrapper, Arrays.asList(command))); } else { Collections.addAll(args, command); } // Reporting StringBuilder cmdLine = new StringBuilder(); for (String cmd : args) cmdLine.append(cmd).append(' '); System.out.println("Command line: [" + cmdLine.toString() + "]"); ProcessBuilder pb = new ProcessBuilder(args); if (noCP) { // clear CLASSPATH from the env pb.environment().remove("CLASSPATH"); } return pb; } private static void printStack(Thread t, StackTraceElement[] stack) { System.out.println("\t" + t + " stack: (length = " + stack.length + ")"); if (t != null) { for (StackTraceElement stack1 : stack) { System.out.println("\t" + stack1); } System.out.println(); } } /** * Create ProcessBuilder using the java launcher from the jdk to be tested. * The default jvm options from jtreg, test.vm.opts and test.java.opts, are added. * <p> * The command line will be like: * {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds * Create ProcessBuilder using the java launcher from the jdk to be tested. * * @param command Arguments to pass to the java command. * @return The ProcessBuilder instance representing the java command. */ public static ProcessBuilder createTestJvm(List<String> command) { return createTestJvm(command.toArray(String[]::new)); } /** * Create ProcessBuilder using the java launcher from the jdk to be tested. * The default jvm options from jtreg, test.vm.opts and test.java.opts, are added. * <p> * The command line will be like: * {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds * Create ProcessBuilder using the java launcher from the jdk to be tested. * * @param command Arguments to pass to the java command. * @return The ProcessBuilder instance representing the java command. */ public static ProcessBuilder createTestJvm(String... command) { return createJavaProcessBuilder(Utils.prependTestJavaOpts(command)); } /** * Executes a test jvm process, waits for it to finish and returns the process output. * The default jvm options from jtreg, test.vm.opts and test.java.opts, are added. * The java from the test.jdk is used to execute the command. * <p> * The command line will be like: * {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds * <p> * The jvm process will have exited before this method returns. * * @param cmds User specified arguments. * @return The output from the process. */ public static OutputAnalyzer executeTestJvm(List<String> cmds) throws Exception { return executeTestJvm(cmds.toArray(String[]::new)); } /** * Executes a test jvm process, waits for it to finish and returns the process output. * The default jvm options from jtreg, test.vm.opts and test.java.opts, are added. * The java from the test.jdk is used to execute the command. * <p> * The command line will be like: * {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds * <p> * The jvm process will have exited before this method returns. * * @param cmds User specified arguments. * @return The output from the process. */ public static OutputAnalyzer executeTestJvm(String... cmds) throws Exception { ProcessBuilder pb = createTestJvm(cmds); return executeProcess(pb); } /** * @param cmds User specified arguments. * @return The output from the process. * @see #executeTestJvm(String...) */ public static OutputAnalyzer executeTestJava(String... cmds) throws Exception { return executeTestJvm(cmds); } /** * Executes a process, waits for it to finish and returns the process output. * The process will have exited before this method returns. * * @param pb The ProcessBuilder to execute. * @return The {@linkplain OutputAnalyzer} instance wrapping the process. */ public static OutputAnalyzer executeProcess(ProcessBuilder pb) throws Exception { return executeProcess(pb, null); } /** * Executes a process, pipe some text into its STDIN, waits for it * to finish and returns the process output. The process will have exited * before this method returns. * * @param pb The ProcessBuilder to execute. * @param input The text to pipe into STDIN. Can be null. * @return The {@linkplain OutputAnalyzer} instance wrapping the process. */ public static OutputAnalyzer executeProcess(ProcessBuilder pb, String input) throws Exception { return executeProcess(pb, input, null); } /** * Executes a process, pipe some text into its STDIN, waits for it * to finish and returns the process output. The process will have exited * before this method returns. * * @param pb The ProcessBuilder to execute. * @param input The text to pipe into STDIN. Can be null. * @param cs The charset used to convert from bytes to chars or null for * the default charset. * @return The {@linkplain OutputAnalyzer} instance wrapping the process. */ @SuppressWarnings("removal") public static OutputAnalyzer executeProcess(ProcessBuilder pb, String input, Charset cs) throws Exception { OutputAnalyzer output = null; Process p = null; boolean failed = false; try { p = privilegedStart(pb); if (input != null) { try (PrintStream ps = new PrintStream(p.getOutputStream())) { ps.print(input); } } output = new OutputAnalyzer(p, cs); p.waitFor(); { // Dumping the process output to a separate file var fileName = String.format("pid-%d-output.log", p.pid()); var processOutput = getProcessLog(pb, output); AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> { Files.writeString(Path.of(fileName), processOutput); return null; }); System.out.printf( "Output and diagnostic info for process %d " + "was saved into '%s'%n", p.pid(), fileName); } return output; } catch (Throwable t) { if (p != null) { p.destroyForcibly().waitFor(); } failed = true; System.out.println("executeProcess() failed: " + t); throw t; } finally { if (failed) { System.err.println(getProcessLog(pb, output)); } } } /** * Executes a process, waits for it to finish and returns the process output. * <p> * The process will have exited before this method returns. * * @param cmds The command line to execute. * @return The output from the process. */ public static OutputAnalyzer executeProcess(String... cmds) throws Throwable { return executeProcess(new ProcessBuilder(cmds)); } /** * Used to log command line, stdout, stderr and exit code from an executed process. * * @param pb The executed process. * @param output The output from the process. */ public static String getProcessLog(ProcessBuilder pb, OutputAnalyzer output) { String stderr = output == null ? "null" : output.getStderr(); String stdout = output == null ? "null" : output.getStdout(); String exitValue = output == null ? "null" : Integer.toString(output.getExitValue()); return String.format("--- ProcessLog ---%n" + "cmd: %s%n" + "exitvalue: %s%n" + "stderr: %s%n" + "stdout: %s%n", getCommandLine(pb), exitValue, stderr, stdout); } /** * @return The full command line for the ProcessBuilder. */ public static String getCommandLine(ProcessBuilder pb) { if (pb == null) { return "null"; } StringBuilder cmd = new StringBuilder(); for (String s : pb.command()) { cmd.append(s).append(" "); } return cmd.toString().trim(); } /** * Executes a process, waits for it to finish, prints the process output * to stdout, and returns the process output. * <p> * The process will have exited before this method returns. * * @param cmds The command line to execute. * @return The {@linkplain OutputAnalyzer} instance wrapping the process. */ public static OutputAnalyzer executeCommand(String... cmds) throws Throwable { String cmdLine = String.join(" ", cmds); System.out.println("Command line: [" + cmdLine + "]"); OutputAnalyzer analyzer = ProcessTools.executeProcess(cmds); System.out.println(analyzer.getOutput()); return analyzer; } /** * Executes a process, waits for it to finish, prints the process output * to stdout and returns the process output. * <p> * The process will have exited before this method returns. * * @param pb The ProcessBuilder to execute. * @return The {@linkplain OutputAnalyzer} instance wrapping the process. */ public static OutputAnalyzer executeCommand(ProcessBuilder pb) throws Throwable { String cmdLine = pb.command().stream() .map(x -> (x.contains(" ") || x.contains("$")) ? ("'" + x + "'") : x) .collect(Collectors.joining(" ")); System.out.println("Command line: [" + cmdLine + "]"); OutputAnalyzer analyzer = ProcessTools.executeProcess(pb); System.out.println(analyzer.getOutput()); return analyzer; } /** * Helper method to create a process builder for launching native executable * test that uses/loads JVM. * * @param executableName The name of an executable to be launched. * @param args Arguments for the executable. * @return New ProcessBuilder instance representing the command. */ public static ProcessBuilder createNativeTestProcessBuilder(String executableName, String... args) throws Exception {
executableName = Platform.isWindows() ? executableName + ".exe" : executableName;
1
2023-10-15 15:56:58+00:00
24k
team-moabam/moabam-BE
src/main/java/com/moabam/api/application/room/SearchService.java
[ { "identifier": "GlobalConstant", "path": "src/main/java/com/moabam/global/common/util/GlobalConstant.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class GlobalConstant {\n\n\tpublic static final String BLANK = \"\";\n\tpublic static final String DELIMITER = \"/\";\n\tpubli...
import static com.moabam.global.common.util.GlobalConstant.*; import static com.moabam.global.error.model.ErrorMessage.*; import static org.apache.commons.lang3.StringUtils.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.notification.NotificationService; import com.moabam.api.application.room.mapper.CertificationsMapper; import com.moabam.api.application.room.mapper.ParticipantMapper; import com.moabam.api.application.room.mapper.RoomMapper; import com.moabam.api.application.room.mapper.RoutineMapper; import com.moabam.api.domain.item.Inventory; import com.moabam.api.domain.item.repository.InventorySearchRepository; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.room.Certification; import com.moabam.api.domain.room.DailyMemberCertification; import com.moabam.api.domain.room.DailyRoomCertification; import com.moabam.api.domain.room.Participant; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.RoomType; import com.moabam.api.domain.room.Routine; import com.moabam.api.domain.room.repository.CertificationsSearchRepository; import com.moabam.api.domain.room.repository.ParticipantSearchRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.domain.room.repository.RoomSearchRepository; import com.moabam.api.domain.room.repository.RoutineRepository; import com.moabam.api.dto.room.CertificationImageResponse; import com.moabam.api.dto.room.CertificationImagesResponse; import com.moabam.api.dto.room.GetAllRoomResponse; import com.moabam.api.dto.room.GetAllRoomsResponse; import com.moabam.api.dto.room.ManageRoomResponse; import com.moabam.api.dto.room.MyRoomResponse; import com.moabam.api.dto.room.MyRoomsResponse; import com.moabam.api.dto.room.ParticipantResponse; import com.moabam.api.dto.room.RoomDetailsResponse; import com.moabam.api.dto.room.RoomHistoryResponse; import com.moabam.api.dto.room.RoomsHistoryResponse; import com.moabam.api.dto.room.RoutineResponse; import com.moabam.api.dto.room.TodayCertificateRankResponse; import com.moabam.api.dto.room.UnJoinedRoomCertificateRankResponse; import com.moabam.api.dto.room.UnJoinedRoomDetailsResponse; import com.moabam.global.common.util.ClockHolder; import com.moabam.global.error.exception.ForbiddenException; import com.moabam.global.error.exception.NotFoundException; import jakarta.annotation.Nullable; import lombok.RequiredArgsConstructor;
15,355
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class SearchService { private final RoomRepository roomRepository; private final RoomSearchRepository roomSearchRepository; private final RoutineRepository routineRepository; private final ParticipantSearchRepository participantSearchRepository; private final CertificationsSearchRepository certificationsSearchRepository; private final InventorySearchRepository inventorySearchRepository; private final CertificationService certificationService; private final MemberService memberService; private final NotificationService notificationService; private final ClockHolder clockHolder; public RoomDetailsResponse getRoomDetails(Long memberId, Long roomId, LocalDate date) {
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class SearchService { private final RoomRepository roomRepository; private final RoomSearchRepository roomSearchRepository; private final RoutineRepository routineRepository; private final ParticipantSearchRepository participantSearchRepository; private final CertificationsSearchRepository certificationsSearchRepository; private final InventorySearchRepository inventorySearchRepository; private final CertificationService certificationService; private final MemberService memberService; private final NotificationService notificationService; private final ClockHolder clockHolder; public RoomDetailsResponse getRoomDetails(Long memberId, Long roomId, LocalDate date) {
Participant participant = participantSearchRepository.findOne(memberId, roomId)
14
2023-10-20 06:15:43+00:00
24k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/button/animate/ClickShadowAnimate.java
[ { "identifier": "FxKit", "path": "BaseUI/src/main/java/com/xm2013/jfx/common/FxKit.java", "snippet": "public class FxKit {\n\n /** The Constant DOUBLE_ARROW_RIGHT. */\n public static final String DOUBLE_ARROW_RIGHT = \"<svg version=\\\"1.1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" p-id=\\\"1050...
import com.xm2013.jfx.common.FxKit; import com.xm2013.jfx.control.button.XmButton; import com.xm2013.jfx.control.button.XmButtonSkin; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.scene.effect.BlurType; import javafx.scene.effect.DropShadow; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.scene.paint.LinearGradient; import javafx.scene.paint.Paint; import javafx.scene.paint.RadialGradient; import javafx.util.Duration;
19,908
package com.xm2013.jfx.control.button.animate; /** * 阴影扩散动画 */ public class ClickShadowAnimate implements XmButtonClickAnimate{ private XmButton control;
package com.xm2013.jfx.control.button.animate; /** * 阴影扩散动画 */ public class ClickShadowAnimate implements XmButtonClickAnimate{ private XmButton control;
private XmButtonSkin skin;
2
2023-10-17 08:57:08+00:00
24k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/PCFGLA/UnaryCounterTable.java
[ { "identifier": "ArrayUtil", "path": "src/berkeley_parser/edu/berkeley/nlp/util/ArrayUtil.java", "snippet": "public class ArrayUtil {\r\n\r\n\t// ARITHMETIC FUNCTIONS\r\n\r\n\tpublic static double[] add(double[] a, double c) {\r\n\t\tdouble[] result = new double[a.length];\r\n\t\tfor (int i = 0; i < a.l...
import java.io.Serializable; import java.util.Map; import java.util.Set; import edu.berkeley.nlp.util.ArrayUtil; import edu.berkeley.nlp.util.MapFactory;
19,640
package edu.berkeley.nlp.PCFGLA; public class UnaryCounterTable implements Serializable { /** * Based on Counter. * * A map from objects to doubles. Includes convenience methods for getting, * setting, and incrementing element counts. Objects not in the counter will * return a count of zero. The counter is backed by a HashMap (unless * specified otherwise with the MapFactory constructor). * * @author Slav Petrov */ private static final long serialVersionUID = 1L; Map<UnaryRule, double[][]> entries; short[] numSubStates; UnaryRule searchKey; /** * The elements in the counter. * * @return set of keys */ public Set<UnaryRule> keySet() { return entries.keySet(); } /** * The number of entries in the counter (not the total count -- use * totalCount() instead). */ public int size() { return entries.size(); } /** * True if there are no entries in the counter (false does not mean * totalCount > 0) */ public boolean isEmpty() { return size() == 0; } /** * Returns whether the counter contains the given key. Note that this is the * way to distinguish keys which are in the counter with count zero, and * those which are not in the counter (and will therefore return count zero * from getCount(). * * @param key * @return whether the counter contains the key */ public boolean containsKey(UnaryRule key) { return entries.containsKey(key); } /** * Get the count of the element, or zero if the element is not in the * counter. Can return null! * * @param key * @return */ public double[][] getCount(UnaryRule key) { double[][] value = entries.get(key); return value; } public double[][] getCount(short pState, short cState) { searchKey.setNodes(pState, cState); double[][] value = entries.get(searchKey); return value; } /** * Set the count for the given key, clobbering any previous count. * * @param key * @param count */ public void setCount(UnaryRule key, double[][] counts) { entries.put(key, counts); } /** * Increment a key's count by the given amount. Assumes for efficiency that * the arrays have the same size. * * @param key * @param increment */ public void incrementCount(UnaryRule key, double[][] increment) { double[][] current = getCount(key); if (current == null) { setCount(key, increment); return; } for (int i = 0; i < current.length; i++) { // test if increment[i] is null or zero, in which case // we needn't add it if (increment[i] == null) continue; // allocate more space as needed if (current[i] == null) current[i] = new double[increment[i].length]; // if we've gotten here, then both current and increment // have correct arrays in index i for (int j = 0; j < current[i].length; j++) { current[i][j] += increment[i][j]; } } setCount(key, current); } public void incrementCount(UnaryRule key, double increment) { double[][] current = getCount(key); if (current == null) { double[][] tmp = key.getScores2(); current = new double[tmp.length][tmp[0].length]; ArrayUtil.fill(current, increment); setCount(key, current); return; } for (int i = 0; i < current.length; i++) { if (current[i] == null) current[i] = new double[numSubStates[key.getParentState()]]; for (int j = 0; j < current[i].length; j++) { current[i][j] += increment; } } setCount(key, current); } public UnaryCounterTable(short[] numSubStates) {
package edu.berkeley.nlp.PCFGLA; public class UnaryCounterTable implements Serializable { /** * Based on Counter. * * A map from objects to doubles. Includes convenience methods for getting, * setting, and incrementing element counts. Objects not in the counter will * return a count of zero. The counter is backed by a HashMap (unless * specified otherwise with the MapFactory constructor). * * @author Slav Petrov */ private static final long serialVersionUID = 1L; Map<UnaryRule, double[][]> entries; short[] numSubStates; UnaryRule searchKey; /** * The elements in the counter. * * @return set of keys */ public Set<UnaryRule> keySet() { return entries.keySet(); } /** * The number of entries in the counter (not the total count -- use * totalCount() instead). */ public int size() { return entries.size(); } /** * True if there are no entries in the counter (false does not mean * totalCount > 0) */ public boolean isEmpty() { return size() == 0; } /** * Returns whether the counter contains the given key. Note that this is the * way to distinguish keys which are in the counter with count zero, and * those which are not in the counter (and will therefore return count zero * from getCount(). * * @param key * @return whether the counter contains the key */ public boolean containsKey(UnaryRule key) { return entries.containsKey(key); } /** * Get the count of the element, or zero if the element is not in the * counter. Can return null! * * @param key * @return */ public double[][] getCount(UnaryRule key) { double[][] value = entries.get(key); return value; } public double[][] getCount(short pState, short cState) { searchKey.setNodes(pState, cState); double[][] value = entries.get(searchKey); return value; } /** * Set the count for the given key, clobbering any previous count. * * @param key * @param count */ public void setCount(UnaryRule key, double[][] counts) { entries.put(key, counts); } /** * Increment a key's count by the given amount. Assumes for efficiency that * the arrays have the same size. * * @param key * @param increment */ public void incrementCount(UnaryRule key, double[][] increment) { double[][] current = getCount(key); if (current == null) { setCount(key, increment); return; } for (int i = 0; i < current.length; i++) { // test if increment[i] is null or zero, in which case // we needn't add it if (increment[i] == null) continue; // allocate more space as needed if (current[i] == null) current[i] = new double[increment[i].length]; // if we've gotten here, then both current and increment // have correct arrays in index i for (int j = 0; j < current[i].length; j++) { current[i][j] += increment[i][j]; } } setCount(key, current); } public void incrementCount(UnaryRule key, double increment) { double[][] current = getCount(key); if (current == null) { double[][] tmp = key.getScores2(); current = new double[tmp.length][tmp[0].length]; ArrayUtil.fill(current, increment); setCount(key, current); return; } for (int i = 0; i < current.length; i++) { if (current[i] == null) current[i] = new double[numSubStates[key.getParentState()]]; for (int j = 0; j < current[i].length; j++) { current[i][j] += increment; } } setCount(key, current); } public UnaryCounterTable(short[] numSubStates) {
this(new MapFactory.HashMapFactory<UnaryRule, double[][]>(),
1
2023-10-22 13:13:22+00:00
24k
neftalito/R-Info-Plus
form/Parser.java
[ { "identifier": "Iniciar", "path": "arbol/sentencia/primitiva/Iniciar.java", "snippet": "public class Iniciar extends Primitiva {\n RobotAST r;\n int x;\n int y;\n Identificador Ident;\n DeclaracionRobots robAST;\n DeclaracionVariable varAST;\n\n public Iniciar(final Identificador I...
import arbol.sentencia.primitiva.Iniciar; import arbol.sentencia.primitiva.AsignarArea; import arbol.DeclaracionAreas; import arbol.Programa; import arbol.ParametroFormal; import arbol.Proceso; import arbol.RobotAST; import arbol.DeclaracionProcesos; import arbol.Cuerpo; import arbol.sentencia.IteradorCondicional; import arbol.sentencia.IteradorIncondicional; import arbol.sentencia.Seleccion; import arbol.sentencia.primitiva.Random; import arbol.sentencia.primitiva.RecibirMensaje; import arbol.sentencia.primitiva.EnviarMensaje; import arbol.sentencia.primitiva.DepositarPapel; import arbol.sentencia.primitiva.DepositarFlor; import arbol.sentencia.primitiva.TomarPapel; import arbol.sentencia.primitiva.TomarFlor; import arbol.sentencia.primitiva.Derecha; import arbol.sentencia.primitiva.Izquierda; import arbol.sentencia.primitiva.Mover; import arbol.sentencia.primitiva.Leer; import arbol.sentencia.primitiva.BloquearEsquina; import arbol.sentencia.primitiva.LiberarEsquina; import arbol.sentencia.primitiva.Primitiva; import arbol.llamada.IdentificadorLlamada; import arbol.sentencia.Sentencia; import arbol.sentencia.Asignacion; import arbol.llamada.Pos; import arbol.llamada.Informar; import java.util.ArrayList; import arbol.sentencia.Invocacion; import javax.swing.JOptionPane; import arbol.DeclaracionRobots; import arbol.Tipo; import arbol.Variable; import arbol.Identificador; import arbol.expresion.ExpresionBinaria; import arbol.expresion.ExpresionUnaria; import java.util.Stack; import arbol.DeclaracionVariable; import arbol.expresion.ValorBooleano; import arbol.expresion.ValorNumerico; import arbol.expresion.operador.relacional.MenorIgual; import arbol.expresion.operador.relacional.Menor; import arbol.expresion.operador.relacional.MayorIgual; import arbol.expresion.operador.relacional.Mayor; import arbol.expresion.operador.relacional.Igual; import arbol.expresion.operador.relacional.Distinto; import arbol.expresion.operador.booleano.Not; import arbol.expresion.operador.booleano.Or; import arbol.expresion.operador.booleano.And; import arbol.expresion.operador.aritmetico.Suma; import arbol.expresion.operador.aritmetico.Resta; import arbol.expresion.operador.aritmetico.Multiplicacion; import arbol.expresion.operador.aritmetico.Division; import arbol.expresion.operador.aritmetico.Modulo; import arbol.expresion.operador.Operador; import arbol.expresion.HayObstaculo; import arbol.expresion.HayPapelEnLaEsquina; import arbol.expresion.HayFlorEnLaEsquina; import arbol.expresion.HayPapelEnLaBolsa; import arbol.expresion.HayFlorEnLaBolsa; import arbol.expresion.PosCa; import arbol.expresion.PosAv; import arbol.expresion.CantidadFloresBolsa; import arbol.expresion.CantidadPapelesBolsa; import arbol.expresion.Expresion;
21,154
case 52: case 53: case 54: case 55: case 56: case 81: { res = true; break; } default: { res = false; break; } } return res; } public boolean isParentesis(final Token token) { boolean res = false; switch (token.kind) { case 21: case 22: { res = true; break; } default: { res = false; break; } } return res; } public boolean thereIsHighOrEqualPrecedence(final Object o) { boolean res = true; final Token t = (Token) o; if (t.kind == 21 || (this.currentToken.kind == 49 && t.kind == 50) || (this.currentToken.kind == 49 && t.kind == 51) || ((this.currentToken.kind == 48 || this.currentToken.kind == 47 || this.currentToken.kind == 81) && (t.kind == 45 || t.kind == 46))) { res = false; } return res; } public Expresion parseVariableEntorno(final Token t) { Expresion expAST = null; switch (t.kind) { case 8: { expAST = new PosAv(); break; } case 9: { expAST = new PosCa(); break; } case 11: { expAST = new HayFlorEnLaBolsa(); break; } case 13: { expAST = new HayPapelEnLaBolsa(); break; } case 10: { expAST = new HayFlorEnLaEsquina(); break; } case 12: { expAST = new HayPapelEnLaEsquina(); break; } case 63: { expAST = new HayObstaculo(); break; } case 82: { expAST = new CantidadFloresBolsa(); break; } case 83: { expAST = new CantidadPapelesBolsa(); break; } default: { expAST = null; break; } } return expAST; } public Operador parseOperador(final Token t) { Operador expAST = null; switch (t.kind) { case 47: { expAST = new Division(); break; } case 48: { expAST = new Multiplicacion(); break; } case 46: { expAST = new Resta(); break; } case 45: { expAST = new Suma(); break; } case 50: { expAST = new And(); break; } case 51: { expAST = new Or(); break; } case 49: {
package form; public class Parser { public Token currentToken; private Scanner scanner; Ciudad city; Parser(final String fuente, final Ciudad city) throws Exception { this.city = city; this.scanner = new Scanner(fuente); try { this.nextToken(); } catch (Exception e) { this.reportParseError("Error in Parser!"); } } public boolean isOperando(final Token token) { return token.kind == 23 || token.kind == 32 || token.kind == 33; } public boolean isVariableEntorno(final Token token) { switch (token.kind) { case 8: case 9: case 10: case 11: case 12: case 13: case 63: case 82: case 83: { return true; } default: { return false; } } } public boolean isOperador(final Token token) { boolean res = false; switch (token.kind) { case 30: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 81: { res = true; break; } default: { res = false; break; } } return res; } public boolean isParentesis(final Token token) { boolean res = false; switch (token.kind) { case 21: case 22: { res = true; break; } default: { res = false; break; } } return res; } public boolean thereIsHighOrEqualPrecedence(final Object o) { boolean res = true; final Token t = (Token) o; if (t.kind == 21 || (this.currentToken.kind == 49 && t.kind == 50) || (this.currentToken.kind == 49 && t.kind == 51) || ((this.currentToken.kind == 48 || this.currentToken.kind == 47 || this.currentToken.kind == 81) && (t.kind == 45 || t.kind == 46))) { res = false; } return res; } public Expresion parseVariableEntorno(final Token t) { Expresion expAST = null; switch (t.kind) { case 8: { expAST = new PosAv(); break; } case 9: { expAST = new PosCa(); break; } case 11: { expAST = new HayFlorEnLaBolsa(); break; } case 13: { expAST = new HayPapelEnLaBolsa(); break; } case 10: { expAST = new HayFlorEnLaEsquina(); break; } case 12: { expAST = new HayPapelEnLaEsquina(); break; } case 63: { expAST = new HayObstaculo(); break; } case 82: { expAST = new CantidadFloresBolsa(); break; } case 83: { expAST = new CantidadPapelesBolsa(); break; } default: { expAST = null; break; } } return expAST; } public Operador parseOperador(final Token t) { Operador expAST = null; switch (t.kind) { case 47: { expAST = new Division(); break; } case 48: { expAST = new Multiplicacion(); break; } case 46: { expAST = new Resta(); break; } case 45: { expAST = new Suma(); break; } case 50: { expAST = new And(); break; } case 51: { expAST = new Or(); break; } case 49: {
expAST = new Not();
47
2023-10-20 15:45:37+00:00
24k
moonstoneid/aero-cast
apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/eth/EthSubscriberAdapter.java
[ { "identifier": "EthRegistryProperties", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/config/EthRegistryProperties.java", "snippet": "@ConfigurationProperties(prefix = \"eth.registry\")\n@Data\npublic class EthRegistryProperties {\n public String contractAddress;\n}" }, ...
import java.util.List; import com.moonstoneid.aerocast.common.config.EthRegistryProperties; import com.moonstoneid.aerocast.common.eth.BaseEthAdapter; import com.moonstoneid.aerocast.common.eth.EthUtil; import com.moonstoneid.aerocast.common.eth.contracts.FeedRegistry; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber.CreateSubscriptionEventResponse; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber.RemoveSubscriptionEventResponse; 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;
17,732
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j public class EthSubscriberAdapter extends BaseEthAdapter { public interface EventCallback { void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr); void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr); } private final Credentials credentials; private final String regContractAddr; private final MultiValueMap<String, Disposable> eventSubscribers = new LinkedMultiValueMap<>();
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j public class EthSubscriberAdapter extends BaseEthAdapter { public interface EventCallback { void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr); void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr); } private final Credentials credentials; private final String regContractAddr; private final MultiValueMap<String, Disposable> eventSubscribers = new LinkedMultiValueMap<>();
public EthSubscriberAdapter(Web3j web3j, EthRegistryProperties ethRegistryProperties) {
0
2023-10-23 20:33:07+00:00
24k
JonnyOnlineYT/xenza
src/minecraft/net/augustus/modules/render/Line.java
[ { "identifier": "EventRender3D", "path": "src/minecraft/net/augustus/events/EventRender3D.java", "snippet": "public class EventRender3D extends Event {\n}" }, { "identifier": "Categorys", "path": "src/minecraft/net/augustus/modules/Categorys.java", "snippet": "public enum Categorys {\n ...
import java.awt.Color; import java.util.Arrays; import net.augustus.events.EventRender3D; import net.augustus.modules.Categorys; import net.augustus.modules.Module; import net.augustus.settings.BooleanValue; import net.augustus.settings.ColorSetting; import net.augustus.settings.DoubleValue; import net.lenni0451.eventapi.reflection.EventTarget; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import org.lwjgl.opengl.GL11;
21,481
package net.augustus.modules.render; public class Line extends Module { public final BooleanValue line = new BooleanValue(0, "FeetLine", this, true); public final ColorSetting color = new ColorSetting(1, "Color", this, new Color(77, 0, 255, 255)); public final DoubleValue lineWidth = new DoubleValue(2, "LineWidth", this, 2.0, 0.1, 4.0, 2); public final DoubleValue lineTime = new DoubleValue(3, "LineTime", this, 3000.0, 500.0, 20000.0, 0); public final BooleanValue killAura = new BooleanValue(4, "AuraLine", this, true); public final ColorSetting killAuraColor = new ColorSetting(5, "AuraColor", this, new Color(77, 0, 255, 255)); public final DoubleValue killAuraLineWidth = new DoubleValue(6, "AuraLineWidth", this, 2.0, 0.1, 4.0, 2); public final DoubleValue killAuraLineTime = new DoubleValue(7, "AuraLineTime", this, 3000.0, 500.0, 20000.0, 0); private java.util.ArrayList<double[]> positions = new java.util.ArrayList<>(); public Line() { super("Line", new Color(10, 20, 15), Categorys.RENDER); } @Override public void onDisable() { super.onDisable(); this.positions.clear(); } @Override public void onEnable() { super.onEnable(); this.positions = new java.util.ArrayList<>(); } @EventTarget public void onEventRender3D(EventRender3D eventRender3D) { if (this.line.getBoolean()) { GL11.glEnable(3042); GL11.glBlendFunc(770, 771); GL11.glEnable(2848); GL11.glDisable(3553); GlStateManager.disableCull(); GL11.glDepthMask(false); float x = (float)(mc.thePlayer.lastTickPosX + (mc.thePlayer.posX - mc.thePlayer.lastTickPosX) * (double)mc.getTimer().renderPartialTicks); float y = (float)( mc.thePlayer.lastTickPosY + this.lineWidth.getValue() / 100.0 + (mc.thePlayer.posY - mc.thePlayer.lastTickPosY) * (double)mc.getTimer().renderPartialTicks ); float z = (float)(mc.thePlayer.lastTickPosZ + (mc.thePlayer.posZ - mc.thePlayer.lastTickPosZ) * (double)mc.getTimer().renderPartialTicks); this.positions.add(new double[]{(double)x, (double)y, (double)z, (double)System.currentTimeMillis()}); this.positions.removeIf(values -> this.shouldRenderPoint(values[3])); GL11.glColor4f( (float)this.color.getColor().getRed() / 255.0F, (float)this.color.getColor().getGreen() / 255.0F, (float)this.color.getColor().getBlue() / 255.0F, (float)this.color.getColor().getAlpha() / 255.0F ); GL11.glLineWidth((float)this.lineWidth.getValue());
package net.augustus.modules.render; public class Line extends Module { public final BooleanValue line = new BooleanValue(0, "FeetLine", this, true); public final ColorSetting color = new ColorSetting(1, "Color", this, new Color(77, 0, 255, 255)); public final DoubleValue lineWidth = new DoubleValue(2, "LineWidth", this, 2.0, 0.1, 4.0, 2); public final DoubleValue lineTime = new DoubleValue(3, "LineTime", this, 3000.0, 500.0, 20000.0, 0); public final BooleanValue killAura = new BooleanValue(4, "AuraLine", this, true); public final ColorSetting killAuraColor = new ColorSetting(5, "AuraColor", this, new Color(77, 0, 255, 255)); public final DoubleValue killAuraLineWidth = new DoubleValue(6, "AuraLineWidth", this, 2.0, 0.1, 4.0, 2); public final DoubleValue killAuraLineTime = new DoubleValue(7, "AuraLineTime", this, 3000.0, 500.0, 20000.0, 0); private java.util.ArrayList<double[]> positions = new java.util.ArrayList<>(); public Line() { super("Line", new Color(10, 20, 15), Categorys.RENDER); } @Override public void onDisable() { super.onDisable(); this.positions.clear(); } @Override public void onEnable() { super.onEnable(); this.positions = new java.util.ArrayList<>(); } @EventTarget public void onEventRender3D(EventRender3D eventRender3D) { if (this.line.getBoolean()) { GL11.glEnable(3042); GL11.glBlendFunc(770, 771); GL11.glEnable(2848); GL11.glDisable(3553); GlStateManager.disableCull(); GL11.glDepthMask(false); float x = (float)(mc.thePlayer.lastTickPosX + (mc.thePlayer.posX - mc.thePlayer.lastTickPosX) * (double)mc.getTimer().renderPartialTicks); float y = (float)( mc.thePlayer.lastTickPosY + this.lineWidth.getValue() / 100.0 + (mc.thePlayer.posY - mc.thePlayer.lastTickPosY) * (double)mc.getTimer().renderPartialTicks ); float z = (float)(mc.thePlayer.lastTickPosZ + (mc.thePlayer.posZ - mc.thePlayer.lastTickPosZ) * (double)mc.getTimer().renderPartialTicks); this.positions.add(new double[]{(double)x, (double)y, (double)z, (double)System.currentTimeMillis()}); this.positions.removeIf(values -> this.shouldRenderPoint(values[3])); GL11.glColor4f( (float)this.color.getColor().getRed() / 255.0F, (float)this.color.getColor().getGreen() / 255.0F, (float)this.color.getColor().getBlue() / 255.0F, (float)this.color.getColor().getAlpha() / 255.0F ); GL11.glLineWidth((float)this.lineWidth.getValue());
Tessellator tessellator = Tessellator.getInstance();
7
2023-10-15 00:21:15+00:00
24k
instrumental-id/iiq-common-public
src/com/identityworksllc/iiq/common/query/QueryUtil.java
[ { "identifier": "ResultSetIterator", "path": "src/com/identityworksllc/iiq/common/iterators/ResultSetIterator.java", "snippet": "@SuppressWarnings(\"unused\")\npublic final class ResultSetIterator implements Iterator<Object[]>, AutoCloseable {\n\n\t/**\n\t * An interface to use for custom type handlers\...
import com.identityworksllc.iiq.common.iterators.ResultSetIterator; import com.identityworksllc.iiq.common.threads.PooledWorkerResults; import com.identityworksllc.iiq.common.threads.SailPointWorker; import com.identityworksllc.iiq.common.vo.Failure; import openconnector.Util; import org.apache.commons.logging.Log; import sailpoint.api.SailPointContext; import sailpoint.api.SailPointFactory; import sailpoint.object.Filter; import sailpoint.object.QueryOptions; import sailpoint.object.SailPointObject; import sailpoint.tools.GeneralException; import sailpoint.tools.ObjectNotFoundException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger;
14,611
private final Log logger; /** * Connection to SailPoint */ private final SailPointContext sailPointContext; /** * Constructor * @param Log logger * @throws GeneralException if there is an error getting the current thread's SailPoint context */ public QueryUtil(@SuppressWarnings("unused") Log Log) throws GeneralException { this(SailPointFactory.getCurrentContext(), Log); } /** * Constructor * @param context The SailPoint context * @param log The logger */ public QueryUtil(SailPointContext context, Log log) { this.sailPointContext = context; this.logger = log; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public T getResult(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); T output = null; try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { if (results.next()) { output = processor.processResult(results); } else { processor.noResult(); } } } } return output; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public List<T> getResults(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); List<T> output = new ArrayList<>(); try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { boolean hasResults = false; while (results.next()) { hasResults = true; output.add(processor.processResult(results)); } if (!hasResults) { processor.noResult(); } } } } return output; } /** * Iterates a query by invoking a Beanshell callback for each method * @param inputs The inputs * @throws GeneralException if anything goes wrong */ public void iterateQuery(IterateQueryOptions inputs) throws GeneralException { try (Connection connection = inputs.openConnection()) { try (NamedParameterStatement stmt = new NamedParameterStatement(connection, inputs.getQuery())) { if (!Util.isEmpty(inputs.getQueryParams())) { stmt.setParameters(inputs.getQueryParams()); } try (ResultSet results = stmt.executeQuery()) { ResultSetMetaData rsmd = results.getMetaData(); List<String> columns = new ArrayList<>(); for(int c = 1; c <= rsmd.getColumnCount(); c++) { columns.add(rsmd.getColumnLabel(c)); } ResultSetIterator rsi = new ResultSetIterator(results, columns, sailPointContext); while(rsi.hasNext()) { Map<String, Object> row = rsi.nextRow(); inputs.doCallback(row); } } } } catch(SQLException e) { throw new GeneralException(e); } } /** * Iterates over a query in parallel, making a call to the defined callback * in the input options. (NOTE: Beanshell is explicitly thread-safe, but you * should use the thread context provided and you should not access shared * resources without doing your own thread-safety stuff.) * * @param inputs The input options * @param threads The number of threads to use * @throws GeneralException if anything fails */
package com.identityworksllc.iiq.common.query; /** * Simplifies querying by automatically enclosing queries in a result processing loop. * This is copied from an older project. IIQ also provides a number of similar utilities * in their JdbcUtil class. * * @param <T> The type returned from the result processor */ @SuppressWarnings("unused") public class QueryUtil<T> { /** * Callback for processing the result * * @param <U> The type returned from the result processor, must extend T */ @FunctionalInterface public interface ResultProcessor<U> { /** * Callback to indicate that the result set had no results * * @throws SQLException on failures */ @SuppressWarnings("unused") default void noResult() throws SQLException { // Blank by default } /** * Called once per result. Do not call "next" on the ResultSet here. * * @param result The result set at the current point * @return An object of type T * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ U processResult(ResultSet result) throws GeneralException, SQLException; } /** * Static helper method to retrieve the first value from the result set as a long * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static Long getLongValue(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<Long>(Log).getResult(query, result -> result.getLong(resultColumn), parameters); } /** * Retrieves the first string from the result set in the given column, then * queries for a sailPoint object of the given type based on that name or * ID. The column name is assumed to be 'id', which is the primary key in * most of the SailPoint tables. * * @param context The Sailpoint context to use to query * @param cls The class to query based on the ID being pulled * @param query The query to run * @param log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static <T extends SailPointObject> T getObjectByQuery(final SailPointContext context, Class<T> cls, final String query, final Log log, Object... parameters) throws Throwable { return getObjectByQuery(context, cls, query, "id", log, parameters); } /** * Retrieves the first string from the result set in the given column, then * queries for a sailPoint object of the given type based on that name or * ID. * * @param context The Sailpoint context to use to query * @param cls The class to query based on the ID being pulled * @param query The query to run * @param idColumn The column to grab from the results * @param log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static <T extends SailPointObject> T getObjectByQuery(final SailPointContext context, Class<T> cls, final String query, final String idColumn, final Log log, Object... parameters) throws Throwable { String id = getStringValue(query, idColumn, log, parameters); return context.getObject(cls, id); } /** * Static helper method ot retrieve values from the query as a list of strings * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static List<String> getStringList(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<String>(Log).getResults(query, result -> result.getString(resultColumn), parameters); } /** * Static helper method to retrieve the first string value from the result set * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static String getStringValue(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<String>(Log).getResult(query, result -> result.getString(resultColumn), parameters); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param filterString The Filter string * @param <T> The type of the object to query * @return The queried object * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, String filterString) throws GeneralException { Filter filter = Filter.compile(filterString); return getUniqueObject(context, cls, filter); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param filter a Filter object * @param <T> The type of the object to query * @return The queried object * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, Filter filter) throws GeneralException { QueryOptions qo = new QueryOptions(); qo.add(filter); return getUniqueObject(context, cls, qo); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param queryOptions a QueryOptions object which will be cloned before querying * @param <T> The type of the object to query * @return The queried object * @throws ObjectNotFoundException if no matches are found * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, QueryOptions queryOptions) throws ObjectNotFoundException, GeneralException { QueryOptions qo = new QueryOptions(); qo.setFilters(queryOptions.getFilters()); qo.setCacheResults(queryOptions.isCacheResults()); qo.setDirtyRead(queryOptions.isDirtyRead()); qo.setDistinct(queryOptions.isDistinct()); qo.setFlushBeforeQuery(queryOptions.isFlushBeforeQuery()); qo.setGroupBys(queryOptions.getGroupBys()); qo.setOrderings(queryOptions.getOrderings()); qo.setScopeResults(queryOptions.getScopeResults()); qo.setTransactionLock(queryOptions.isTransactionLock()); qo.setUnscopedGloballyAccessible(queryOptions.getUnscopedGloballyAccessible()); qo.setResultLimit(2); List<T> results = context.getObjects(cls, qo); if (results == null || results.isEmpty()) { throw new ObjectNotFoundException(); } else if (results.size() > 1) { throw new GeneralException("Expected a unique result, got " + results.size() + " results"); } return results.get(0); } /** * Set up the given parameters in the prepared statmeent * @param stmt The statement * @param parameters The parameters * @throws SQLException if any failures occur setting parameters */ public static void setupParameters(PreparedStatement stmt, Object[] parameters) throws SQLException { Parameters.setupParameters(stmt, parameters); } /** * Logger */ private final Log logger; /** * Connection to SailPoint */ private final SailPointContext sailPointContext; /** * Constructor * @param Log logger * @throws GeneralException if there is an error getting the current thread's SailPoint context */ public QueryUtil(@SuppressWarnings("unused") Log Log) throws GeneralException { this(SailPointFactory.getCurrentContext(), Log); } /** * Constructor * @param context The SailPoint context * @param log The logger */ public QueryUtil(SailPointContext context, Log log) { this.sailPointContext = context; this.logger = log; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public T getResult(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); T output = null; try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { if (results.next()) { output = processor.processResult(results); } else { processor.noResult(); } } } } return output; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public List<T> getResults(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); List<T> output = new ArrayList<>(); try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { boolean hasResults = false; while (results.next()) { hasResults = true; output.add(processor.processResult(results)); } if (!hasResults) { processor.noResult(); } } } } return output; } /** * Iterates a query by invoking a Beanshell callback for each method * @param inputs The inputs * @throws GeneralException if anything goes wrong */ public void iterateQuery(IterateQueryOptions inputs) throws GeneralException { try (Connection connection = inputs.openConnection()) { try (NamedParameterStatement stmt = new NamedParameterStatement(connection, inputs.getQuery())) { if (!Util.isEmpty(inputs.getQueryParams())) { stmt.setParameters(inputs.getQueryParams()); } try (ResultSet results = stmt.executeQuery()) { ResultSetMetaData rsmd = results.getMetaData(); List<String> columns = new ArrayList<>(); for(int c = 1; c <= rsmd.getColumnCount(); c++) { columns.add(rsmd.getColumnLabel(c)); } ResultSetIterator rsi = new ResultSetIterator(results, columns, sailPointContext); while(rsi.hasNext()) { Map<String, Object> row = rsi.nextRow(); inputs.doCallback(row); } } } } catch(SQLException e) { throw new GeneralException(e); } } /** * Iterates over a query in parallel, making a call to the defined callback * in the input options. (NOTE: Beanshell is explicitly thread-safe, but you * should use the thread context provided and you should not access shared * resources without doing your own thread-safety stuff.) * * @param inputs The input options * @param threads The number of threads to use * @throws GeneralException if anything fails */
public PooledWorkerResults<Map<String, Object>> parallelIterateQuery(IterateQueryOptions inputs, int threads) throws GeneralException {
1
2023-10-20 15:20:16+00:00
24k
mosaic-addons/traffic-state-estimation
src/main/java/com/dcaiti/mosaic/app/tse/TseServerApp.java
[ { "identifier": "FcdRecord", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FcdRecord.java", "snippet": "public class FcdRecord extends FxdRecord {\n\n /**\n * List of vehicles perceived during the collection of FCD in the form of {@link VehicleObject VehicleObjects}.\n */\n private...
import java.nio.file.Path; import java.nio.file.Paths; import com.dcaiti.mosaic.app.fxd.data.FcdRecord; import com.dcaiti.mosaic.app.fxd.data.FcdTraversal; import com.dcaiti.mosaic.app.fxd.messages.FcdUpdateMessage; import com.dcaiti.mosaic.app.tse.config.CTseServerApp; import com.dcaiti.mosaic.app.tse.persistence.FcdDataStorage; import com.dcaiti.mosaic.app.tse.persistence.FcdDatabaseHelper; import com.dcaiti.mosaic.app.tse.persistence.ScenarioDatabaseHelper; import com.dcaiti.mosaic.app.tse.processors.SpatioTemporalProcessor; import com.dcaiti.mosaic.app.tse.processors.ThresholdProcessor; import org.eclipse.mosaic.lib.database.Database; import org.eclipse.mosaic.lib.objects.v2x.V2xMessage; import org.eclipse.mosaic.lib.util.scheduling.EventManager; import com.google.common.collect.Lists;
15,717
/* * Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse; /** * An extension of {@link FxdReceiverApp} adding the data storage in the form of the {@link FcdDataStorage} and the * Network-{@link Database} and configuring default * {@link com.dcaiti.mosaic.app.tse.processors.FxdProcessor FxdProcessors}. */ public class TseServerApp extends FxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage, CTseServerApp, TseKernel> { /** * Storage field, allowing to persist TSE results as well as data exchange between processors. * Default value will be a {@link FcdDatabaseHelper} */ private FcdDataStorage fcdDataStorage; public TseServerApp() { super(CTseServerApp.class); } @Override public void enableCellModule() { getOs().getCellModule().enable(); } /** * Initializes the {@link TseKernel} by * <ul> * <li>validating that processors for minimal function are configured,</li> * <li> reading the scenario database for access to network specific data,</li> * <li>and setting up the {@link #fcdDataStorage} to persist TSE metrics.</li> * </ul> * * @param eventManager the {@link EventManager} to enable the kernel with event handling capabilities * @param config configuration for the server * @return the initialized {@link TseKernel} */ @Override protected TseKernel initKernel(EventManager eventManager, CTseServerApp config) { addRequiredProcessors(config); Database networkDatabase = ScenarioDatabaseHelper.getNetworkDbFromFile(getOs()); String databaseDirectory = config.databasePath == null ? getOs().getConfigurationPath().getPath() : getConfiguration().databasePath; String databaseFileName = getConfiguration().databaseFileName == null ? "FcdData.sqlite" : getConfiguration().databaseFileName; Path databasePath = Paths.get(databaseDirectory, databaseFileName); // set data storage to configured type else use default FcdDatabaseHelper fcdDataStorage = config.fcdDataStorage == null ? new FcdDatabaseHelper() : config.fcdDataStorage; fcdDataStorage.initialize(databasePath, networkDatabase, config.isPersistent, getLog()); return new TseKernel(eventManager, getLog(), config, fcdDataStorage, networkDatabase); } private void addRequiredProcessors(CTseServerApp config) { if (config.traversalBasedProcessors == null) {
/* * Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse; /** * An extension of {@link FxdReceiverApp} adding the data storage in the form of the {@link FcdDataStorage} and the * Network-{@link Database} and configuring default * {@link com.dcaiti.mosaic.app.tse.processors.FxdProcessor FxdProcessors}. */ public class TseServerApp extends FxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage, CTseServerApp, TseKernel> { /** * Storage field, allowing to persist TSE results as well as data exchange between processors. * Default value will be a {@link FcdDatabaseHelper} */ private FcdDataStorage fcdDataStorage; public TseServerApp() { super(CTseServerApp.class); } @Override public void enableCellModule() { getOs().getCellModule().enable(); } /** * Initializes the {@link TseKernel} by * <ul> * <li>validating that processors for minimal function are configured,</li> * <li> reading the scenario database for access to network specific data,</li> * <li>and setting up the {@link #fcdDataStorage} to persist TSE metrics.</li> * </ul> * * @param eventManager the {@link EventManager} to enable the kernel with event handling capabilities * @param config configuration for the server * @return the initialized {@link TseKernel} */ @Override protected TseKernel initKernel(EventManager eventManager, CTseServerApp config) { addRequiredProcessors(config); Database networkDatabase = ScenarioDatabaseHelper.getNetworkDbFromFile(getOs()); String databaseDirectory = config.databasePath == null ? getOs().getConfigurationPath().getPath() : getConfiguration().databasePath; String databaseFileName = getConfiguration().databaseFileName == null ? "FcdData.sqlite" : getConfiguration().databaseFileName; Path databasePath = Paths.get(databaseDirectory, databaseFileName); // set data storage to configured type else use default FcdDatabaseHelper fcdDataStorage = config.fcdDataStorage == null ? new FcdDatabaseHelper() : config.fcdDataStorage; fcdDataStorage.initialize(databasePath, networkDatabase, config.isPersistent, getLog()); return new TseKernel(eventManager, getLog(), config, fcdDataStorage, networkDatabase); } private void addRequiredProcessors(CTseServerApp config) { if (config.traversalBasedProcessors == null) {
config.traversalBasedProcessors = Lists.newArrayList(new SpatioTemporalProcessor());
7
2023-10-23 16:39:40+00:00
24k
Primogem-Craft-Development/Primogem-Craft-Fabric
src/main/java/com/primogemstudio/primogemcraft/PrimogemCraftCreativeTabs.java
[ { "identifier": "PrimogemCraftItems", "path": "src/main/java/com/primogemstudio/primogemcraft/items/PrimogemCraftItems.java", "snippet": "public class PrimogemCraftItems {\n public static final TheAllBeginningItem THE_ALL_BEGINNING_ITEM = register(\"the_all_beginning\", new TheAllBeginningItem());\n ...
import com.google.common.collect.ImmutableList; import com.primogemstudio.primogemcraft.items.PrimogemCraftItems; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; import static com.primogemstudio.primogemcraft.PrimogemCraftFabric.MOD_ID; import static com.primogemstudio.primogemcraft.blocks.PrimogemCraftBlocks.*; import static com.primogemstudio.primogemcraft.items.PrimogemCraftItems.*;
15,604
package com.primogemstudio.primogemcraft; public class PrimogemCraftCreativeTabs { public static final ResourceKey<CreativeModeTab> KEY_MAIN = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(MOD_ID, "primogemcraft_tab")); public static final ResourceKey<CreativeModeTab> KEY_BLOCKS = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(MOD_ID, "primogemcraft_blocks_tab")); public static final ResourceKey<CreativeModeTab> KEY_TOOLS = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(MOD_ID, "primogemcraft_tools_tab")); public static void init() {
package com.primogemstudio.primogemcraft; public class PrimogemCraftCreativeTabs { public static final ResourceKey<CreativeModeTab> KEY_MAIN = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(MOD_ID, "primogemcraft_tab")); public static final ResourceKey<CreativeModeTab> KEY_BLOCKS = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(MOD_ID, "primogemcraft_blocks_tab")); public static final ResourceKey<CreativeModeTab> KEY_TOOLS = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(MOD_ID, "primogemcraft_tools_tab")); public static void init() {
PrimogemCraftItems.init();
3
2023-10-15 08:07:06+00:00
24k
eclipse-egit/egit
org.eclipse.egit.gitflow.ui/src/org/eclipse/egit/gitflow/ui/internal/actions/FeatureFinishHandler.java
[ { "identifier": "error", "path": "org.eclipse.egit.gitflow.ui/src/org/eclipse/egit/gitflow/ui/Activator.java", "snippet": "public static IStatus error(String message, Throwable throwable) {\n\treturn new Status(IStatus.ERROR, getPluginId(), 0, message, throwable);\n}" }, { "identifier": "JobUtil...
import static org.eclipse.egit.gitflow.ui.Activator.error; import java.io.IOException; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.egit.core.internal.job.JobUtil; import org.eclipse.egit.core.op.CommitOperation; import org.eclipse.egit.gitflow.GitFlowRepository; import org.eclipse.egit.gitflow.WrongGitFlowStateException; import org.eclipse.egit.gitflow.op.FeatureFinishOperation; import org.eclipse.egit.gitflow.ui.Activator; import org.eclipse.egit.gitflow.ui.internal.JobFamilies; import org.eclipse.egit.gitflow.ui.internal.UIText; import org.eclipse.egit.gitflow.ui.internal.dialogs.FinishFeatureDialog; import org.eclipse.egit.ui.internal.UIRepositoryUtils; import org.eclipse.egit.ui.internal.commit.CommitHelper; import org.eclipse.egit.ui.internal.rebase.CommitMessageEditorDialog; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.window.Window; import org.eclipse.jgit.api.MergeResult; import org.eclipse.jgit.api.MergeResult.MergeStatus; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.CommitConfig.CleanupMode; import org.eclipse.jgit.lib.Repository; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil;
16,743
/******************************************************************************* * Copyright (C) 2015, Max Hohenegger <eclipse@hohenegger.eu> * * 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 *******************************************************************************/ package org.eclipse.egit.gitflow.ui.internal.actions; /** * git flow feature finish */ public class FeatureFinishHandler extends AbstractGitFlowHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { final GitFlowRepository gfRepo = GitFlowHandlerUtil.getRepository(event); if (gfRepo == null) {
/******************************************************************************* * Copyright (C) 2015, Max Hohenegger <eclipse@hohenegger.eu> * * 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 *******************************************************************************/ package org.eclipse.egit.gitflow.ui.internal.actions; /** * git flow feature finish */ public class FeatureFinishHandler extends AbstractGitFlowHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { final GitFlowRepository gfRepo = GitFlowHandlerUtil.getRepository(event); if (gfRepo == null) {
return error(UIText.Handlers_noGitflowRepositoryFound);
0
2023-10-20 15:17:51+00:00
24k
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/query/Q3.java
[ { "identifier": "OLAPTerminal", "path": "code/src/main/java/benchmark/olap/OLAPTerminal.java", "snippet": "public class OLAPTerminal implements Runnable {\n // public static AtomicInteger DeliveryBG=new AtomicInteger(0);\n public static AtomicLong oorderTableSize = new AtomicLong(benchmark.olap.qu...
import benchmark.olap.OLAPTerminal; import benchmark.oltp.OLTPClient; import config.CommonConfig; import org.apache.log4j.Logger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import static config.CommonConfig.DB_OCEANBASE;
14,512
package benchmark.olap.query; public class Q3 extends baseQuery { private static final Logger log = Logger.getLogger(Q3.class); public double k; public double b; private final int dbType; public Q3(int dbType) throws ParseException { super(); this.filterRate = benchmark.olap.OLAPClient.filterRate[2]; //0.0480 this.dbType = dbType; this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException { double countNumber = OLAPTerminal.orderLineTableSize.get() * filterRate; SimpleDateFormat simFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start_d = simFormat.parse("1998-08-12 00:00:00");//min date 1992-01-01,1995-03-15 Date start_d_1 = simFormat.parse("1992-01-11 00:00:00"); if (countNumber > OLAPTerminal.orderlineTableNotNullSize.get()) { int s = (int) (((countNumber - this.b) / this.k) / 1000); return simFormat.format(super.getDateAfter(start_d, s)); } else { int s = (int) ((countNumber / OLAPTerminal.orderlineTableNotNullSize.get()) * ((2405 + OLTPClient.deltaDays2) * 24 * 60 * 60)); return simFormat.format(super.getDateAfter(start_d_1, s)); } } @Override public String getQuery() throws ParseException { String query;
package benchmark.olap.query; public class Q3 extends baseQuery { private static final Logger log = Logger.getLogger(Q3.class); public double k; public double b; private final int dbType; public Q3(int dbType) throws ParseException { super(); this.filterRate = benchmark.olap.OLAPClient.filterRate[2]; //0.0480 this.dbType = dbType; this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException { double countNumber = OLAPTerminal.orderLineTableSize.get() * filterRate; SimpleDateFormat simFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start_d = simFormat.parse("1998-08-12 00:00:00");//min date 1992-01-01,1995-03-15 Date start_d_1 = simFormat.parse("1992-01-11 00:00:00"); if (countNumber > OLAPTerminal.orderlineTableNotNullSize.get()) { int s = (int) (((countNumber - this.b) / this.k) / 1000); return simFormat.format(super.getDateAfter(start_d, s)); } else { int s = (int) ((countNumber / OLAPTerminal.orderlineTableNotNullSize.get()) * ((2405 + OLTPClient.deltaDays2) * 24 * 60 * 60)); return simFormat.format(super.getDateAfter(start_d_1, s)); } } @Override public String getQuery() throws ParseException { String query;
if (this.dbType == CommonConfig.DB_TIDB) {
2
2023-10-22 11:22:32+00:00
24k
bowbahdoe/java-audio-stack
vorbisspi/src/main/java/dev/mccue/vorbisspi/vorbis/sampled/convert/DecodedVorbisAudioInputStream.java
[ { "identifier": "PropertiesContainer", "path": "vorbisspi/src/main/java/dev/mccue/vorbisspi/PropertiesContainer.java", "snippet": "public interface PropertiesContainer\r\n{\r\n\tpublic Map properties();\r\n}\r" }, { "identifier": "TDebug", "path": "tritonus-share/src/main/java/dev/mccue/trit...
import dev.mccue.vorbisspi.PropertiesContainer; import dev.mccue.tritonus.share.TDebug; import dev.mccue.tritonus.share.sampled.convert.TAsynchronousFilteredAudioInputStream; import dev.mccue.jogg.Packet; import dev.mccue.jogg.Page; import dev.mccue.jogg.StreamState; import dev.mccue.jogg.SyncState; import dev.mccue.jorbis.Block; import dev.mccue.jorbis.Comment; import dev.mccue.jorbis.DspState; import dev.mccue.jorbis.Info; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream;
20,290
/* * DecodedVorbisAudioInputStream * * JavaZOOM : vorbisspi@javazoom.net * http://www.javazoom.net * * ---------------------------------------------------------------------------- * 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. * ---------------------------------------------------------------------------- */ package dev.mccue.vorbisspi.vorbis.sampled.convert; /** * This class implements the Vorbis decoding. */ @SuppressWarnings("unchecked") public class DecodedVorbisAudioInputStream extends TAsynchronousFilteredAudioInputStream implements PropertiesContainer { private InputStream oggBitStream_ = null; private SyncState oggSyncState_ = null; private StreamState oggStreamState_ = null; private Page oggPage_ = null;
/* * DecodedVorbisAudioInputStream * * JavaZOOM : vorbisspi@javazoom.net * http://www.javazoom.net * * ---------------------------------------------------------------------------- * 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. * ---------------------------------------------------------------------------- */ package dev.mccue.vorbisspi.vorbis.sampled.convert; /** * This class implements the Vorbis decoding. */ @SuppressWarnings("unchecked") public class DecodedVorbisAudioInputStream extends TAsynchronousFilteredAudioInputStream implements PropertiesContainer { private InputStream oggBitStream_ = null; private SyncState oggSyncState_ = null; private StreamState oggStreamState_ = null; private Page oggPage_ = null;
private Packet oggPacket_ = null;
3
2023-10-19 14:09:37+00:00
24k
AstroDev2023/2023-studio-1-but-better
source/core/src/test/com/csse3200/game/components/player/InventoryHotkeyTest.java
[ { "identifier": "TestGameArea", "path": "source/core/src/main/com/csse3200/game/areas/TestGameArea.java", "snippet": "public class TestGameArea extends GameArea {\n\tprivate GameMap gameMap;\n\tprivate ClimateController climateController = new ClimateController();\n\n\t@Override\n\tpublic void create() ...
import com.csse3200.game.areas.TestGameArea; import com.csse3200.game.areas.terrain.GameMap; import com.csse3200.game.components.items.ItemComponent; import com.csse3200.game.components.items.ItemType; import com.csse3200.game.entities.Entity; import com.csse3200.game.extensions.GameExtension; import com.csse3200.game.input.InputService; import com.csse3200.game.services.ResourceService; import com.csse3200.game.services.ServiceLocator; import com.csse3200.game.services.sound.EffectSoundFile; import com.csse3200.game.services.sound.InvalidSoundFileException; import com.csse3200.game.services.sound.SoundFile; import com.csse3200.game.services.sound.SoundService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.params.provider.Arguments.arguments; import static org.mockito.Mockito.*;
18,868
package com.csse3200.game.components.player; @ExtendWith(GameExtension.class) class InventoryHotkeyTest { private Entity player; private InventoryComponent inventoryComponent; private PlayerActions playerActions; private KeyboardPlayerInputComponent keyboardPlayerInputComponent; private static final Logger logger = LoggerFactory.getLogger(InventoryHotkeyTest.class); String[] texturePaths = {"images/tool_shovel.png"}; //TestGameArea to register so GameMap can be accessed through the ServiceLocator private static final TestGameArea gameArea = new TestGameArea(); // Necessary for the playerActions component @BeforeAll static void setupGameAreaAndMap() { GameMap gameMap = mock(GameMap.class); gameArea.setGameMap(gameMap); } @BeforeEach void initialiseTest() { ServiceLocator.registerResourceService(new ResourceService()); ServiceLocator.getResourceService().loadTextures(texturePaths); ServiceLocator.getResourceService().loadAll(); inventoryComponent = spy(new InventoryComponent(new ArrayList<>())); keyboardPlayerInputComponent = spy(new KeyboardPlayerInputComponent()); ServiceLocator.registerInputService(new InputService()); ServiceLocator.registerGameArea(gameArea); playerActions = spy(new PlayerActions()); keyboardPlayerInputComponent.setActions(playerActions); player = new Entity() .addComponent(inventoryComponent) .addComponent(keyboardPlayerInputComponent) .addComponent(playerActions); player.create(); String[] itemNames = {"Hoe", "Hoe1", "Hoe2", "Hoe3", "Hoe4", "Hoe5", "Hoe6", "Hoe7", "Hoe8", "Hoe9", "Hoe10"}; List<Entity> items = new ArrayList<>(); for (int i = 0; i < itemNames.length; ) { items.add(new Entity().addComponent(new ItemComponent(itemNames[i++], ItemType.HOE, "images/tool_shovel.png"))); } inventoryComponent.setInventory(items); //Set up the dependencies for the item select sound ServiceLocator.registerSoundService(new SoundService()); java.util.List<SoundFile> effects = new ArrayList<>();
package com.csse3200.game.components.player; @ExtendWith(GameExtension.class) class InventoryHotkeyTest { private Entity player; private InventoryComponent inventoryComponent; private PlayerActions playerActions; private KeyboardPlayerInputComponent keyboardPlayerInputComponent; private static final Logger logger = LoggerFactory.getLogger(InventoryHotkeyTest.class); String[] texturePaths = {"images/tool_shovel.png"}; //TestGameArea to register so GameMap can be accessed through the ServiceLocator private static final TestGameArea gameArea = new TestGameArea(); // Necessary for the playerActions component @BeforeAll static void setupGameAreaAndMap() { GameMap gameMap = mock(GameMap.class); gameArea.setGameMap(gameMap); } @BeforeEach void initialiseTest() { ServiceLocator.registerResourceService(new ResourceService()); ServiceLocator.getResourceService().loadTextures(texturePaths); ServiceLocator.getResourceService().loadAll(); inventoryComponent = spy(new InventoryComponent(new ArrayList<>())); keyboardPlayerInputComponent = spy(new KeyboardPlayerInputComponent()); ServiceLocator.registerInputService(new InputService()); ServiceLocator.registerGameArea(gameArea); playerActions = spy(new PlayerActions()); keyboardPlayerInputComponent.setActions(playerActions); player = new Entity() .addComponent(inventoryComponent) .addComponent(keyboardPlayerInputComponent) .addComponent(playerActions); player.create(); String[] itemNames = {"Hoe", "Hoe1", "Hoe2", "Hoe3", "Hoe4", "Hoe5", "Hoe6", "Hoe7", "Hoe8", "Hoe9", "Hoe10"}; List<Entity> items = new ArrayList<>(); for (int i = 0; i < itemNames.length; ) { items.add(new Entity().addComponent(new ItemComponent(itemNames[i++], ItemType.HOE, "images/tool_shovel.png"))); } inventoryComponent.setInventory(items); //Set up the dependencies for the item select sound ServiceLocator.registerSoundService(new SoundService()); java.util.List<SoundFile> effects = new ArrayList<>();
effects.add(EffectSoundFile.HOTKEY_SELECT);
9
2023-10-17 22:34:04+00:00
24k
moeinfatehi/PassiveDigger
src/PassiveDigger/PassiveAnalyzer.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 ...
import burp.BurpExtender; import burp.IBurpExtenderCallbacks; import burp.IHttpRequestResponse; import burp.IHttpService; import burp.IParameter; import burp.IRequestInfo; import burp.IResponseInfo; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter;
15,836
int index=AnalyzerTable.getSelectedRow(); int ind=(int)AnalyzerTable.getValueAt(index, 0)-1; if(vulnerabilityList.get(ind)!=null){ try { vulnerability vuln = vulnerabilityList.get(ind); vulnerabilityForm.setReqResp(vuln.reqResp); vulnerabilityForm vf = new vulnerabilityForm(); vf.setReqResp(vuln.reqResp); vf.descriptionField.setText(vuln.getDescription()); vf.URLField.setText(Functions.getURL(vuln.reqResp).toString()); vf.severityField.setText(vuln.severity); vf.cvssField.setText(vuln.cvss); if(vuln.param!=null){ vf.paramField.setText(vuln.param.getName()); vf.paramType_Field.setText(Functions.getParamType(vuln.param.getType())); } vf.setSeverityColor(); vf.setLocationRelativeTo(null); vf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); vf.setSeverityColor(); vf.tabs.setSelectedIndex(0); vf.setVisible(true); } catch (Exception e) { BurpExtender.output.println("*******"+e.toString()); } } } }//GEN-LAST:event_AnalyzerTableMouseClicked private void FalsePositiveButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FalsePositiveButton1ActionPerformed int[]rows=AnalyzerTable.getSelectedRows(); for(int i=0;i<rows.length;i++){ int thisInd=AnalyzerTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table IHttpService serv = vulnerabilityList.get(thisInd).getReqResp().getHttpService(); String tabname=""; tabname=vulnerabilityList.get(thisInd).getCode(); String param=""; if(vulnerabilityList.get(thisInd).param!=null){ param=vulnerabilityList.get(thisInd).param.getName(); if(param.length()>8){ param=param.substring(0,8); } tabname=tabname+"("+param+")"; } BurpExtender.callbacks.sendToRepeater(serv.getHost(),serv.getPort(), (serv.getProtocol().equalsIgnoreCase("HTTPS"))?true:false, vulnerabilityList.get(thisInd).getReqResp().getRequest(),tabname); } updateRowNumbers(); updateAnalyseTabTitle(); }//GEN-LAST:event_FalsePositiveButton1ActionPerformed private void FalsePositiveButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FalsePositiveButton2ActionPerformed int[]rows=AnalyzerTable.getSelectedRows(); for(int i=0;i<rows.length;i++){ int thisInd=AnalyzerTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table IHttpService serv = vulnerabilityList.get(thisInd).getReqResp().getHttpService(); BurpExtender.callbacks.sendToIntruder(serv.getHost(),serv.getPort(), (serv.getProtocol().equalsIgnoreCase("HTTPS"))?true:false, vulnerabilityList.get(thisInd).getReqResp().getRequest()); } updateRowNumbers(); updateAnalyseTabTitle(); }//GEN-LAST:event_FalsePositiveButton2ActionPerformed private void FalsePositiveButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FalsePositiveButton3ActionPerformed int[]rows=AnalyzerTable.getSelectedRows(); for(int i=0;i<rows.length;i++){ int thisInd=AnalyzerTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table URL url = BurpExtender.callbacks.getHelpers().analyzeRequest(vulnerabilityList.get(thisInd).getReqResp()).getUrl(); Functions.openWebpage(url); } }//GEN-LAST:event_FalsePositiveButton3ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables public static javax.swing.JTable AnalyzerTable; private javax.swing.JButton FalsePositiveButton; private javax.swing.JButton FalsePositiveButton1; private javax.swing.JButton FalsePositiveButton2; private javax.swing.JButton FalsePositiveButton3; private javax.swing.JPanel PassiveAbalyzerPanel; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton loadFromHistoryButton; private javax.swing.JButton loadFromSitemap; // End of variables declaration//GEN-END:variables public static void removeAnalyzerTableRow(int i) { BurpExtender.output.println("Row "+i+" removed."); DefaultTableModel AnalyzerModel=(DefaultTableModel)AnalyzerTable.getModel(); AnalyzerModel.removeRow(i); vulnerabilityList.remove(i); Functions.updateRowNumbers(AnalyzerTable); updateAnalyseTabTitle(); } private void initialize() { TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(AnalyzerTable.getModel()); AnalyzerTable.setRowSorter(sorter); } @Override public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) { if(requestIsInScope(messageInfo)){ if(messageIsRequest){ passiveAnalyzerThread pat = new passiveAnalyzerThread(messageInfo, false); //false: do not test response-based tests pat.start(); } else if (!messageIsRequest) { passiveAnalyzerThread pat = new passiveAnalyzerThread(messageInfo, true); //True: test response-based tests pat.start(); } } } public static String getToolName (int toolFlag){ switch (toolFlag){
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 moein.fatehi@gmail.com" */ public class PassiveAnalyzer extends javax.swing.JPanel implements burp.IHttpListener{ private static String extension_name="Analyzer"; private static Scanner sc; public static List<vulnerability> vulnerabilityList=new ArrayList<>(); private static int EAR_avg=400; private static int ConcurrentModificationException=0; public static void AnalyzeRequest(IHttpRequestResponse reqResp,int toolFlag) { if(requestIsInScope(reqResp)){ FindFileUploadInRequest(reqResp, toolFlag); ExtractEncodingsInRequest(reqResp); } } public static void AnalyzeResponse(IHttpRequestResponse reqResp, int toolFlag){ try { if(requestIsInScope(reqResp)){ SendToHeadersTab(reqResp); checkSQLInjection(reqResp); checkReflectedParams(reqResp); extractSensitiveDatas(reqResp); ExtractEncodingsInResponse(reqResp); checkMisconfiguration(reqResp); IResponseInfo respInfo = BurpExtender.callbacks.getHelpers().analyzeResponse(reqResp.getResponse()); int status = respInfo.getStatusCode(); if (status == 200) { checkSensitiveFiles(reqResp, toolFlag); checkLFI(reqResp, toolFlag); checkDirectoryListing(reqResp, toolFlag); } else if (status / 100 == 3) { //3xx checkEAR(reqResp); //Execution after redirection } else if (status / 100 == 4) { //4xx } else if (status / 100 == 5) { //5xx ExtractSensitiveDatasInErrors(reqResp); } } } catch (ConcurrentModificationException e) { // BurpExtender.output.println(new String(reqResp.getRequest())); // BurpExtender.output.println(Functions.getURL(reqResp)); // BurpExtender.output.println(e.toString()); BurpExtender.output.println("ConcurrentModificationException: " + (++ConcurrentModificationException)); //BurpExtender.output.println(e.getMessage()); //BurpExtender.output.println(e.getCause()); //BurpExtender.output.println(e.getCause().toString()); } } private static void FindSerializedInputInRequest(IHttpRequestResponse reqResp) { if(ruleIsEnabledToScan("request", "serialized")){ String code=getRuleCode("request", "serialized"); String req = new String(reqResp.getRequest()); IRequestInfo reqInfo = BurpExtender.callbacks.getHelpers().analyzeRequest(reqResp); String serialize_regex = "[a-z]:[0-9]+:[{\"][^{}]+[\"]+;"; for (IParameter param : reqInfo.getParameters()) { String value_decoded = BurpExtender.callbacks.getHelpers().urlDecode(param.getValue()); if (value_decoded.length() > 7) { if (Functions.findRegex(serialize_regex, value_decoded) != null) { // param includes special chars and is not encoded. vulnerability temp_vuln = new vulnerability(reqResp, param, "High", "-",code, "Serialized data found in input. Try PHP object injection)", false); addToAnalyzerTable(temp_vuln); } } } } } private static void updateAnalyseTabTitle() { PassivePanel.PassiveTabs.setTitleAt(PassivePanel.analyzer_index,"Analyzer ("+vulnerabilityList.size()+")"); // BurpExtender.output.println("Analyzer size: "+vulnerabilityList.size()); } private static void extractSensitiveDatas(IHttpRequestResponse reqResp) { ExtractEmailAddresses(reqResp); ExtractMobileNumbers(reqResp); FingerPrint(reqResp); } private static void ExtractSensitiveDatasInErrors(IHttpRequestResponse reqResp) { if(ruleIsEnabledToScan("response", "sensitive data in errors")){ ExtractSourceCode(reqResp); ExtractLocalPathes(reqResp); } } private static void ExtractSourceCode(IHttpRequestResponse reqResp) { try { String code=getRuleCode("response", "sensitive data"); IResponseInfo respInfo=BurpExtender.callbacks.getHelpers().analyzeResponse(reqResp.getResponse()); String resp = new String(reqResp.getResponse()).substring(respInfo.getBodyOffset()); List<String> regexes = Functions.ReadFile("analyzer_exceptionRegex"); for (String regex : regexes) { List<String> matches = Functions.getAllMatches(regex, resp); for (String match : matches) { vulnerability temp_vuln = new vulnerability(reqResp, null, "Low", "-", code,"Sensitive data disclosure in error ("+match+")", false); addToAnalyzerTable(temp_vuln); } } } catch (IOException ex) { Logger.getLogger(PassiveAnalyzer.class.getName()).log(Level.SEVERE, null, ex); } } private static void ExtractLocalPathes(IHttpRequestResponse reqResp) { String code=getRuleCode("response", "sensitive data"); IResponseInfo respInfo=BurpExtender.callbacks.getHelpers().analyzeResponse(reqResp.getResponse()); String resp = new String(reqResp.getResponse()).substring(respInfo.getBodyOffset()); IRequestInfo reqInfo = BurpExtender.callbacks.getHelpers().analyzeRequest(reqResp); String windows_regex = "([a-z]:\\\\|\\\\\\\\)(\\\\?[a-z_\\-\\s0-9\\.]+\\\\)+([a-z_\\-\\s0-9\\.]+)\\.([a-z_\\-0-9]{2,4})"; String unix_regex = "(?i)\\/((var|opt|home)\\/)([a-z_\\- 0-9\\.]+\\/)+[a-z_\\- 0-9\\.]+(\\.[a-z0-9]{2,5})?"; List<String> matches=Functions.getAllMatches(windows_regex, resp) ; for (String match : matches) { vulnerability temp_vuln = new vulnerability(reqResp, null, "Informational", "-",code,"Local path '"+match+"' found in error", false); addToAnalyzerTable(temp_vuln); } matches=Functions.getAllMatches(unix_regex, resp) ; for (String match : matches) { vulnerability temp_vuln = new vulnerability(reqResp, null,code,"Informational", "-", "Unix-based local path '"+match+"' found in error", false); addToAnalyzerTable(temp_vuln); } } private static void FingerPrint(IHttpRequestResponse reqResp) { if(ruleIsEnabledToScan("response", "fingerprint")){ String code=getRuleCode("response", "fingerprint"); IResponseInfo respInfo=BurpExtender.callbacks.getHelpers().analyzeResponse(reqResp.getResponse()); for(String header:respInfo.getHeaders()){ if(header.startsWith("Server:")){ vulnerability temp_vuln = new vulnerability(reqResp, null, "Informational", "-", code,"Server name '" + getHeaderValue(header) + "' extracted from "+getHeaderName(header)+" header", true); addToAnalyzerTable(temp_vuln); } if(header.startsWith("X-Powered-By:")){ vulnerability temp_vuln = new vulnerability(reqResp, null, "Informational", "-", code,"Web application framework '" + getHeaderValue(header) + "' extracted from "+getHeaderName(header)+" header", true); addToAnalyzerTable(temp_vuln); } if (header.startsWith("X-AspNet-Version:")) { vulnerability temp_vuln = new vulnerability(reqResp, null, "Informational", "-", code,"ASP.net version '" + getHeaderValue(header) + "' extracted from "+getHeaderName(header)+" header", true); addToAnalyzerTable(temp_vuln); } } } } private static void CheckCookieFlags(IHttpRequestResponse reqResp) { if(ruleIsEnabledToScan("response", "cookie flags")){ String code=getRuleCode("response", "cookie flags"); IResponseInfo respInfo=BurpExtender.callbacks.getHelpers().analyzeResponse(reqResp.getResponse()); for(String header:respInfo.getHeaders()){ if(header.startsWith("Set-Cookie:")){ String newCookie=getHeaderValue(header); if(!newCookie.contains("HttpOnly")){ vulnerability temp_vuln = new vulnerability(reqResp, null, "Low", "-", code,"Cookie '" + newCookie.substring(0,newCookie.indexOf("="))+ "' is without HttpOnly flag set.", true); addToAnalyzerTable(temp_vuln); } if(!newCookie.contains("Secure")){ if(reqResp.getHttpService().getProtocol().equalsIgnoreCase("https")){ vulnerability temp_vuln = new vulnerability(reqResp, null, "Low", "-", code,"Cookie '" + newCookie.substring(0,newCookie.indexOf("="))+ "' is without Secure flag set in HTTPS mode.", true); addToAnalyzerTable(temp_vuln); } } } } } } private static String getHeaderName(String header) { Scanner sc=new Scanner(header); sc.useDelimiter(":"); return sc.next(); } private static String getHeaderValue(String header) { Scanner sc=new Scanner(header); sc.useDelimiter(":"); try { sc.next(); String value = sc.next(); if (value.startsWith(" ")) { value = value.substring(1); } return value; } catch (Exception e) { return ""; } } private static void checkMisconfiguration(IHttpRequestResponse reqResp) { CheckCookieFlags(reqResp); } private static void ExtractEncodingsInRequest(IHttpRequestResponse reqResp) { FindSerializedInputInRequest(reqResp); FindBase64InRequest(reqResp); } private static void FindBase64InRequest(IHttpRequestResponse reqResp) { if(ruleIsEnabledToScan("request", "base64")){ String code=getRuleCode("response", "cookie flags"); String req = BurpExtender.callbacks.getHelpers().urlDecode(new String(reqResp.getRequest())); IRequestInfo reqInfo = BurpExtender.callbacks.getHelpers().analyzeRequest(reqResp); String base64_regex = "[A-Za-z0-9+]{4}(?:[A-Za-z0-9+\\/]{4}){2,}(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?"; for (IParameter parameter : reqInfo.getParameters()) { try { String b64 = Functions.findRegex(base64_regex, parameter.getValue()); if (b64 != null) { if (!Functions.base64Decode(b64).equals(b64) && !Functions.base64Decode(b64).equals("encrypted_Base64")) { vulnerability temp_vuln = new vulnerability(reqResp, parameter, "Informational", "-", code,"Base64 encoded data in request, decoded to: '" + Functions.base64Decode(b64) + "' (" + parameter.getName() + " " + Functions.getParamType(parameter.getType()) + " parameter)", true); addToAnalyzerTable(temp_vuln); } } } catch (Exception e) { // BurpExtender.output.println("****1"); } } for (String header : reqInfo.getHeaders()) { try { List<String> matches = Functions.getAllMatches(base64_regex, getHeaderValue(header)); for (String match : matches) { if (!Functions.base64Decode(match).equals(match) && !Functions.base64Decode(match).equals("encrypted_Base64")) { vulnerability temp_vuln = new vulnerability(reqResp, null, "Informational", "-", code,"Base64 encoded data in request, decoded to: '" + Functions.base64Decode(match) + "' (" + getHeaderName(header) + " header)", true); addToAnalyzerTable(temp_vuln); } } } catch (Exception e) { BurpExtender.output.println(e.toString()); } } List<String> matches=Functions.getAllMatches(base64_regex, req) ; for (String match : matches) { if(!Functions.base64Decode(match).equals(match)&&!Functions.base64Decode(match).equals("encrypted_Base64")){ vulnerability temp_vuln = new vulnerability(reqResp, null, "Informational", "-", code,"Base64 encoded data in request, decoded to: '" + Functions.base64Decode(match) + "'", true); addToAnalyzerTable(temp_vuln); } } } } private static void ExtractEncodingsInResponse(IHttpRequestResponse reqResp) { FindBase64InResponse(reqResp); } private static void FindBase64InResponse(IHttpRequestResponse reqResp) { if(ruleIsEnabledToScan("response", "base64")){ String code=getRuleCode("response", "base64"); IResponseInfo respInfo=BurpExtender.callbacks.getHelpers().analyzeResponse(reqResp.getResponse()); String resp = BurpExtender.callbacks.getHelpers().urlDecode(new String(reqResp.getResponse())); String base64_regex = "[A-Za-z0-9+]{4}(?:[A-Za-z0-9+\\/]{4}){2,}(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?"; List<String> matches=Functions.getAllMatches(base64_regex, resp) ; for (String match : matches) { if(!Functions.base64Decode(match).equals(match)&&!Functions.base64Decode(match).equals("encrypted_Base64")){ vulnerability temp_vuln = new vulnerability(reqResp, null, "Informational", "-", code,"Base64 encoded data in response, decoded to: '" + Functions.base64Decode(match) + "'", true); addToAnalyzerTable(temp_vuln); } } } } private static void SendToHeadersTab(IHttpRequestResponse reqResp) { Passive_Headers.addToHeadersTable(reqResp); } private static boolean ruleIsEnabledToScan(String reqOrResp, String rule) { switch (reqOrResp){ case "request": for (int i = 0; i < Passive_optionsPanel.options_request_table.getRowCount(); i++) { if(Passive_optionsPanel.options_request_table.getValueAt(i, 2).toString().toLowerCase().contains(rule)){ return getRuleStatus(Passive_optionsPanel.options_request_table, i); // try { // When it is not enabled, it returns exception. // return (boolean)Passive_optionsPanel.options_request_table.getValueAt(i, 0); // } catch (Exception e) { // return false; // } } } return false; case "response": for (int i = 0; i < Passive_optionsPanel.options_response_table.getRowCount(); i++) { if(Passive_optionsPanel.options_response_table.getValueAt(i, 2).toString().toLowerCase().contains(rule)){ return getRuleStatus(Passive_optionsPanel.options_response_table, i); // try { // When it is not enabled, it returns null! (ty to enable and disable in netbeans GUI (in table contents part). // return (boolean)Passive_optionsPanel.options_response_table.getValueAt(i, 0); // } catch (Exception e) { // return false; // } } } return false; } return false; } private static String getRuleCode(String reqOrResp, String rule) { switch (reqOrResp){ case "request": for (int i = 0; i < Passive_optionsPanel.options_request_table.getRowCount(); i++) { if(Passive_optionsPanel.options_request_table.getValueAt(i, 2).toString().toLowerCase().contains(rule)){ return Passive_optionsPanel.options_request_table.getValueAt(i, 1).toString(); } } case "response": for (int i = 0; i < Passive_optionsPanel.options_response_table.getRowCount(); i++) { if(Passive_optionsPanel.options_response_table.getValueAt(i, 2).toString().toLowerCase().contains(rule)){ return Passive_optionsPanel.options_response_table.getValueAt(i, 1).toString(); } } } return null; } public static boolean getRuleStatus(JTable table,int row) { if((boolean)table.getValueAt(row, 0)==true){ return true; } // When it is not enabled, it returns null! (ty to enable and disable in netbeans GUI (in table contents part) return false; } /** * Creates new form HeadersPanel */ public PassiveAnalyzer() { initComponents(); initialize(); } /** * 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() { PassiveAbalyzerPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); AnalyzerTable = new javax.swing.JTable(); loadFromHistoryButton = new javax.swing.JButton(); FalsePositiveButton = new javax.swing.JButton(); loadFromSitemap = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); FalsePositiveButton1 = new javax.swing.JButton(); FalsePositiveButton2 = new javax.swing.JButton(); FalsePositiveButton3 = new javax.swing.JButton(); AnalyzerTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "Severity", "URL", "Parameter", "Type", "Code", "Description" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); AnalyzerTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { AnalyzerTableMouseClicked(evt); } }); jScrollPane1.setViewportView(AnalyzerTable); if (AnalyzerTable.getColumnModel().getColumnCount() > 0) { AnalyzerTable.getColumnModel().getColumn(0).setPreferredWidth(40); AnalyzerTable.getColumnModel().getColumn(0).setMaxWidth(60); AnalyzerTable.getColumnModel().getColumn(1).setPreferredWidth(100); AnalyzerTable.getColumnModel().getColumn(1).setMaxWidth(150); AnalyzerTable.getColumnModel().getColumn(2).setPreferredWidth(200); AnalyzerTable.getColumnModel().getColumn(2).setMaxWidth(400); AnalyzerTable.getColumnModel().getColumn(3).setPreferredWidth(100); AnalyzerTable.getColumnModel().getColumn(3).setMaxWidth(200); AnalyzerTable.getColumnModel().getColumn(4).setPreferredWidth(70); AnalyzerTable.getColumnModel().getColumn(4).setMaxWidth(100); AnalyzerTable.getColumnModel().getColumn(5).setPreferredWidth(70); AnalyzerTable.getColumnModel().getColumn(5).setMaxWidth(80); AnalyzerTable.getColumnModel().getColumn(6).setPreferredWidth(300); } loadFromHistoryButton.setText("Load From History"); loadFromHistoryButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromHistoryButtonActionPerformed(evt); } }); FalsePositiveButton.setText("False positive"); FalsePositiveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { FalsePositiveButtonActionPerformed(evt); } }); loadFromSitemap.setText("Load From Sitemap"); loadFromSitemap.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadFromSitemapActionPerformed(evt); } }); jLabel2.setText("(Double click for details)"); FalsePositiveButton1.setText("-> Repeater"); FalsePositiveButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { FalsePositiveButton1ActionPerformed(evt); } }); FalsePositiveButton2.setText("-> Intruder"); FalsePositiveButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { FalsePositiveButton2ActionPerformed(evt); } }); FalsePositiveButton3.setText("Open"); FalsePositiveButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { FalsePositiveButton3ActionPerformed(evt); } }); javax.swing.GroupLayout PassiveAbalyzerPanelLayout = new javax.swing.GroupLayout(PassiveAbalyzerPanel); PassiveAbalyzerPanel.setLayout(PassiveAbalyzerPanelLayout); PassiveAbalyzerPanelLayout.setHorizontalGroup( PassiveAbalyzerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PassiveAbalyzerPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(PassiveAbalyzerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PassiveAbalyzerPanelLayout.createSequentialGroup() .addComponent(loadFromHistoryButton, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(loadFromSitemap, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(PassiveAbalyzerPanelLayout.createSequentialGroup() .addGroup(PassiveAbalyzerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(FalsePositiveButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(FalsePositiveButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(FalsePositiveButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(FalsePositiveButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 583, Short.MAX_VALUE))) .addContainerGap()) ); PassiveAbalyzerPanelLayout.setVerticalGroup( PassiveAbalyzerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PassiveAbalyzerPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(PassiveAbalyzerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(loadFromHistoryButton) .addComponent(loadFromSitemap) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(PassiveAbalyzerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PassiveAbalyzerPanelLayout.createSequentialGroup() .addComponent(FalsePositiveButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(FalsePositiveButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(FalsePositiveButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(FalsePositiveButton2) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane1)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(PassiveAbalyzerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(PassiveAbalyzerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void loadFromSitemapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadFromSitemapActionPerformed if(Passive_optionsPanel.targetIsLoaded()){ for (IHttpRequestResponse rr : Passive_optionsPanel.getBaseReqRespList()) { IHttpService serv=rr.getHttpService(); String prefix=serv.getProtocol()+"://"+serv.getHost(); if(serv.getPort()!=80){ prefix+=":"+serv.getPort(); } AnalyzeManyRequests(BurpExtender.callbacks.getSiteMap(prefix)); } } }//GEN-LAST:event_loadFromSitemapActionPerformed private void FalsePositiveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FalsePositiveButtonActionPerformed int[]rows=AnalyzerTable.getSelectedRows(); for(int i=rows.length-1;i>=0;i--){ int thisInd=AnalyzerTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table removeAnalyzerTableRow(thisInd); } updateRowNumbers(); updateAnalyseTabTitle(); }//GEN-LAST:event_FalsePositiveButtonActionPerformed private void loadFromHistoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadFromHistoryButtonActionPerformed if(Passive_optionsPanel.targetIsLoaded()){ AnalyzeManyRequests(BurpExtender.callbacks.getProxyHistory()); } }//GEN-LAST:event_loadFromHistoryButtonActionPerformed private void AnalyzerTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalyzerTableMouseClicked if(evt.getClickCount()==2){ int index=AnalyzerTable.getSelectedRow(); int ind=(int)AnalyzerTable.getValueAt(index, 0)-1; if(vulnerabilityList.get(ind)!=null){ try { vulnerability vuln = vulnerabilityList.get(ind); vulnerabilityForm.setReqResp(vuln.reqResp); vulnerabilityForm vf = new vulnerabilityForm(); vf.setReqResp(vuln.reqResp); vf.descriptionField.setText(vuln.getDescription()); vf.URLField.setText(Functions.getURL(vuln.reqResp).toString()); vf.severityField.setText(vuln.severity); vf.cvssField.setText(vuln.cvss); if(vuln.param!=null){ vf.paramField.setText(vuln.param.getName()); vf.paramType_Field.setText(Functions.getParamType(vuln.param.getType())); } vf.setSeverityColor(); vf.setLocationRelativeTo(null); vf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); vf.setSeverityColor(); vf.tabs.setSelectedIndex(0); vf.setVisible(true); } catch (Exception e) { BurpExtender.output.println("*******"+e.toString()); } } } }//GEN-LAST:event_AnalyzerTableMouseClicked private void FalsePositiveButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FalsePositiveButton1ActionPerformed int[]rows=AnalyzerTable.getSelectedRows(); for(int i=0;i<rows.length;i++){ int thisInd=AnalyzerTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table IHttpService serv = vulnerabilityList.get(thisInd).getReqResp().getHttpService(); String tabname=""; tabname=vulnerabilityList.get(thisInd).getCode(); String param=""; if(vulnerabilityList.get(thisInd).param!=null){ param=vulnerabilityList.get(thisInd).param.getName(); if(param.length()>8){ param=param.substring(0,8); } tabname=tabname+"("+param+")"; } BurpExtender.callbacks.sendToRepeater(serv.getHost(),serv.getPort(), (serv.getProtocol().equalsIgnoreCase("HTTPS"))?true:false, vulnerabilityList.get(thisInd).getReqResp().getRequest(),tabname); } updateRowNumbers(); updateAnalyseTabTitle(); }//GEN-LAST:event_FalsePositiveButton1ActionPerformed private void FalsePositiveButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FalsePositiveButton2ActionPerformed int[]rows=AnalyzerTable.getSelectedRows(); for(int i=0;i<rows.length;i++){ int thisInd=AnalyzerTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table IHttpService serv = vulnerabilityList.get(thisInd).getReqResp().getHttpService(); BurpExtender.callbacks.sendToIntruder(serv.getHost(),serv.getPort(), (serv.getProtocol().equalsIgnoreCase("HTTPS"))?true:false, vulnerabilityList.get(thisInd).getReqResp().getRequest()); } updateRowNumbers(); updateAnalyseTabTitle(); }//GEN-LAST:event_FalsePositiveButton2ActionPerformed private void FalsePositiveButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FalsePositiveButton3ActionPerformed int[]rows=AnalyzerTable.getSelectedRows(); for(int i=0;i<rows.length;i++){ int thisInd=AnalyzerTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table URL url = BurpExtender.callbacks.getHelpers().analyzeRequest(vulnerabilityList.get(thisInd).getReqResp()).getUrl(); Functions.openWebpage(url); } }//GEN-LAST:event_FalsePositiveButton3ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables public static javax.swing.JTable AnalyzerTable; private javax.swing.JButton FalsePositiveButton; private javax.swing.JButton FalsePositiveButton1; private javax.swing.JButton FalsePositiveButton2; private javax.swing.JButton FalsePositiveButton3; private javax.swing.JPanel PassiveAbalyzerPanel; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton loadFromHistoryButton; private javax.swing.JButton loadFromSitemap; // End of variables declaration//GEN-END:variables public static void removeAnalyzerTableRow(int i) { BurpExtender.output.println("Row "+i+" removed."); DefaultTableModel AnalyzerModel=(DefaultTableModel)AnalyzerTable.getModel(); AnalyzerModel.removeRow(i); vulnerabilityList.remove(i); Functions.updateRowNumbers(AnalyzerTable); updateAnalyseTabTitle(); } private void initialize() { TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(AnalyzerTable.getModel()); AnalyzerTable.setRowSorter(sorter); } @Override public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) { if(requestIsInScope(messageInfo)){ if(messageIsRequest){ passiveAnalyzerThread pat = new passiveAnalyzerThread(messageInfo, false); //false: do not test response-based tests pat.start(); } else if (!messageIsRequest) { passiveAnalyzerThread pat = new passiveAnalyzerThread(messageInfo, true); //True: test response-based tests pat.start(); } } } public static String getToolName (int toolFlag){ switch (toolFlag){
case IBurpExtenderCallbacks.TOOL_TARGET:
1
2023-10-23 12:13:00+00:00
24k
RoessinghResearch/senseeact
SenSeeActService/src/main/java/nl/rrd/senseeact/service/DatabaseLoader.java
[ { "identifier": "PerformanceStatTable", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/PerformanceStatTable.java", "snippet": "public class PerformanceStatTable extends DatabaseTableDef<PerformanceStat> {\n\tpublic static final String NAME = \"performance_stats\";\n\t\n\tprivate st...
import nl.rrd.senseeact.client.model.PerformanceStatTable; import nl.rrd.senseeact.client.model.Role; import nl.rrd.senseeact.client.model.SystemStatTable; import nl.rrd.senseeact.client.project.BaseProject; import nl.rrd.senseeact.client.project.ProjectRepository; import nl.rrd.senseeact.dao.*; import nl.rrd.senseeact.dao.listener.DatabaseActionListener; import nl.rrd.senseeact.dao.listener.DatabaseListenerRepository; import nl.rrd.senseeact.service.access.ProjectUserAccessControl; import nl.rrd.senseeact.service.access.ProjectUserAccessControlRepository; import nl.rrd.senseeact.service.controller.AuthControllerExecution; import nl.rrd.senseeact.service.exception.HttpException; import nl.rrd.senseeact.service.model.UserTable; import nl.rrd.senseeact.service.model.*; import nl.rrd.utils.AppComponents; import nl.rrd.utils.ReferenceParameter; import nl.rrd.utils.datetime.DateTimeUtils; import nl.rrd.utils.exception.DatabaseException; import nl.rrd.utils.schedule.AbstractScheduledTask; import nl.rrd.utils.schedule.ScheduleParams; import nl.rrd.utils.schedule.TaskSchedule; import nl.rrd.utils.schedule.TaskScheduler; import org.slf4j.Logger; import java.io.IOException; import java.time.ZonedDateTime; import java.util.*;
16,072
if (closed) throw new IOException("DatabaseLoader closed"); OpenDatabaseConnection openConn = findMatchingOpenConnection(); if (openConn != null) { CloseListenDatabaseConnection conn = new CloseListenDatabaseConnection(openConn); openConn.dbConns.add(conn); logger.trace("Reuse simultaneously created new database connection"); return conn; } openConn = new OpenDatabaseConnection(); openConn.baseConn = baseConn; openConn.openTime = System.currentTimeMillis(); CloseListenDatabaseConnection conn = new CloseListenDatabaseConnection(openConn); openConn.dbConns.add(conn); openConns.add(openConn); saved = true; logger.trace("Saved new database connection"); return conn; } } finally { if (!saved) { baseConn.close(); logger.trace("Closed unsaved database connection"); } } } /** * Closes this database loader and any open database connections. */ public void close() { synchronized (INSTANCE_LOCK) { if (closed) return; closed = true; TaskScheduler scheduler = AppComponents.get(TaskScheduler.class); scheduler.cancelTask(null, cleanTaskId); for (OpenDatabaseConnection openConn : openConns) { openConn.baseConn.close(); } openConns.clear(); Logger logger = AppComponents.getLogger(getClass().getSimpleName()); logger.info("Closed database loader and connections"); } } /** * Returns the authentication database. It will create, initialise or * upgrade the database if needed. If no user exists, it will create the * admin user. You should not call any queries that change the database * structure. * * @param conn the database connection * @return the database * @throws DatabaseException if a database error occurs */ public Database initAuthDatabase(DatabaseConnection conn) throws DatabaseException { synchronized (AUTH_DB_LOCK) { List<DatabaseTableDef<?>> tableDefs = getAuthDbTables(); Configuration config = AppComponents.get(Configuration.class); String dbNamePrefix = config.get(Configuration.DB_NAME_PREFIX); Database db = conn.initDatabase(dbNamePrefix + "_auth", tableDefs, true); db.setSyncEnabled(false); UserCache userCache = UserCache.createInstance(db); int count = userCache.getCount(); if (count == 0) createInitialAuthData(db); return db; } } public static List<DatabaseTableDef<?>> getAuthDbTables() { List<DatabaseTableDef<?>> result = new ArrayList<>(); result.add(new UserTable()); result.add(new GroupTable()); result.add(new UserProjectTable()); result.add(new GroupMemberTable()); result.add(new PermissionTable()); result.add(new ProjectUserAccessTable()); result.add(new UserActiveChangeTable()); result.add(new SyncPushRegistrationTable()); result.add(new WatchSubjectRegistrationTable()); result.add(new WatchTableRegistrationTable()); result.add(new MobileWakeRequestTable()); result.add(new DataExportTable()); result.add(new SystemStatTable()); result.add(new PerformanceStatTable()); OAuthTableRepository oauthRepo = AppComponents.get( OAuthTableRepository.class); result.addAll(oauthRepo.getOAuthTables()); ProjectUserAccessControlRepository uacRepo = AppComponents.get( ProjectUserAccessControlRepository.class); Map<String,ProjectUserAccessControl> projectAccessControlMap = uacRepo.getProjectMap(); for (String project : projectAccessControlMap.keySet()) { ProjectUserAccessControl projectAccessControl = projectAccessControlMap.get(project); result.addAll(projectAccessControl.getTables()); } return result; } /** * This method is called on the authentication database if it doesn't have * any users. It will create the admin user. * * @param db the authentication database * @throws DatabaseException if a database error occurs */ private void createInitialAuthData(Database db) throws DatabaseException { Configuration config = AppComponents.get(Configuration.class); User user = new User(); user.setUserid(UUID.randomUUID().toString().toLowerCase() .replaceAll("-", "")); user.setEmail(config.get(Configuration.ADMIN_EMAIL)); try {
package nl.rrd.senseeact.service; /** * Utility class to load the authentication database and project databases. * This is thread-safe. * * @author Dennis Hofs (RRD) */ public class DatabaseLoader { private static final int MIN_KEEP_OPEN_DURATION = 300000; // milliseconds private static final int MAX_KEEP_OPEN_DURATION = 600000; // milliseconds private static final int CLEAN_INTERVAL = 60000; // milliseconds private final Object AUTH_DB_LOCK = new Object(); private final Map<String,Object> PROJECT_DB_LOCKS = new LinkedHashMap<>(); private final List<String> listeningDatabases = new ArrayList<>(); private List<OpenDatabaseConnection> openConns = new ArrayList<>(); private static final Object INSTANCE_LOCK = new Object(); private static DatabaseLoader instance = null; private boolean closed = false; private String cleanTaskId; private DatabaseLoader() { TaskScheduler scheduler = AppComponents.get(TaskScheduler.class); cleanTaskId = scheduler.generateTaskId(); scheduler.scheduleTask(null, new CleanConnectionsTask(), cleanTaskId); } public static DatabaseLoader getInstance() { synchronized (INSTANCE_LOCK) { if (instance == null) instance = new DatabaseLoader(); return instance; } } /** * Opens a connection to the database server. It enables action logging * for synchronisation with a remote database. When you have completed the * database operations, you should close the connection. * * @return the database connection * @throws IOException if the connection could not be opened */ public DatabaseConnection openConnection() throws IOException { Logger logger = AppComponents.getLogger(getClass().getSimpleName()); synchronized (INSTANCE_LOCK) { if (closed) throw new IOException("DatabaseLoader closed"); OpenDatabaseConnection openConn = findMatchingOpenConnection(); if (openConn != null) { CloseListenDatabaseConnection conn = new CloseListenDatabaseConnection(openConn); openConn.dbConns.add(conn); logger.trace("Reuse database connection"); return conn; } } DatabaseFactory dbFactory = AppComponents.getInstance() .getComponent(DatabaseFactory.class); boolean saved = false; DatabaseConnection baseConn = dbFactory.connect(); logger.trace("Created new database connection"); try { baseConn.setSyncEnabled(true); synchronized (INSTANCE_LOCK) { if (closed) throw new IOException("DatabaseLoader closed"); OpenDatabaseConnection openConn = findMatchingOpenConnection(); if (openConn != null) { CloseListenDatabaseConnection conn = new CloseListenDatabaseConnection(openConn); openConn.dbConns.add(conn); logger.trace("Reuse simultaneously created new database connection"); return conn; } openConn = new OpenDatabaseConnection(); openConn.baseConn = baseConn; openConn.openTime = System.currentTimeMillis(); CloseListenDatabaseConnection conn = new CloseListenDatabaseConnection(openConn); openConn.dbConns.add(conn); openConns.add(openConn); saved = true; logger.trace("Saved new database connection"); return conn; } } finally { if (!saved) { baseConn.close(); logger.trace("Closed unsaved database connection"); } } } /** * Closes this database loader and any open database connections. */ public void close() { synchronized (INSTANCE_LOCK) { if (closed) return; closed = true; TaskScheduler scheduler = AppComponents.get(TaskScheduler.class); scheduler.cancelTask(null, cleanTaskId); for (OpenDatabaseConnection openConn : openConns) { openConn.baseConn.close(); } openConns.clear(); Logger logger = AppComponents.getLogger(getClass().getSimpleName()); logger.info("Closed database loader and connections"); } } /** * Returns the authentication database. It will create, initialise or * upgrade the database if needed. If no user exists, it will create the * admin user. You should not call any queries that change the database * structure. * * @param conn the database connection * @return the database * @throws DatabaseException if a database error occurs */ public Database initAuthDatabase(DatabaseConnection conn) throws DatabaseException { synchronized (AUTH_DB_LOCK) { List<DatabaseTableDef<?>> tableDefs = getAuthDbTables(); Configuration config = AppComponents.get(Configuration.class); String dbNamePrefix = config.get(Configuration.DB_NAME_PREFIX); Database db = conn.initDatabase(dbNamePrefix + "_auth", tableDefs, true); db.setSyncEnabled(false); UserCache userCache = UserCache.createInstance(db); int count = userCache.getCount(); if (count == 0) createInitialAuthData(db); return db; } } public static List<DatabaseTableDef<?>> getAuthDbTables() { List<DatabaseTableDef<?>> result = new ArrayList<>(); result.add(new UserTable()); result.add(new GroupTable()); result.add(new UserProjectTable()); result.add(new GroupMemberTable()); result.add(new PermissionTable()); result.add(new ProjectUserAccessTable()); result.add(new UserActiveChangeTable()); result.add(new SyncPushRegistrationTable()); result.add(new WatchSubjectRegistrationTable()); result.add(new WatchTableRegistrationTable()); result.add(new MobileWakeRequestTable()); result.add(new DataExportTable()); result.add(new SystemStatTable()); result.add(new PerformanceStatTable()); OAuthTableRepository oauthRepo = AppComponents.get( OAuthTableRepository.class); result.addAll(oauthRepo.getOAuthTables()); ProjectUserAccessControlRepository uacRepo = AppComponents.get( ProjectUserAccessControlRepository.class); Map<String,ProjectUserAccessControl> projectAccessControlMap = uacRepo.getProjectMap(); for (String project : projectAccessControlMap.keySet()) { ProjectUserAccessControl projectAccessControl = projectAccessControlMap.get(project); result.addAll(projectAccessControl.getTables()); } return result; } /** * This method is called on the authentication database if it doesn't have * any users. It will create the admin user. * * @param db the authentication database * @throws DatabaseException if a database error occurs */ private void createInitialAuthData(Database db) throws DatabaseException { Configuration config = AppComponents.get(Configuration.class); User user = new User(); user.setUserid(UUID.randomUUID().toString().toLowerCase() .replaceAll("-", "")); user.setEmail(config.get(Configuration.ADMIN_EMAIL)); try {
AuthControllerExecution.setPassword(user,
9
2023-10-24 09:36:50+00:00
24k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/commons/entities/EntityServiceImpl.java
[ { "identifier": "Displayable", "path": "src/main/java/org/msh/etbm/commons/Displayable.java", "snippet": "@FunctionalInterface\npublic interface Displayable {\n\n /**\n * The displayable representation of the object\n *\n * @return\n */\n String getDisplayString();\n}" }, { ...
import org.apache.commons.lang3.StringUtils; import org.hibernate.Hibernate; import org.msh.etbm.commons.Displayable; import org.msh.etbm.commons.Messages; import org.msh.etbm.commons.commands.CommandLog; import org.msh.etbm.commons.commands.CommandType; import org.msh.etbm.commons.commands.CommandTypes; import org.msh.etbm.commons.entities.cmdlog.EntityCmdLogHandler; import org.msh.etbm.commons.entities.cmdlog.Operation; import org.msh.etbm.commons.entities.cmdlog.PropertyLogUtils; import org.msh.etbm.commons.entities.dao.EntityDAO; import org.msh.etbm.commons.entities.dao.EntityDAOFactory; import org.msh.etbm.commons.entities.query.EntityQueryParams; import org.msh.etbm.commons.entities.query.QueryBuilder; import org.msh.etbm.commons.entities.query.QueryBuilderFactory; import org.msh.etbm.commons.entities.query.QueryResult; import org.msh.etbm.commons.objutils.Diffs; import org.msh.etbm.commons.objutils.DiffsUtils; import org.msh.etbm.commons.objutils.ObjectUtils; import org.msh.etbm.commons.objutils.ObjectValues; import org.msh.etbm.db.Synchronizable; import org.msh.etbm.db.WorkspaceEntity; import org.msh.etbm.services.session.usersession.UserRequestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; import java.util.UUID;
20,080
* @return */ protected Diffs createDiffs(ObjectValues prevVals, ObjectValues newVals) { return DiffsUtils.generateDiffsFromValues(prevVals, newVals); } /** * Return the current workspace ID * * @return instance of UUID */ protected UUID getWorkspaceId() { return userRequestService.getUserSession().getWorkspaceId(); } /** * Create the result to be returned by the create, update or delete operation * * @param entity the entity involved in the operation * @return instance of {@link ServiceResult} */ protected ServiceResult createResult(E entity) { ServiceResult res = new ServiceResult(); res.setId(entity.getId()); res.setEntityClass(getEntityClass()); String cmdPath = getCommandType(); res.setCommandType(CommandTypes.get(cmdPath)); if (entity instanceof Displayable) { res.setEntityName(((Displayable) entity).getDisplayString()); } else { res.setEntityName(entity.toString()); } return res; } /** * Return the entity by its given id * * @param id the entity primary key * @return entity object */ protected E findEntity(Object id) { try { return entityManager.find(getEntityClass(), id); } catch (EntityNotFoundException e) { return null; } } /** * Create a binding result to store validation error messages * * @param entity the entity assgined to the binding result * @return instance of {@link BindingResult} */ protected BindingResult createBindingResult(Object entity) { return new BeanPropertyBindingResult(entity, getEntityClass().getSimpleName()); } /** * Raise exception of a required field not present * * @param obj the object related to the exception * @param field the name of the field */ protected void raiseRequiredFieldException(Object obj, String field) { rejectFieldException(obj, field, Messages.REQUIRED); } /** * Raise a validation error exception. The exception is thrown immediately and there will be * just one field assigned to it * * @param obj the object related to the validation error * @param field the field with an error * @param msg the message with the validation error */ protected void rejectFieldException(Object obj, String field, String msg) { BindingResult res = createBindingResult(obj); res.rejectValue(field, msg); throw new EntityValidationException(res); } /** * Return the class of the entity being managed * * @return */ protected Class<E> getEntityClass() { if (entityClass == null) { entityClass = ObjectUtils.getGenericType(getClass(), 0); if (entityClass == null) { throw new RuntimeException("Could not get entity class"); } } return entityClass; } /** * Create a new instance of the entity class * * @param req the object used as request for this service * @return */ protected E createEntityInstance(Object req) { Class<E> clazz = getEntityClass(); return ObjectUtils.newInstance(clazz); } @Override public QueryResult findMany(Q qryParams) {
package org.msh.etbm.commons.entities; /** * Abstract class to provide a complete CRUD solution for entity services. * <p> * Created by rmemoria on 17/10/15. */ public abstract class EntityServiceImpl<E extends Synchronizable, Q extends EntityQueryParams> implements EntityService<Q> { @Autowired protected UserRequestService userRequestService; @PersistenceContext EntityManager entityManager; @Autowired QueryBuilderFactory queryBuilderFactory; @Autowired EntityDAOFactory entityDAOFactory; @Autowired protected ApplicationContext applicationContext; /** * The entity class */ private Class<E> entityClass; /** * Return the command type used to register the entity service * @return instance of the {@link CommandType} */ public abstract String getCommandType(); /** * Create a new entity based on the given request object. The request object depends on the implementation * and contains the values to create a new entity * * @param req list of all values in the format field x value * @return service result containing information about the new entity generated */ @Transactional @CommandLog(type = CommandTypes.CMD_CREATE, handler = EntityCmdLogHandler.class) @Override public ServiceResult create(@Valid @NotNull Object req) { // create a new instance of the entity E entity = createEntityInstance(req); EntityDAO<E> dao = createEntityDAO(); dao.setEntity(entity); EntityServiceContext<E> context = createContext(null, entity, req); // set values from request to entity object (must ignore null values) mapRequest(context); validateAndSave(context, dao); // create the result of the service ServiceResult res = createResult(entity); res.setLogValues(createValuesToLog(entity, Operation.NEW)); res.setOperation(Operation.NEW); afterSave(context, res); applicationContext.publishEvent(new EntityServiceEvent(this, res)); return res; } /** * Update the values of the entity * * @param id the entity ID * @param req the object request with information about fields to be updated * @return */ @Transactional @CommandLog(type = CommandTypes.CMD_UPDATE, handler = EntityCmdLogHandler.class) @Override public ServiceResult update(UUID id, Object req) { EntityDAO<E> dao = createEntityDAO(); dao.setId(id); // get initial state ObjectValues prevVals = createValuesToLog(dao.getEntity(), Operation.EDIT); EntityServiceContext<E> context = createContext(id, dao.getEntity(), req); // set the values to the entity mapRequest(context); // create diff list ObjectValues newVals = createValuesToLog(dao.getEntity(), Operation.EDIT); Diffs diffs = createDiffs(prevVals, newVals); // is there anything to save? if (diffs.getValues().isEmpty()) { return createResult(dao.getEntity()); } validateAndSave(context, dao); // create result object ServiceResult res = createResult(dao.getEntity()); // generate the result res.setLogDiffs(diffs); res.setOperation(Operation.EDIT); afterSave(context, res); applicationContext.publishEvent(new EntityServiceEvent(this, res)); return res; } @Transactional @CommandLog(type = CommandTypes.CMD_DELETE, handler = EntityCmdLogHandler.class) @Override public ServiceResult delete(UUID id) { EntityDAO<E> dao = createEntityDAO(); dao.setId(id); // create result to be sent back to the client ServiceResult res = createResult(dao.getEntity()); EntityServiceContext<E> context = createContext(id, dao.getEntity(), null); // prepare entity to be deleted beforeDelete(context, dao.getErrors()); // check if there is any error if (dao.hasErrors()) { dao.raiseValidationError(); } // generate the values to log res.setLogValues(createValuesToLog(dao.getEntity(), Operation.DELETE)); // delete the entity dao.delete(); res.setOperation(Operation.DELETE); afterDelete(context, res); applicationContext.publishEvent(new EntityServiceEvent(this, res)); return res; } /** * Check if the given entity is unique by searching by the given field * * @param entity the entity to check unique values * @param field the field (or comma separated list of fields) to check uniqueness * @return true if the entity is unique */ protected boolean checkUnique(E entity, String field) { return checkUnique(entity, field, null); } /** * Check if a given entity for a given class is unique. THis is a generic way of checking unique entities * that are not related to the entity class of this service * * @param entityClass The entity class to check from * @param entity The entity to evaluate the values * @param field The field to check uniqueness * @param restriction Any optional restriction to the method * @return true if entity is unique */ protected boolean checkUnique(Class<? extends Synchronizable> entityClass, Synchronizable entity, String field, String restriction) { String hql = "select count(*) from " + entityClass.getSimpleName(); List<String> criterias = new ArrayList<>(); if (entity instanceof WorkspaceEntity) { criterias.add("workspace.id = :wsid"); } String[] fields = field.split(","); for (String f : fields) { criterias.add(f + " = :" + f); } if (entity.getId() != null) { criterias.add("id <> :id"); } // any restriction available if (restriction != null) { criterias.add(restriction); } if (criterias.size() > 0) { hql += " where " + StringUtils.join(criterias, " and "); } Query qry = entityManager .createQuery(hql); if (entity instanceof WorkspaceEntity) { qry.setParameter("wsid", getWorkspaceId()); } if (entity.getId() != null) { qry.setParameter("id", entity.getId()); } // get the field value in the given object for (String f : fields) { Object val = ObjectUtils.getProperty(entity, f); qry.setParameter(f, val); } // query the database Number count = (Number) qry.getSingleResult(); return count.intValue() == 0; } /** * Check if the given entity is unique by searching by the given field * * @param entity the entity to check unique values * @param field the field (or comma separated list of fields) to check uniqueness * @param restriction an optional restriction to be included in the HQL WHERE clause * @return true if the entity is unique */ protected boolean checkUnique(E entity, String field, String restriction) { return checkUnique((Class<Synchronizable>) getEntityClass(), entity, field, restriction); } protected void validateAndSave(EntityServiceContext<E> context, EntityDAO<E> dao) { beforeValidate(context); // validate entity data if (!dao.validate()) { dao.raiseValidationError(); } // prepare entity to be saved beforeSave(context, dao.getErrors()); if (dao.hasErrors()) { dao.raiseValidationError(); } // save the entity dao.save(); } /** * Method that must be override in order to make any initialization before validation * * @param context object containing information about the requested operation */ protected void beforeValidate(EntityServiceContext<E> context) { // do nothing... To be implemented in the child class } /** * Prepare entity for saving, called right after the validation * * @param context object with information about the entity being saved * @param errors a container to receive any validation error found during the method call */ protected void beforeSave(EntityServiceContext<E> context, Errors errors) { // do nothing... To be implemented in the child class } /** * Called after the entity is saved * * @param context object containing information about the entity * @param res the result to be returned to the caller */ protected void afterSave(EntityServiceContext<E> context, ServiceResult res) { // do nothing... To be implemented in the child class } /** * Make any preparation before deleting the entity * * @param context object containing information about the entity * @param errors the list of possible validation errors */ protected void beforeDelete(EntityServiceContext<E> context, Errors errors) { // do nothing... To be implemented in the child class } /** * Called after the entity is deleted * * @param context object containing information about the entity * @param res the data to be returned to the caller */ protected void afterDelete(EntityServiceContext<E> context, ServiceResult res) { // do nothing... To be implemented in the child class } /** * Create a new object context to be passed to interceptors during CRUD operations * @param id the ID of the entity (if available) * @param entity the entity * @param request the request object that originated the operation * @return */ protected EntityServiceContext<E> createContext(UUID id, E entity, Object request) { return new EntityServiceContext<>(id, entity, request); } /** * Copy the values of the request to the entity * * @param context The context shared among interceptors, with information about the entity */ protected void mapRequest(EntityServiceContext<E> context) { EntityDAO<E> dao = createEntityDAO(); dao.setEntity(context.getEntity()); dao.mapToEntity(context.getRequest()); } /** * Generate the response from the entity * * @param entity the entity class * @param resultClass the class of the response data to be created * @param <K> * @return instance of the response data */ protected <K> K mapResponse(E entity, Class<K> resultClass) { EntityDAO<E> dao = createEntityDAO(); dao.setEntity(entity); return dao.mapFromEntity(resultClass); } /** * Create new DAO to handle CRUD operations * * @return instance of {@link EntityDAO} */ protected EntityDAO<E> createEntityDAO() { return entityDAOFactory.newDAO(getEntityClass()); } /** * Create a new instance of {@link EntityDAO} for a given entity class * * @param entityClass the class to create an EntityDAO for * @param <K> the generic class to be used * @return instance of {@link EntityDAO} */ protected <K> EntityDAO<K> createEntityDAO(Class<K> entityClass) { return entityDAOFactory.newDAO(entityClass); } /** * Search for an entity by its ID * * @param id * @param resultClass * @return the instance of resultClass containing the mapped entity values */ @Override @Transactional public <K> K findOne(UUID id, Class<K> resultClass) { EntityDAO<E> dao = createEntityDAO(); dao.setId(id); return dao.mapFromEntity(resultClass); } /** * Create the list of values to be logged * * @param entity * @param oper * @return */ protected ObjectValues createValuesToLog(E entity, Operation oper) { Class pureClass = Hibernate.getClass(entity); return PropertyLogUtils.generateLog(entity, pureClass, oper); } /** * Create the difference between two set of object values * * @param prevVals * @param newVals * @return */ protected Diffs createDiffs(ObjectValues prevVals, ObjectValues newVals) { return DiffsUtils.generateDiffsFromValues(prevVals, newVals); } /** * Return the current workspace ID * * @return instance of UUID */ protected UUID getWorkspaceId() { return userRequestService.getUserSession().getWorkspaceId(); } /** * Create the result to be returned by the create, update or delete operation * * @param entity the entity involved in the operation * @return instance of {@link ServiceResult} */ protected ServiceResult createResult(E entity) { ServiceResult res = new ServiceResult(); res.setId(entity.getId()); res.setEntityClass(getEntityClass()); String cmdPath = getCommandType(); res.setCommandType(CommandTypes.get(cmdPath)); if (entity instanceof Displayable) { res.setEntityName(((Displayable) entity).getDisplayString()); } else { res.setEntityName(entity.toString()); } return res; } /** * Return the entity by its given id * * @param id the entity primary key * @return entity object */ protected E findEntity(Object id) { try { return entityManager.find(getEntityClass(), id); } catch (EntityNotFoundException e) { return null; } } /** * Create a binding result to store validation error messages * * @param entity the entity assgined to the binding result * @return instance of {@link BindingResult} */ protected BindingResult createBindingResult(Object entity) { return new BeanPropertyBindingResult(entity, getEntityClass().getSimpleName()); } /** * Raise exception of a required field not present * * @param obj the object related to the exception * @param field the name of the field */ protected void raiseRequiredFieldException(Object obj, String field) { rejectFieldException(obj, field, Messages.REQUIRED); } /** * Raise a validation error exception. The exception is thrown immediately and there will be * just one field assigned to it * * @param obj the object related to the validation error * @param field the field with an error * @param msg the message with the validation error */ protected void rejectFieldException(Object obj, String field, String msg) { BindingResult res = createBindingResult(obj); res.rejectValue(field, msg); throw new EntityValidationException(res); } /** * Return the class of the entity being managed * * @return */ protected Class<E> getEntityClass() { if (entityClass == null) { entityClass = ObjectUtils.getGenericType(getClass(), 0); if (entityClass == null) { throw new RuntimeException("Could not get entity class"); } } return entityClass; } /** * Create a new instance of the entity class * * @param req the object used as request for this service * @return */ protected E createEntityInstance(Object req) { Class<E> clazz = getEntityClass(); return ObjectUtils.newInstance(clazz); } @Override public QueryResult findMany(Q qryParams) {
QueryBuilder<E> builder = queryBuilderFactory.createQueryBuilder(getEntityClass());
10
2023-10-23 13:47:54+00:00
24k
toel--/ocpp-backend-emulator
src/org/java_websocket/server/WebSocketServer.java
[ { "identifier": "AbstractWebSocket", "path": "src/org/java_websocket/AbstractWebSocket.java", "snippet": "public abstract class AbstractWebSocket extends WebSocketAdapter {\n\n /**\n * Logger instance\n *\n * @since 1.4.0\n */\n private final Logger log = LoggerFactory.getLogger(AbstractWebSoc...
import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.java_websocket.AbstractWebSocket; import org.java_websocket.SocketChannelIOHelper; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketFactory; import org.java_websocket.WebSocketImpl; import org.java_websocket.WebSocketServerFactory; import org.java_websocket.WrappedByteChannel; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.exceptions.WrappedIOException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.Handshakedata; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
21,381
* * @param conn The <tt>WebSocket</tt> instance this event is occurring on. * @param message The UTF-8 decoded message that was received. * @see #onMessage(WebSocket, ByteBuffer) **/ public abstract void onMessage(WebSocket conn, String message); /** * Called when errors occurs. If an error causes the websocket connection to fail {@link * #onClose(WebSocket, int, String, boolean)} will be called additionally.<br> This method will be * called primarily because of IO or protocol errors.<br> If the given exception is an * RuntimeException that probably means that you encountered a bug.<br> * * @param conn Can be null if there error does not belong to one specific websocket. For example * if the servers port could not be bound. * @param ex The exception causing this error **/ public abstract void onError(WebSocket conn, Exception ex); /** * Called when the server started up successfully. * <p> * If any error occurred, onError is called instead. */ public abstract void onStart(); /** * Callback for binary messages received from the remote host * * @param conn The <tt>WebSocket</tt> instance this event is occurring on. * @param message The binary message that was received. * @see #onMessage(WebSocket, ByteBuffer) **/ public void onMessage(WebSocket conn, ByteBuffer message) { } /** * Send a text to all connected endpoints * * @param text the text to send to the endpoints */ public void broadcast(String text) { broadcast(text, connections); } /** * Send a byte array to all connected endpoints * * @param data the data to send to the endpoints */ public void broadcast(byte[] data) { broadcast(data, connections); } /** * Send a ByteBuffer to all connected endpoints * * @param data the data to send to the endpoints */ public void broadcast(ByteBuffer data) { broadcast(data, connections); } /** * Send a byte array to a specific collection of websocket connections * * @param data the data to send to the endpoints * @param clients a collection of endpoints to whom the text has to be send */ public void broadcast(byte[] data, Collection<WebSocket> clients) { if (data == null || clients == null) { throw new IllegalArgumentException(); } broadcast(ByteBuffer.wrap(data), clients); } /** * Send a ByteBuffer to a specific collection of websocket connections * * @param data the data to send to the endpoints * @param clients a collection of endpoints to whom the text has to be send */ public void broadcast(ByteBuffer data, Collection<WebSocket> clients) { if (data == null || clients == null) { throw new IllegalArgumentException(); } doBroadcast(data, clients); } /** * Send a text to a specific collection of websocket connections * * @param text the text to send to the endpoints * @param clients a collection of endpoints to whom the text has to be send */ public void broadcast(String text, Collection<WebSocket> clients) { if (text == null || clients == null) { throw new IllegalArgumentException(); } doBroadcast(text, clients); } /** * Private method to cache all the frames to improve memory footprint and conversion time * * @param data the data to broadcast * @param clients the clients to send the message to */ private void doBroadcast(Object data, Collection<WebSocket> clients) { String strData = null; if (data instanceof String) { strData = (String) data; } ByteBuffer byteData = null; if (data instanceof ByteBuffer) { byteData = (ByteBuffer) data; } if (strData == null && byteData == null) { return; }
/* * Copyright (c) 2010-2020 Nathan Rajlich * * 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 org.java_websocket.server; /** * <tt>WebSocketServer</tt> is an abstract class that only takes care of the * HTTP handshake portion of WebSockets. It's up to a subclass to add functionality/purpose to the * server. */ public abstract class WebSocketServer extends AbstractWebSocket implements Runnable { private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); /** * Logger instance * * @since 1.4.0 */ private final Logger log = LoggerFactory.getLogger(WebSocketServer.class); /** * Holds the list of active WebSocket connections. "Active" means WebSocket handshake is complete * and socket can be written to, or read from. */ private final Collection<WebSocket> connections; /** * The port number that this WebSocket server should listen on. Default is * WebSocketImpl.DEFAULT_PORT. */ private final InetSocketAddress address; /** * The socket channel for this WebSocket server. */ private ServerSocketChannel server; /** * The 'Selector' used to get event keys from the underlying socket. */ private Selector selector; /** * The Draft of the WebSocket protocol the Server is adhering to. */ private List<Draft> drafts; private Thread selectorthread; private final AtomicBoolean isclosed = new AtomicBoolean(false); protected List<WebSocketWorker> decoders; private List<WebSocketImpl> iqueue; private BlockingQueue<ByteBuffer> buffers; private int queueinvokes = 0; private final AtomicInteger queuesize = new AtomicInteger(0); private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory(); /** * Attribute which allows you to configure the socket "backlog" parameter which determines how * many client connections can be queued. * * @since 1.5.0 */ private int maxPendingConnections = -1; /** * Creates a WebSocketServer that will attempt to listen on port <var>WebSocketImpl.DEFAULT_PORT</var>. * * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer() { this(new InetSocketAddress(WebSocketImpl.DEFAULT_PORT), AVAILABLE_PROCESSORS, null); } /** * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>. * * @param address The address to listen to * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address) { this(address, AVAILABLE_PROCESSORS, null); } /** * @param address The address (host:port) this server should listen on. * @param decodercount The number of {@link WebSocketWorker}s that will be used to process the * incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code> * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address, int decodercount) { this(address, decodercount, null); } /** * @param address The address (host:port) this server should listen on. * @param drafts The versions of the WebSocket protocol that this server instance should comply * to. Clients that use an other protocol version will be rejected. * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address, List<Draft> drafts) { this(address, AVAILABLE_PROCESSORS, drafts); } /** * @param address The address (host:port) this server should listen on. * @param decodercount The number of {@link WebSocketWorker}s that will be used to process the * incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code> * @param drafts The versions of the WebSocket protocol that this server instance should * comply to. Clients that use an other protocol version will be rejected. * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address, int decodercount, List<Draft> drafts) { this(address, decodercount, drafts, new HashSet<WebSocket>()); } /** * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>, and * comply with <tt>Draft</tt> version <var>draft</var>. * * @param address The address (host:port) this server should listen on. * @param decodercount The number of {@link WebSocketWorker}s that will be used to process * the incoming network data. By default this will be * <code>Runtime.getRuntime().availableProcessors()</code> * @param drafts The versions of the WebSocket protocol that this server instance * should comply to. Clients that use an other protocol version will * be rejected. * @param connectionscontainer Allows to specify a collection that will be used to store the * websockets in. <br> If you plan to often iterate through the * currently connected websockets you may want to use a collection * that does not require synchronization like a {@link * CopyOnWriteArraySet}. In that case make sure that you overload * {@link #removeConnection(WebSocket)} and {@link * #addConnection(WebSocket)}.<br> By default a {@link HashSet} will * be used. * @see #removeConnection(WebSocket) for more control over syncronized operation * @see <a href="https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts" > more about * drafts</a> */ public WebSocketServer(InetSocketAddress address, int decodercount, List<Draft> drafts, Collection<WebSocket> connectionscontainer) { if (address == null || decodercount < 1 || connectionscontainer == null) { throw new IllegalArgumentException( "address and connectionscontainer must not be null and you need at least 1 decoder"); } if (drafts == null) { this.drafts = Collections.emptyList(); } else { this.drafts = drafts; } this.address = address; this.connections = connectionscontainer; setTcpNoDelay(false); setReuseAddr(false); iqueue = new LinkedList<>(); decoders = new ArrayList<>(decodercount); buffers = new LinkedBlockingQueue<>(); for (int i = 0; i < decodercount; i++) { WebSocketWorker ex = new WebSocketWorker(); decoders.add(ex); } } /** * Starts the server selectorthread that binds to the currently set port number and listeners for * WebSocket connection requests. Creates a fixed thread pool with the size {@link * WebSocketServer#AVAILABLE_PROCESSORS}<br> May only be called once. * <p> * Alternatively you can call {@link WebSocketServer#run()} directly. * * @throws IllegalStateException Starting an instance again */ public void start() { if (selectorthread != null) { throw new IllegalStateException(getClass().getName() + " can only be started once."); } new Thread(this).start(); } public void stop(int timeout) throws InterruptedException { stop(timeout, ""); } /** * Closes all connected clients sockets, then closes the underlying ServerSocketChannel, * effectively killing the server socket selectorthread, freeing the port the server was bound to * and stops all internal workerthreads. * <p> * If this method is called before the server is started it will never start. * * @param timeout Specifies how many milliseconds the overall close handshaking may take * altogether before the connections are closed without proper close * handshaking. * @param closeMessage Specifies message for remote client<br> * @throws InterruptedException Interrupt */ public void stop(int timeout, String closeMessage) throws InterruptedException { if (!isclosed.compareAndSet(false, true)) { // this also makes sure that no further connections will be added to this.connections return; } List<WebSocket> socketsToClose; // copy the connections in a list (prevent callback deadlocks) synchronized (connections) { socketsToClose = new ArrayList<>(connections); } for (WebSocket ws : socketsToClose) { ws.close(CloseFrame.GOING_AWAY, closeMessage); } wsf.close(); synchronized (this) { if (selectorthread != null && selector != null) { selector.wakeup(); selectorthread.join(timeout); } } } public void stop() throws InterruptedException { stop(0); } /** * Returns all currently connected clients. This collection does not allow any modification e.g. * removing a client. * * @return A unmodifiable collection of all currently connected clients * @since 1.3.8 */ @Override public Collection<WebSocket> getConnections() { synchronized (connections) { return Collections.unmodifiableCollection(new ArrayList<>(connections)); } } public InetSocketAddress getAddress() { return this.address; } /** * Gets the port number that this server listens on. * * @return The port number. */ public int getPort() { int port = getAddress().getPort(); if (port == 0 && server != null) { port = server.socket().getLocalPort(); } return port; } /** * Get the list of active drafts * * @return the available drafts for this server */ public List<Draft> getDraft() { return Collections.unmodifiableList(drafts); } /** * Set the requested maximum number of pending connections on the socket. The exact semantics are * implementation specific. The value provided should be greater than 0. If it is less than or * equal to 0, then an implementation specific default will be used. This option will be passed as * "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)} * * @since 1.5.0 * @param numberOfConnections the new number of allowed pending connections */ public void setMaxPendingConnections(int numberOfConnections) { maxPendingConnections = numberOfConnections; } /** * Returns the currently configured maximum number of pending connections. * * @see #setMaxPendingConnections(int) * @since 1.5.0 * @return the maximum number of pending connections */ public int getMaxPendingConnections() { return maxPendingConnections; } // Runnable IMPLEMENTATION ///////////////////////////////////////////////// public void run() { if (!doEnsureSingleThread()) { return; } if (!doSetupSelectorAndServerThread()) { return; } try { int shutdownCount = 5; int selectTimeout = 0; while (!selectorthread.isInterrupted() && shutdownCount != 0) { SelectionKey key = null; try { if (isclosed.get()) { selectTimeout = 5; } int keyCount = selector.select(selectTimeout); if (keyCount == 0 && isclosed.get()) { shutdownCount--; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while (i.hasNext()) { key = i.next(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { doAccept(key, i); continue; } if (key.isReadable() && !doRead(key, i)) { continue; } if (key.isWritable()) { doWrite(key); } } doAdditionalRead(); } catch (CancelledKeyException e) { // an other thread may cancel the key } catch (ClosedByInterruptException e) { return; // do the same stuff as when InterruptedException is thrown } catch (WrappedIOException ex) { handleIOException(key, ex.getConnection(), ex.getIOException()); } catch (IOException ex) { handleIOException(key, null, ex); } catch (InterruptedException e) { // FIXME controlled shutdown (e.g. take care of buffermanagement) Thread.currentThread().interrupt(); } } } catch (RuntimeException e) { // should hopefully never occur handleFatal(null, e); } finally { doServerShutdown(); } } /** * Do an additional read * * @throws InterruptedException thrown by taking a buffer * @throws IOException if an error happened during read */ private void doAdditionalRead() throws InterruptedException, IOException { WebSocketImpl conn; while (!iqueue.isEmpty()) { conn = iqueue.remove(0); WrappedByteChannel c = ((WrappedByteChannel) conn.getChannel()); ByteBuffer buf = takeBuffer(); try { if (SocketChannelIOHelper.readMore(buf, conn, c)) { iqueue.add(conn); } if (buf.hasRemaining()) { conn.inQueue.put(buf); queue(conn); } else { pushBuffer(buf); } } catch (IOException e) { pushBuffer(buf); throw e; } } } /** * Execute a accept operation * * @param key the selectionkey to read off * @param i the iterator for the selection keys * @throws InterruptedException thrown by taking a buffer * @throws IOException if an error happened during accept */ private void doAccept(SelectionKey key, Iterator<SelectionKey> i) throws IOException, InterruptedException { if (!onConnect(key)) { key.cancel(); return; } SocketChannel channel = server.accept(); if (channel == null) { return; } channel.configureBlocking(false); Socket socket = channel.socket(); socket.setTcpNoDelay(isTcpNoDelay()); socket.setKeepAlive(true); WebSocketImpl w = wsf.createWebSocket(this, drafts); w.setSelectionKey(channel.register(selector, SelectionKey.OP_READ, w)); try { w.setChannel(wsf.wrapChannel(channel, w.getSelectionKey())); i.remove(); allocateBuffers(w); } catch (IOException ex) { if (w.getSelectionKey() != null) { w.getSelectionKey().cancel(); } handleIOException(w.getSelectionKey(), null, ex); } } /** * Execute a read operation * * @param key the selectionkey to read off * @param i the iterator for the selection keys * @return true, if the read was successful, or false if there was an error * @throws InterruptedException thrown by taking a buffer * @throws IOException if an error happened during read */ private boolean doRead(SelectionKey key, Iterator<SelectionKey> i) throws InterruptedException, WrappedIOException { WebSocketImpl conn = (WebSocketImpl) key.attachment(); ByteBuffer buf = takeBuffer(); if (conn.getChannel() == null) { key.cancel(); handleIOException(key, conn, new IOException()); return false; } try { if (SocketChannelIOHelper.read(buf, conn, conn.getChannel())) { if (buf.hasRemaining()) { conn.inQueue.put(buf); queue(conn); i.remove(); if (conn.getChannel() instanceof WrappedByteChannel && ((WrappedByteChannel) conn .getChannel()).isNeedRead()) { iqueue.add(conn); } } else { pushBuffer(buf); } } else { pushBuffer(buf); } } catch (IOException e) { pushBuffer(buf); throw new WrappedIOException(conn, e); } return true; } /** * Execute a write operation * * @param key the selectionkey to write on * @throws IOException if an error happened during batch */ private void doWrite(SelectionKey key) throws WrappedIOException { WebSocketImpl conn = (WebSocketImpl) key.attachment(); try { if (SocketChannelIOHelper.batch(conn, conn.getChannel()) && key.isValid()) { key.interestOps(SelectionKey.OP_READ); } } catch (IOException e) { throw new WrappedIOException(conn, e); } } /** * Setup the selector thread as well as basic server settings * * @return true, if everything was successful, false if some error happened */ private boolean doSetupSelectorAndServerThread() { selectorthread.setName("WebSocketSelector-" + selectorthread.getId()); try { server = ServerSocketChannel.open(); server.configureBlocking(false); ServerSocket socket = server.socket(); socket.setReceiveBufferSize(WebSocketImpl.RCVBUF); socket.setReuseAddress(isReuseAddr()); socket.bind(address, getMaxPendingConnections()); selector = Selector.open(); server.register(selector, server.validOps()); startConnectionLostTimer(); for (WebSocketWorker ex : decoders) { ex.start(); } onStart(); } catch (IOException ex) { handleFatal(null, ex); return false; } return true; } /** * The websocket server can only be started once * * @return true, if the server can be started, false if already a thread is running */ private boolean doEnsureSingleThread() { synchronized (this) { if (selectorthread != null) { throw new IllegalStateException(getClass().getName() + " can only be started once."); } selectorthread = Thread.currentThread(); if (isclosed.get()) { return false; } } return true; } /** * Clean up everything after a shutdown */ private void doServerShutdown() { stopConnectionLostTimer(); if (decoders != null) { for (WebSocketWorker w : decoders) { w.interrupt(); } } if (selector != null) { try { selector.close(); } catch (IOException e) { log.error("IOException during selector.close", e); onError(null, e); } } if (server != null) { try { server.close(); } catch (IOException e) { log.error("IOException during server.close", e); onError(null, e); } } } protected void allocateBuffers(WebSocket c) throws InterruptedException { if (queuesize.get() >= 2 * decoders.size() + 1) { return; } queuesize.incrementAndGet(); buffers.put(createBuffer()); } protected void releaseBuffers(WebSocket c) throws InterruptedException { // queuesize.decrementAndGet(); // takeBuffer(); } public ByteBuffer createBuffer() { return ByteBuffer.allocate(WebSocketImpl.RCVBUF); } protected void queue(WebSocketImpl ws) throws InterruptedException { if (ws.getWorkerThread() == null) { ws.setWorkerThread(decoders.get(queueinvokes % decoders.size())); queueinvokes++; } ws.getWorkerThread().put(ws); } private ByteBuffer takeBuffer() throws InterruptedException { return buffers.take(); } private void pushBuffer(ByteBuffer buf) throws InterruptedException { if (buffers.size() > queuesize.intValue()) { return; } buffers.put(buf); } private void handleIOException(SelectionKey key, WebSocket conn, IOException ex) { // onWebsocketError( conn, ex );// conn may be null here if (key != null) { key.cancel(); } if (conn != null) { conn.closeConnection(CloseFrame.ABNORMAL_CLOSE, ex.getMessage()); } else if (key != null) { SelectableChannel channel = key.channel(); if (channel != null && channel .isOpen()) { // this could be the case if the IOException ex is a SSLException try { channel.close(); } catch (IOException e) { // there is nothing that must be done here } log.trace("Connection closed because of exception", ex); } } } private void handleFatal(WebSocket conn, Exception e) { log.error("Shutdown due to fatal error", e); onError(conn, e); String causeMessage = e.getCause() != null ? " caused by " + e.getCause().getClass().getName() : ""; String errorMessage = "Got error on server side: " + e.getClass().getName() + causeMessage; try { stop(0, errorMessage); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); log.error("Interrupt during stop", e); onError(null, e1); } //Shutting down WebSocketWorkers, see #222 if (decoders != null) { for (WebSocketWorker w : decoders) { w.interrupt(); } } if (selectorthread != null) { selectorthread.interrupt(); } } @Override public final void onWebsocketMessage(WebSocket conn, String message) { onMessage(conn, message); } @Override public final void onWebsocketMessage(WebSocket conn, ByteBuffer blob) { onMessage(conn, blob); } @Override public final void onWebsocketOpen(WebSocket conn, Handshakedata handshake) { if (addConnection(conn)) { onOpen(conn, (ClientHandshake) handshake); } } @Override public final void onWebsocketClose(WebSocket conn, int code, String reason, boolean remote) { selector.wakeup(); try { if (removeConnection(conn)) { onClose(conn, code, reason, remote); } } finally { try { releaseBuffers(conn); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } /** * This method performs remove operations on the connection and therefore also gives control over * whether the operation shall be synchronized * <p> * {@link #WebSocketServer(InetSocketAddress, int, List, Collection)} allows to specify a * collection which will be used to store current connections in.<br> Depending on the type on the * connection, modifications of that collection may have to be synchronized. * * @param ws The Websocket connection which should be removed * @return Removing connection successful */ protected boolean removeConnection(WebSocket ws) { boolean removed = false; synchronized (connections) { if (this.connections.contains(ws)) { removed = this.connections.remove(ws); } else { //Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512 log.trace( "Removing connection which is not in the connections collection! Possible no handshake received! {}", ws); } } if (isclosed.get() && connections.isEmpty()) { selectorthread.interrupt(); } return removed; } /** * @param ws the Websocket connection which should be added * @return Adding connection successful * @see #removeConnection(WebSocket) */ protected boolean addConnection(WebSocket ws) { if (!isclosed.get()) { synchronized (connections) { return this.connections.add(ws); } } else { // This case will happen when a new connection gets ready while the server is already stopping. ws.close(CloseFrame.GOING_AWAY); return true;// for consistency sake we will make sure that both onOpen will be called } } @Override public final void onWebsocketError(WebSocket conn, Exception ex) { onError(conn, ex); } @Override public final void onWriteDemand(WebSocket w) { WebSocketImpl conn = (WebSocketImpl) w; try { conn.getSelectionKey().interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } catch (CancelledKeyException e) { // the thread which cancels key is responsible for possible cleanup conn.outQueue.clear(); } selector.wakeup(); } @Override public void onWebsocketCloseInitiated(WebSocket conn, int code, String reason) { onCloseInitiated(conn, code, reason); } @Override public void onWebsocketClosing(WebSocket conn, int code, String reason, boolean remote) { onClosing(conn, code, reason, remote); } public void onCloseInitiated(WebSocket conn, int code, String reason) { } public void onClosing(WebSocket conn, int code, String reason, boolean remote) { } public final void setWebSocketFactory(WebSocketServerFactory wsf) { if (this.wsf != null) { this.wsf.close(); } this.wsf = wsf; } public final WebSocketFactory getWebSocketFactory() { return wsf; } /** * Returns whether a new connection shall be accepted or not.<br> Therefore method is well suited * to implement some kind of connection limitation.<br> * * @param key the SelectionKey for the new connection * @return Can this new connection be accepted * @see #onOpen(WebSocket, ClientHandshake) * @see #onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake) **/ protected boolean onConnect(SelectionKey key) { return true; } /** * Getter to return the socket used by this specific connection * * @param conn The specific connection * @return The socket used by this connection */ private Socket getSocket(WebSocket conn) { WebSocketImpl impl = (WebSocketImpl) conn; return ((SocketChannel) impl.getSelectionKey().channel()).socket(); } @Override public InetSocketAddress getLocalSocketAddress(WebSocket conn) { return (InetSocketAddress) getSocket(conn).getLocalSocketAddress(); } @Override public InetSocketAddress getRemoteSocketAddress(WebSocket conn) { return (InetSocketAddress) getSocket(conn).getRemoteSocketAddress(); } /** * Called after an opening handshake has been performed and the given websocket is ready to be * written on. * * @param conn The <tt>WebSocket</tt> instance this event is occurring on. * @param handshake The handshake of the websocket instance */ public abstract void onOpen(WebSocket conn, ClientHandshake handshake); /** * Called after the websocket connection has been closed. * * @param conn The <tt>WebSocket</tt> instance this event is occurring on. * @param code The codes can be looked up here: {@link CloseFrame} * @param reason Additional information string * @param remote Returns whether or not the closing of the connection was initiated by the remote * host. **/ public abstract void onClose(WebSocket conn, int code, String reason, boolean remote); /** * Callback for string messages received from the remote host * * @param conn The <tt>WebSocket</tt> instance this event is occurring on. * @param message The UTF-8 decoded message that was received. * @see #onMessage(WebSocket, ByteBuffer) **/ public abstract void onMessage(WebSocket conn, String message); /** * Called when errors occurs. If an error causes the websocket connection to fail {@link * #onClose(WebSocket, int, String, boolean)} will be called additionally.<br> This method will be * called primarily because of IO or protocol errors.<br> If the given exception is an * RuntimeException that probably means that you encountered a bug.<br> * * @param conn Can be null if there error does not belong to one specific websocket. For example * if the servers port could not be bound. * @param ex The exception causing this error **/ public abstract void onError(WebSocket conn, Exception ex); /** * Called when the server started up successfully. * <p> * If any error occurred, onError is called instead. */ public abstract void onStart(); /** * Callback for binary messages received from the remote host * * @param conn The <tt>WebSocket</tt> instance this event is occurring on. * @param message The binary message that was received. * @see #onMessage(WebSocket, ByteBuffer) **/ public void onMessage(WebSocket conn, ByteBuffer message) { } /** * Send a text to all connected endpoints * * @param text the text to send to the endpoints */ public void broadcast(String text) { broadcast(text, connections); } /** * Send a byte array to all connected endpoints * * @param data the data to send to the endpoints */ public void broadcast(byte[] data) { broadcast(data, connections); } /** * Send a ByteBuffer to all connected endpoints * * @param data the data to send to the endpoints */ public void broadcast(ByteBuffer data) { broadcast(data, connections); } /** * Send a byte array to a specific collection of websocket connections * * @param data the data to send to the endpoints * @param clients a collection of endpoints to whom the text has to be send */ public void broadcast(byte[] data, Collection<WebSocket> clients) { if (data == null || clients == null) { throw new IllegalArgumentException(); } broadcast(ByteBuffer.wrap(data), clients); } /** * Send a ByteBuffer to a specific collection of websocket connections * * @param data the data to send to the endpoints * @param clients a collection of endpoints to whom the text has to be send */ public void broadcast(ByteBuffer data, Collection<WebSocket> clients) { if (data == null || clients == null) { throw new IllegalArgumentException(); } doBroadcast(data, clients); } /** * Send a text to a specific collection of websocket connections * * @param text the text to send to the endpoints * @param clients a collection of endpoints to whom the text has to be send */ public void broadcast(String text, Collection<WebSocket> clients) { if (text == null || clients == null) { throw new IllegalArgumentException(); } doBroadcast(text, clients); } /** * Private method to cache all the frames to improve memory footprint and conversion time * * @param data the data to broadcast * @param clients the clients to send the message to */ private void doBroadcast(Object data, Collection<WebSocket> clients) { String strData = null; if (data instanceof String) { strData = (String) data; } ByteBuffer byteData = null; if (data instanceof ByteBuffer) { byteData = (ByteBuffer) data; } if (strData == null && byteData == null) { return; }
Map<Draft, List<Framedata>> draftFrames = new HashMap<>();
11
2023-10-16 23:10:55+00:00
24k
weibocom/rill-flow
rill-flow-service/src/main/java/com/weibo/rill/flow/service/component/OlympiceneCallback.java
[ { "identifier": "PrometheusActions", "path": "rill-flow-service/src/main/java/com/weibo/rill/flow/service/util/PrometheusActions.java", "snippet": "@Slf4j\npublic class PrometheusActions {\n\n public static final String REACHED = \"REACHED\";\n public static final String NOT_REACHED = \"NOT_REACHE...
import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.weibo.rill.flow.service.util.PrometheusActions; import com.weibo.rill.flow.olympicene.core.event.Callback; import com.weibo.rill.flow.olympicene.core.event.Event; import com.weibo.rill.flow.olympicene.core.helper.DAGWalkHelper; import com.weibo.rill.flow.olympicene.core.model.dag.DAG; import com.weibo.rill.flow.olympicene.core.model.dag.DAGInfo; import com.weibo.rill.flow.olympicene.core.model.dag.DAGInvokeMsg; import com.weibo.rill.flow.olympicene.core.model.dag.DAGStatus; import com.weibo.rill.flow.olympicene.core.model.strategy.CallbackConfig; import com.weibo.rill.flow.interfaces.model.task.InvokeTimeInfo; import com.weibo.rill.flow.interfaces.model.task.TaskInfo; import com.weibo.rill.flow.interfaces.model.task.TaskInvokeMsg; import com.weibo.rill.flow.olympicene.traversal.callback.DAGCallbackInfo; import com.weibo.rill.flow.olympicene.traversal.callback.DAGEvent; import com.weibo.rill.flow.olympicene.traversal.mappings.JSONPathInputOutputMapping; import com.weibo.rill.flow.interfaces.model.resource.Resource; import com.weibo.rill.flow.interfaces.model.http.HttpParameter; import com.weibo.rill.flow.service.invoke.HttpInvokeHelper; import com.weibo.rill.flow.service.statistic.TenantTaskStatistic; import com.weibo.rill.flow.service.storage.LongTermStorage; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.service.util.ProfileActions; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors;
15,282
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.service.component; @Slf4j public class OlympiceneCallback implements Callback<DAGCallbackInfo> { private final HttpInvokeHelper httpInvokeHelper; private final JSONPathInputOutputMapping inputOutputMapping; private final LongTermStorage longTermStorage; private final ExecutorService callbackExecutor; private final TenantTaskStatistic tenantTaskStatistic; private final SwitcherManager switcherManagerImpl; public OlympiceneCallback(HttpInvokeHelper httpInvokeHelper, JSONPathInputOutputMapping inputOutputMapping, LongTermStorage longTermStorage, ExecutorService callbackExecutor, TenantTaskStatistic tenantTaskStatistic, SwitcherManager switcherManagerImpl) { this.httpInvokeHelper = httpInvokeHelper; this.inputOutputMapping = inputOutputMapping; this.longTermStorage = longTermStorage; this.callbackExecutor = callbackExecutor; this.tenantTaskStatistic = tenantTaskStatistic; this.switcherManagerImpl = switcherManagerImpl; } @Override public void onEvent(Event<DAGCallbackInfo> event) { if (event == null || event.getData() == null) { return; } callbackExecutor.execute(() -> { int eventCode = event.getEventCode(); DAGCallbackInfo eventData = event.getData(); monitorLog(event.getId(), eventCode, eventData); if (eventCode == DAGEvent.DAG_SUCCEED.getCode() || eventCode == DAGEvent.DAG_FAILED.getCode()) { longTermStorage.storeDAGInfoAndContext(eventData); flowCompletedCallback(eventCode, eventData); } }); } private void monitorLog(String executionId, int eventCode, DAGCallbackInfo eventData) { logCompleteEvent(executionId, eventCode, eventData); logTaskCode(executionId, eventCode, eventData); } private void logTaskCode(String executionId, int eventCode, DAGCallbackInfo eventData) { try { if (eventCode != DAGEvent.TASK_FAILED.getCode() && eventCode != DAGEvent.TASK_SKIPPED.getCode()) { return; } TaskInfo taskInfo = eventData.getTaskInfo(); String code = Optional.ofNullable(taskInfo.getTaskInvokeMsg()) .map(TaskInvokeMsg::getCode).orElse(null); if (StringUtils.isNotBlank(code)) { ProfileActions.recordTaskCode(executionId, code, "total"); String baseTaskName = DAGWalkHelper.getInstance().getBaseTaskName(taskInfo.getName()); ProfileActions.recordTaskCode(executionId, code, baseTaskName); // 记录prometheus PrometheusActions.recordTaskCode(executionId, code, "total"); PrometheusActions.recordTaskCode(executionId, code, baseTaskName); } } catch (Exception e) { log.warn("logTaskCode fails, eventCode:{}", eventCode, e); } } private void logCompleteEvent(String executionId, int eventCode, DAGCallbackInfo eventData) { try { if (eventCode > DAGEvent.DAG_SUCCEED.getCode()) { Optional.ofNullable(eventData.getTaskInfo()) .ifPresent(taskInfo -> { long executionCost = getExecutionTime(taskInfo.getTaskInvokeMsg().getInvokeTimeInfos()); ProfileActions.recordTaskComplete(executionId, taskInfo.getTask().getCategory(), executionCost); // 记录prometheus PrometheusActions.recordTaskComplete(executionId, taskInfo.getTask().getCategory(), executionCost); tenantTaskStatistic.taskProfileLog(executionCost, executionId, taskInfo.getName(), "complete"); }); } else { long executionCost = getExecutionTime(eventData.getDagInfo().getDagInvokeMsg().getInvokeTimeInfos()); ProfileActions.recordDAGComplete(executionId, executionCost); // 记录prometheus PrometheusActions.recordDAGComplete(executionId, executionCost); } } catch (Exception e) { log.warn("logCompleteEvent fails, eventCode:{}", eventCode, e); } } private long getExecutionTime(List<InvokeTimeInfo> invokeTimeInfos) { return Optional.ofNullable(invokeTimeInfos) .filter(CollectionUtils::isNotEmpty) .map(it -> it.get(it.size() - 1)) .filter(it -> it.getStartTimeInMillisecond() != null && it.getEndTimeInMillisecond() != null) .map(it -> it.getEndTimeInMillisecond() - it.getStartTimeInMillisecond()) .orElse(0L); } private void flowCompletedCallback(int eventCode, DAGCallbackInfo dagCallbackInfo) { try { DAGInfo dagInfo = dagCallbackInfo.getDagInfo(); CallbackConfig callbackConfig = getCallbackConfig(dagInfo); String executionId = dagInfo.getExecutionId(); String resourceName = Optional.ofNullable(callbackConfig).map(CallbackConfig::getResourceName).orElse(null); if (StringUtils.isBlank(resourceName)) { log.info("flowCompletedCallback return due to empty resourceName, executionId:{}", executionId); return; }
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.service.component; @Slf4j public class OlympiceneCallback implements Callback<DAGCallbackInfo> { private final HttpInvokeHelper httpInvokeHelper; private final JSONPathInputOutputMapping inputOutputMapping; private final LongTermStorage longTermStorage; private final ExecutorService callbackExecutor; private final TenantTaskStatistic tenantTaskStatistic; private final SwitcherManager switcherManagerImpl; public OlympiceneCallback(HttpInvokeHelper httpInvokeHelper, JSONPathInputOutputMapping inputOutputMapping, LongTermStorage longTermStorage, ExecutorService callbackExecutor, TenantTaskStatistic tenantTaskStatistic, SwitcherManager switcherManagerImpl) { this.httpInvokeHelper = httpInvokeHelper; this.inputOutputMapping = inputOutputMapping; this.longTermStorage = longTermStorage; this.callbackExecutor = callbackExecutor; this.tenantTaskStatistic = tenantTaskStatistic; this.switcherManagerImpl = switcherManagerImpl; } @Override public void onEvent(Event<DAGCallbackInfo> event) { if (event == null || event.getData() == null) { return; } callbackExecutor.execute(() -> { int eventCode = event.getEventCode(); DAGCallbackInfo eventData = event.getData(); monitorLog(event.getId(), eventCode, eventData); if (eventCode == DAGEvent.DAG_SUCCEED.getCode() || eventCode == DAGEvent.DAG_FAILED.getCode()) { longTermStorage.storeDAGInfoAndContext(eventData); flowCompletedCallback(eventCode, eventData); } }); } private void monitorLog(String executionId, int eventCode, DAGCallbackInfo eventData) { logCompleteEvent(executionId, eventCode, eventData); logTaskCode(executionId, eventCode, eventData); } private void logTaskCode(String executionId, int eventCode, DAGCallbackInfo eventData) { try { if (eventCode != DAGEvent.TASK_FAILED.getCode() && eventCode != DAGEvent.TASK_SKIPPED.getCode()) { return; } TaskInfo taskInfo = eventData.getTaskInfo(); String code = Optional.ofNullable(taskInfo.getTaskInvokeMsg()) .map(TaskInvokeMsg::getCode).orElse(null); if (StringUtils.isNotBlank(code)) { ProfileActions.recordTaskCode(executionId, code, "total"); String baseTaskName = DAGWalkHelper.getInstance().getBaseTaskName(taskInfo.getName()); ProfileActions.recordTaskCode(executionId, code, baseTaskName); // 记录prometheus PrometheusActions.recordTaskCode(executionId, code, "total"); PrometheusActions.recordTaskCode(executionId, code, baseTaskName); } } catch (Exception e) { log.warn("logTaskCode fails, eventCode:{}", eventCode, e); } } private void logCompleteEvent(String executionId, int eventCode, DAGCallbackInfo eventData) { try { if (eventCode > DAGEvent.DAG_SUCCEED.getCode()) { Optional.ofNullable(eventData.getTaskInfo()) .ifPresent(taskInfo -> { long executionCost = getExecutionTime(taskInfo.getTaskInvokeMsg().getInvokeTimeInfos()); ProfileActions.recordTaskComplete(executionId, taskInfo.getTask().getCategory(), executionCost); // 记录prometheus PrometheusActions.recordTaskComplete(executionId, taskInfo.getTask().getCategory(), executionCost); tenantTaskStatistic.taskProfileLog(executionCost, executionId, taskInfo.getName(), "complete"); }); } else { long executionCost = getExecutionTime(eventData.getDagInfo().getDagInvokeMsg().getInvokeTimeInfos()); ProfileActions.recordDAGComplete(executionId, executionCost); // 记录prometheus PrometheusActions.recordDAGComplete(executionId, executionCost); } } catch (Exception e) { log.warn("logCompleteEvent fails, eventCode:{}", eventCode, e); } } private long getExecutionTime(List<InvokeTimeInfo> invokeTimeInfos) { return Optional.ofNullable(invokeTimeInfos) .filter(CollectionUtils::isNotEmpty) .map(it -> it.get(it.size() - 1)) .filter(it -> it.getStartTimeInMillisecond() != null && it.getEndTimeInMillisecond() != null) .map(it -> it.getEndTimeInMillisecond() - it.getStartTimeInMillisecond()) .orElse(0L); } private void flowCompletedCallback(int eventCode, DAGCallbackInfo dagCallbackInfo) { try { DAGInfo dagInfo = dagCallbackInfo.getDagInfo(); CallbackConfig callbackConfig = getCallbackConfig(dagInfo); String executionId = dagInfo.getExecutionId(); String resourceName = Optional.ofNullable(callbackConfig).map(CallbackConfig::getResourceName).orElse(null); if (StringUtils.isBlank(resourceName)) { log.info("flowCompletedCallback return due to empty resourceName, executionId:{}", executionId); return; }
HttpParameter requestParams = buildRequestParams(callbackConfig, dagCallbackInfo);
16
2023-11-03 03:46:01+00:00
24k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/activities/profile/SettingsActivity.java
[ { "identifier": "UserDAO", "path": "app/src/main/java/com/daominh/quickmem/data/dao/UserDAO.java", "snippet": "public class UserDAO {\n\n private final QMDatabaseHelper qmDatabaseHelper;\n private SQLiteDatabase sqLiteDatabase;\n\n public UserDAO(Context context) {\n qmDatabaseHelper = n...
import android.app.Dialog; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Toast; import com.daominh.quickmem.R; import com.daominh.quickmem.data.dao.UserDAO; import com.daominh.quickmem.databinding.ActivitySettingsBinding; import com.daominh.quickmem.databinding.DialogChangeEmailBinding; import com.daominh.quickmem.databinding.DialogChangeUsernameBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.auth.signin.SignInActivity; import com.daominh.quickmem.ui.activities.profile.change.ChangeEmailActivity; import com.daominh.quickmem.ui.activities.profile.change.ChangePasswordActivity; import com.daominh.quickmem.ui.activities.profile.change.ChangeUsernameActivity; import com.daominh.quickmem.ui.activities.set.ViewSetActivity; import com.daominh.quickmem.utils.PasswordHasher; import com.saadahmedsoft.popupdialog.PopupDialog; import com.saadahmedsoft.popupdialog.Styles; import com.saadahmedsoft.popupdialog.listener.OnDialogButtonClickListener; import java.util.Objects;
15,135
package com.daominh.quickmem.ui.activities.profile; public class SettingsActivity extends AppCompatActivity { private ActivitySettingsBinding binding; private UserSharePreferences userSharePreferences; private AlertDialog detailDialog;
package com.daominh.quickmem.ui.activities.profile; public class SettingsActivity extends AppCompatActivity { private ActivitySettingsBinding binding; private UserSharePreferences userSharePreferences; private AlertDialog detailDialog;
UserDAO userDAO;
0
2023-11-07 16:56:39+00:00
24k
FRCTeam2910/2023CompetitionRobot-Public
src/main/java/org/frcteam2910/c2023/util/PathChooser.java
[ { "identifier": "RobotContainer", "path": "src/main/java/org/frcteam2910/c2023/RobotContainer.java", "snippet": "public class RobotContainer {\n private final PathChooser pathChooser;\n\n private final DrivetrainSubsystem drivetrainSubsystem;\n\n private final LEDSubsystem ledSubsystem;\n\n ...
import com.pathplanner.lib.PathPlannerTrajectory; import edu.wpi.first.math.geometry.Pose2d; 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.*; import org.frcteam2910.c2023.RobotContainer; import org.frcteam2910.c2023.commands.*; import org.frcteam2910.c2023.subsystems.drivetrain.DrivetrainSubsystem; import org.frcteam2910.c2023.subsystems.intake.IntakeSubsystem; import org.frcteam2910.c2023.util.constants.ArmPoseConstants; import org.littletonrobotics.junction.Logger;
15,880
() -> targetPiece)) .andThen(new StowArmCommand(container.getArmSubsystem())); } private Command followWhileIntakingWithNoWait( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece targetPiece) { return follow(container, trajectory) .alongWith(new ArmToPoseCommand(container.getArmSubsystem(), ArmPoseConstants.GROUND_CUBE)) .raceWith(new SetIntakeCommand( container.getIntakeSubsystem(), () -> IntakeSubsystem.TargetIntakeStates.COLLECT, () -> targetPiece)); } private Command followWhileIntaking( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece targetPiece) { return followWhileIntaking(container, trajectory, targetPiece, 2, ArmPoseConstants.ARM_UP, false); } /** * @param container RobotContainer to get subsystems * @param trajectory Trajectory to follow * @param scoringPiece Piece to score */ private Command followThenScore( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece scoringPiece, ArmPositions position) { return followThenScore(container, trajectory, scoringPiece, position, 2, ArmPoseConstants.ARM_UP, false); } private Command followThenScore( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece scoringPiece, ArmPositions position, double waitTime, ArmPositions travelState) { return followThenScore(container, trajectory, scoringPiece, position, waitTime, travelState, false); } private Command followThenScore( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece scoringPiece, ArmPositions position, double waitTime, ArmPositions travelState, boolean fastEject) { SequentialCommandGroup armMotionCommand = new SequentialCommandGroup(); Timer timer = new Timer(); armMotionCommand.addCommands(new InstantCommand(timer::restart)); // Restart timer armMotionCommand.addCommands(new ArmToPoseCommand(container.getArmSubsystem(), travelState)); // Put the arm up armMotionCommand.addCommands(new InstantCommand( timer::stop)); // Stop the timer such that it now stores the amount of time the arm command took armMotionCommand.addCommands(new ProxyCommand(() -> new WaitCommand(trajectory.getTotalTimeSeconds() - timer.get() - waitTime))); // Wait for the remaining time in the path minus a one second wait time armMotionCommand.addCommands(new ArmToPoseCommand( container.getArmSubsystem(), position)); // Move the arm to the scoring pose as we are one second out from hitting the drivetrain SequentialCommandGroup intakeCommand = new SequentialCommandGroup(); intakeCommand.addCommands(new WaitUntilCommand(() -> isAtScoringPose(container, trajectory))); intakeCommand.addCommands(score(container, scoringPiece, fastEject)); return follow(container, trajectory).alongWith(armMotionCommand).alongWith(intakeCommand); } /** * @param container RobotContainer to get subsystems * @param targetPiece Piece to intake */ private Command intake(RobotContainer container, GamePiece targetPiece) { ArmPositions position = ArmPoseConstants.GROUND_CONE_FLAT; if (targetPiece == GamePiece.CUBE) { // position = ArmPoseConstants.GROUND_CUBE; position = ArmPoseConstants.LONG_GROUND_CUBE; } return new ArmToPoseCommand(container.getArmSubsystem(), position) .alongWith(new SetIntakeCommand( container.getIntakeSubsystem(), () -> IntakeSubsystem.TargetIntakeStates.COLLECT, () -> targetPiece)); } /** * @param container RobotContainer to get subsystems */ private Command score(RobotContainer container, GamePiece piece) { return score(container, piece, false); } private Command score(RobotContainer container, GamePiece piece, boolean fastEject) { return new InstantCommand(() -> { container.getIntakeSubsystem().setTargetPiece(piece); container.getIntakeSubsystem().setTargetState(IntakeSubsystem.TargetIntakeStates.HOLDING); }) // .andThen(new ArmToPoseCommand(container.getArmSubsystem(), () -> position)) .andThen(new SetIntakeCommand( container.getIntakeSubsystem(), () -> fastEject ? IntakeSubsystem.TargetIntakeStates.FAST_EJECT : IntakeSubsystem.TargetIntakeStates.EJECT, () -> piece) .withTimeout(piece == GamePiece.CONE ? 0.4 : 0.2)); } private Command score(RobotContainer container, ArmPositions position, GamePiece piece) { return new InstantCommand(() -> { container.getIntakeSubsystem().setTargetPiece(piece); container.getIntakeSubsystem().setTargetState(IntakeSubsystem.TargetIntakeStates.HOLDING); }) .andThen(new ArmToPoseCommand(container.getArmSubsystem(), () -> position)) .andThen(new SetIntakeCommand( container.getIntakeSubsystem(), () -> IntakeSubsystem.TargetIntakeStates.EJECT, () -> piece) .withTimeout(piece == GamePiece.CONE ? 0.4 : 0.15)); } public boolean isAtScoringPose(RobotContainer container, PathPlannerTrajectory trajectory) {
package org.frcteam2910.c2023.util; public class PathChooser { public static final double EJECTION_DISTANCE = 0.4; // Enum for auto modes private enum AutonomousMode { DRIVE_STRAIGHT, BLUE_NO_BUMP_THREE_CUBE, RED_NO_BUMP_THREE_CUBE, NO_BUMP_TWO_CUBE_BALANCE, BLUE_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE, RED_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE, BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE, RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE, BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION, RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION, RED_BUMP_THREE_CUBE, BLUE_BUMP_THREE_CUBE, RED_CHEZYBUMP_THREE_CUBE, BLUE_CHEZYBUMP_THREE_CUBE, RED_CHEZYBUMP_TWO_CUBE, BLUE_CHEZYBUMP_TWO_CUBE, BUMP_TWO_AND_A_HALF_CUBE, BLUE_BUMP_TWO_CUBE, RED_BUMP_TWO_CUBE, MIDDLE_BALANCE, MIDDLE_UP_CUBE_BALANCE, MIDDLE_DOWN_CUBE_BALANCE, NO_BUMP_EXIT_COMMUNITY, BUMP_EXIT_COMMUNITY, } // Trajectories object private final PathTrajectories trajectories; // Chooser for autonomous mode private static final SendableChooser<AutonomousMode> autonomousModeChooser = new SendableChooser<>(); // Add options to chooser public PathChooser(PathTrajectories trajectories) { this.trajectories = trajectories; // autonomousModeChooser.addOption("Drive Straight", AutonomousMode.DRIVE_STRAIGHT); autonomousModeChooser.setDefaultOption( "Blue Yoshi No Bump 3 Cube Balance", AutonomousMode.BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE); autonomousModeChooser.setDefaultOption( "Red Yoshi No Bump 3 Cube Balance", AutonomousMode.RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE); autonomousModeChooser.addOption( "Blue Yoshi No Bump 3 Cube Substation", AutonomousMode.BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION); autonomousModeChooser.addOption( "Red Yoshi No Bump 3 Cube Substation", AutonomousMode.RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION); autonomousModeChooser.addOption("Blue No Bump 3 Cube", AutonomousMode.BLUE_NO_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red No Bump 3 Cube", AutonomousMode.RED_NO_BUMP_THREE_CUBE); // autonomousModeChooser.addOption("No Bump 1 Cube Balance", AutonomousMode.NO_BUMP_ONE_CUBE_BALANCE);; autonomousModeChooser.addOption( "Blue No Bump 2.5 Cube Balance", AutonomousMode.BLUE_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE); autonomousModeChooser.addOption( "Red No Bump 2.5 Cube Balance", AutonomousMode.RED_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE); // autonomousModeChooser.addOption("Bump 1.5 Cube", AutonomousMode.BUMP_ONE_AND_A_HALF_CUBE); // autonomousModeChooser.addOption("Chezy Blue Bump 3 Cube", AutonomousMode.BLUE_CHEZYBUMP_THREE_CUBE); // autonomousModeChooser.addOption("Chezy Red Bump 3 Cube", AutonomousMode.RED_CHEZYBUMP_THREE_CUBE); // autonomousModeChooser.addOption("Chezy Blue Bump 2 Cube", AutonomousMode.BLUE_CHEZYBUMP_TWO_CUBE); // autonomousModeChooser.addOption("Chezy Red Bump 2 Cube", AutonomousMode.RED_CHEZYBUMP_TWO_CUBE); autonomousModeChooser.addOption("Blue Bump 3 Cube", AutonomousMode.BLUE_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red Bump 3 Cube", AutonomousMode.RED_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red Bump 2 Cube", AutonomousMode.RED_BUMP_TWO_CUBE); autonomousModeChooser.addOption("Blue Bump 2 Cube", AutonomousMode.BLUE_BUMP_TWO_CUBE); // autonomousModeChooser.addOption("Middle No Bump Cube Balance", AutonomousMode.MIDDLE_UP_CUBE_BALANCE); // autonomousModeChooser.addOption("Middle Bump Cube Balance", AutonomousMode.MIDDLE_DOWN_CUBE_BALANCE); autonomousModeChooser.addOption("Middle Balance", AutonomousMode.MIDDLE_BALANCE); autonomousModeChooser.addOption("No Bump Exit Community", AutonomousMode.NO_BUMP_EXIT_COMMUNITY); autonomousModeChooser.addOption("Bump Exit Community", AutonomousMode.BUMP_EXIT_COMMUNITY); } public Command getDriveStraight(RobotContainer container) { return resetDrivetrainPose(container, trajectories.getDriveStraightPath()) .andThen(follow(container, trajectories.getDriveStraightPath())); } // Method for the preload score which happens before every sequence public Command getResetPoseAndPreloadScore(RobotContainer container, PathPlannerTrajectory trajectory) { return resetDrivetrainPose(container, trajectory) .alongWith(score(container, ArmPoseConstants.SECONDARY_L3_CONE, GamePiece.CONE)); } // Exit community from white starting position public Command getNoBumpExitCommunity(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getNoBumpExitCommunity())); command.addCommands(followAndHome(container, trajectories.getNoBumpExitCommunity())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // return follow(container, trajectories.getNoBumpExitCommunity()); } public Command getBumpExitCommunity(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getBumpExitCommunity())); command.addCommands(followAndHome(container, trajectories.getBumpExitCommunity())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // return follow(container, trajectories.getBumpExitCommunity()); } public Command getMiddleBalance(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands(resetDrivetrainPose(container, trajectories.getMiddleBalance())); command.addCommands(score(container, ArmPoseConstants.L3_CONE, GamePiece.CONE)); // command.addCommands(follow(container, trajectories.getMiddleBalance()).alongWith(new // SimultaneousHomeArmCommand(container.getArmSubsystem()))); // command.addCommands(new AutoBalanceOnChargeStationCommand(container.getDrivetrainSubsystem())); command.addCommands(followAndDoChargingStationAndHome(container, trajectories.getMiddleBalance())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // return follow(container, trajectories.getMiddleBalance()); } public Command getUpCubeMiddleBalance(RobotContainer container) { // SequentialCommandGroup command = new SequentialCommandGroup(); // command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getFourBlueToPrePlaceB())); // command.addCommands(followWhileIntaking( // container, trajectories.getFourBlueToPrePlaceB(), GamePiece.CUBE, 1, ArmPoseConstants.STOW, // false)); // command.addCommands(followThenScore( // container, // trajectories.getPrePlaceBToFiveBlue(), // GamePiece.CUBE, // ArmPoseConstants.STOW, // 1, // ArmPoseConstants.L3_CUBE)); // command.addCommands(followAndDoChargingStationAndHome(container, // trajectories.getFiveBlueToChargingStation())); // // command.addCommands(resetDrivetrainPose(container, trajectories.getFourBlueToPrePlaceB())); // // command.addCommands(follow(container, trajectories.getFourBlueToPrePlaceB())); // // command.addCommands(follow(container, trajectories.getPrePlaceBToFiveBlue())); // // command.addCommands(follow(container, trajectories.getFiveBlueToChargingStation())); // return command.finallyDo(interrupted -> // container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getFourBlueToPrePlaceB())); command.addCommands(followWhileIntaking( container, trajectories.getFourBlueToPrePlaceB(), GamePiece.CUBE, 1, ArmPoseConstants.STOW, false)); command.addCommands(followAndDoChargingStationAndHomeAndThenScore( container, trajectories.getMiddlePrePlaceBToChargingStation())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getDownCubeMiddleBalance(RobotContainer container) { // SequentialCommandGroup command = new SequentialCommandGroup(); // command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getSixGreenToPrePlaceC())); // command.addCommands(followWhileIntaking( // container, trajectories.getSixGreenToPrePlaceC(), GamePiece.CUBE, 1, ArmPoseConstants.STOW, // false)); // command.addCommands(followThenScore( // container, // trajectories.getPrePlaceCToFiveBlue(), // GamePiece.CUBE, // ArmPoseConstants.STOW, // 1, // ArmPoseConstants.L3_CUBE)); // command.addCommands(followAndDoChargingStationAndHome(container, // trajectories.getFiveBlueToChargingStation())); // // command.addCommands(resetDrivetrainPose(container, trajectories.getSixGreenToPrePlaceC())); // // command.addCommands(follow(container, trajectories.getSixGreenToPrePlaceC())); // // command.addCommands(follow(container, trajectories.getPrePlaceCToFiveBlue())); // // command.addCommands(follow(container, trajectories.getFiveBlueToChargingStation())); SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getSixGreenToPrePlaceC())); command.addCommands(followWhileIntaking( container, trajectories.getSixGreenToPrePlaceC(), GamePiece.CUBE, 1, ArmPoseConstants.STOW, false)); command.addCommands(followAndDoChargingStationAndHomeAndThenScore( container, trajectories.getMiddlePrePlaceCToChargingStation())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getNoBumpTwoAndAHalfCubeBalance(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getBlueOneWhiteToPrePlaceA())); command.addCommands(followWhileIntaking(container, trajectories.getBlueOneWhiteToPrePlaceA(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getBluePrePlaceAToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands(followWhileIntaking(container, trajectories.getBlueTwoWhiteToPrePlaceB(), GamePiece.CUBE)); // command.addCommands(follow(container, trajectories.getPrePlaceBToChargingStation())); // command.addCommands(new AutoBalanceOnChargeStationCommand(container.getDrivetrainSubsystem())); command.addCommands( followAndDoChargingStationAndHome(container, trajectories.getBluePrePlaceBToChargingStation())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // SequentialCommandGroup command = new SequentialCommandGroup(); // command.addCommands(follow(container, trajectories.getOneWhiteToPrePlaceA())); // command.addCommands(follow(container, trajectories.getPrePlaceAToTwoWhite())); // command.addCommands(follow(container, trajectories.getTwoWhiteToPrePlaceB())); // command.addCommands(follow(container, trajectories.getPrePlaceBToChargingStation())); // return command; } public Command getRedNoBumpTwoAndAHalfCubeBalance(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getRedOneWhiteToPrePlaceA())); command.addCommands(followWhileIntaking(container, trajectories.getRedOneWhiteToPrePlaceA(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getRedPrePlaceAToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands(followWhileIntaking(container, trajectories.getRedTwoWhiteToPrePlaceB(), GamePiece.CUBE)); command.addCommands( followAndDoChargingStationAndHome(container, trajectories.getRedPrePlaceBToChargingStation())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // SequentialCommandGroup command = new SequentialCommandGroup(); // command.addCommands(follow(container, trajectories.getOneWhiteToPrePlaceA())); // command.addCommands(follow(container, trajectories.getPrePlaceAToTwoWhite())); // command.addCommands(follow(container, trajectories.getTwoWhiteToPrePlaceB())); // command.addCommands(follow(container, trajectories.getPrePlaceBToChargingStation())); // return command; } public Command getNoBumpThreeCube(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getBlueOneWhiteToPrePlaceA())); command.addCommands(followWhileIntaking(container, trajectories.getBlueOneWhiteToPrePlaceA(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getBluePrePlaceAToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands(followWhileIntaking(container, trajectories.getBlueTwoWhiteToPrePlaceB(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getBluePrePlaceBToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L2_CUBE_BACK)); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // SequentialCommandGroup command = new SequentialCommandGroup(); // command.addCommands(follow(container, trajectories.getOneWhiteToPrePlaceA())); // command.addCommands(follow(container, trajectories.getPrePlaceAToTwoWhite())); // command.addCommands(follow(container, trajectories.getTwoWhiteToPrePlaceB())); // command.addCommands(follow(container, trajectories.getPrePlaceBToTwoWhite())); // return command; } public Command getRedNoBumpThreeCube(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getRedOneWhiteToPrePlaceA())); command.addCommands(followWhileIntaking( container, trajectories.getRedOneWhiteToPrePlaceA(), GamePiece.CUBE, 3, ArmPoseConstants.ARM_UP, false)); command.addCommands(followThenScore( container, trajectories.getRedPrePlaceAToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands(followWhileIntaking(container, trajectories.getRedTwoWhiteToPrePlaceB(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getRedPrePlaceBToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L2_CUBE_BACK)); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // SequentialCommandGroup command = new SequentialCommandGroup(); // command.addCommands(follow(container, trajectories.getOneWhiteToPrePlaceA())); // command.addCommands(follow(container, trajectories.getPrePlaceAToTwoWhite())); // command.addCommands(follow(container, trajectories.getTwoWhiteToPrePlaceB())); // command.addCommands(follow(container, trajectories.getPrePlaceBToTwoWhite())); // return command; } public Command getBumpThreeCube(RobotContainer container) { // SequentialCommandGroup command = new SequentialCommandGroup(); // command.addCommands(resetDrivetrainPose(container, trajectories.getNineOrangeToBumpOut())); // command.addCommands(follow(container, trajectories.getNineOrangeToBumpOut())); // command.addCommands(follow(container, trajectories.getBumpOut())); // command.addCommands(follow(container, trajectories.getBumpOutToPrePlaceD())); // command.addCommands(follow(container, trajectories.getPrePlaceDToBump())); // command.addCommands(follow(container, trajectories.getBumpToPrePlaceC())); // command.addCommands(follow(container, trajectories.getPrePlaceCToBumpReturn())); // command.addCommands(follow(container, trajectories.getBumpReturn())); // command.addCommands(follow(container, trajectories.getBumpReturnToEightOrange())); // return command.finallyDo(interrupted -> // container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( getResetPoseAndPreloadScore(container, trajectories.getBlueThreeBumpNineOrangeToPrePlaceD())); // command.addCommands(new InstantCommand(() -> // container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW))); // command.addCommands(follow(container, trajectories.getNineOrangeToBumpOut())); // command.addCommands(follow(container, trajectories.getBumpOut())); // command.addCommands(followWhileIntaking( // container, trajectories.getBumpOutToPrePlaceD(), GamePiece.CUBE, 1, ArmPoseConstants.STOW, // false)); command.addCommands(followWhileIntaking( container, trajectories.getBlueThreeBumpNineOrangeToPrePlaceD(), GamePiece.CUBE, 2.5, ArmPoseConstants.STOW, false)); // command.addCommands(followThenScore( // container, // trajectories.getPrePlaceDToBump(), // GamePiece.CUBE, // ArmPoseConstants.LONG_L1_CUBE_BACK, // 1.5, // ArmPoseConstants.STOW, true)); command.addCommands(follow(container, trajectories.getBluePrePlaceDToBump()) .alongWith(new WaitCommand(trajectories.getBluePrePlaceDToBump().getTotalTimeSeconds() - 1.5) .andThen(new ArmToPoseCommand( container.getArmSubsystem(), ArmPoseConstants.BUMP_LONG_L1_CUBE_BACK)))); command.addCommands(score(container, GamePiece.CUBE, true)); // command.addCommands(followWhileIntaking( // container, // trajectories.getBumpToPrePlaceC(), // GamePiece.CUBE, // trajectories.getBumpToPrePlaceC().getTotalTimeSeconds(), // ArmPoseConstants.GROUND_CUBE, // false)); command.addCommands( followWhileIntakingWithNoWait(container, trajectories.getBlueBumpToPrePlaceC(), GamePiece.CUBE)); // command.addCommands(follow(container, trajectories.getPrePlaceCToBumpReturn())); // command.addCommands(follow(container, trajectories.getBumpReturn())); // command.addCommands(followThenScore(container, trajectories.getBumpReturnToEightOrange(), GamePiece.CUBE, // ArmPoseConstants.L3_CUBE, 0.5, ArmPoseConstants.ARM_UP)); // command.addCommands(follow(container, trajectories.getThreeBumpPrePlaceCToEightOrange()) // .alongWith(new WaitCommand( // trajectories.getThreeBumpPrePlaceCToEightOrange().getTotalTimeSeconds() - 0.5) // .andThen(new ArmToPoseCommand(container.getArmSubsystem(), // ArmPoseConstants.L3_CUBE)))); // command.addCommands(score(container, GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getBluePrePlaceCToEightORange(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE, 2, ArmPoseConstants.STOW)); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getRedBumpThreeCube(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getRedNineOrangeToPrePlaceD())); command.addCommands(followWhileIntaking( container, trajectories.getRedNineOrangeToPrePlaceD(), GamePiece.CUBE, 2.5, ArmPoseConstants.STOW, false)); command.addCommands(follow(container, trajectories.getRedPrePlaceDToBump()) .alongWith(new WaitCommand(trajectories.getRedPrePlaceDToBump().getTotalTimeSeconds() - 1.5) .andThen(new ArmToPoseCommand( container.getArmSubsystem(), ArmPoseConstants.BUMP_LONG_L1_CUBE_BACK)))); command.addCommands(score(container, GamePiece.CUBE, true)); command.addCommands( followWhileIntakingWithNoWait(container, trajectories.getRedBumpToPrePlaceC(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getRedPrePlaceCToEightOrange(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE, 2, ArmPoseConstants.STOW)); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getBumpTwoAndAHalfCubeThenBalance(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getBlueNineOrangeToPrePlaceD())); command.addCommands(followWhileIntaking( container, trajectories.getBlueNineOrangeToPrePlaceD(), GamePiece.CUBE, 1.5, ArmPoseConstants.STOW, false)); command.addCommands(followThenScore( container, trajectories.getPrePlaceDToNineOrange(), GamePiece.CUBE, ArmPoseConstants.L1_CUBE_BACK, 1.25, ArmPoseConstants.ARM_UP)); command.addCommands(followWhileIntaking( container, trajectories.getNineOrangeToPrePlaceC(), GamePiece.CUBE, 1.5, ArmPoseConstants.STOW, false)); command.addCommands(followAndDoChargingStationAndHome(container, trajectories.getPrePlaceCToChargingStation())); // command.addCommands(resetDrivetrainPose(container, trajectories.getNineOrangeToPrePlaceD())); // command.addCommands(follow(container, trajectories.getNineOrangeToPrePlaceD())); // command.addCommands(follow(container, trajectories.getPrePlaceDToEightOrange())); // command.addCommands(follow(container, trajectories.getEightOrangeToPrePlaceC())); // command.addCommands(follow(container, trajectories.getPrePlaceCToEightOrange())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getBlueBumpTwoCube(RobotContainer container) { // SequentialCommandGroup command = new SequentialCommandGroup(); // command.addCommands(resetDrivetrainPose(container, trajectories.getNineOrangeToPrePlaceD())); // command.addCommands(follow(container, trajectories.getNineOrangeToPrePlaceD())); // command.addCommands(follow(container, trajectories.getPrePlaceDToEightOrange())); // return command; SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getBlueNineOrangeToPrePlaceD())); // command.addCommands(followThenScore( // container, // trajectories.getPrePlaceDToEightOrange(), // GamePiece.CUBE, // ArmPoseConstants.L3_CUBE, // 1, // ArmPoseConstants.ARM_UP)); command.addCommands(followWhileIntaking( container, trajectories.getBlueNineOrangeToPrePlaceD(), GamePiece.CUBE, 2.5, ArmPoseConstants.STOW, false)); command.addCommands(follow(container, trajectories.getPrePlaceDToEightOrange())); command.addCommands(new ArmToPoseCommand(container.getArmSubsystem(), ArmPoseConstants.L3_CUBE)); command.addCommands(score(container, GamePiece.CUBE)); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // command.addCommands(resetDrivetrainPose(container, trajectories.getNineOrangeToPrePlaceD())); // command.addCommands(follow(container, trajectories.getNineOrangeToPrePlaceD())); // command.addCommands(follow(container, trajectories.getPrePlaceDToEightOrange())); // return command; } public Command getRedBumpTwoCube(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getRedNineOrangeToPrePlaceD())); command.addCommands(followWhileIntaking( container, trajectories.getRedNineOrangeToPrePlaceD(), GamePiece.CUBE, 2.5, ArmPoseConstants.STOW, false)); command.addCommands(follow(container, trajectories.getRedPrePlaceDTo8Orange())); command.addCommands(new ArmToPoseCommand(container.getArmSubsystem(), ArmPoseConstants.L3_CUBE)); command.addCommands(score(container, GamePiece.CUBE)); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getChezyBlue3Bump(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getChezyBlueNineOrangeToPrePlaceD())); command.addCommands( followWhileIntaking(container, trajectories.getChezyBlueNineOrangeToPrePlaceD(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getChezyBluePrePlaceDToEightOrange(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands( followWhileIntaking(container, trajectories.getChezyBlueEightOrangeToPrePlaceC(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getChezyBluePrePlaceCToEightOrange(), GamePiece.CUBE, ArmPoseConstants.L2_CUBE_BACK)); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getChezyRed3Bump(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getChezyRedNineOrangeToPrePlaceD())); command.addCommands( followWhileIntaking(container, trajectories.getChezyRedNineOrangeToPrePlaceD(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getChezyRedPrePlaceDToEightOrange(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands( followWhileIntaking(container, trajectories.getChezyRedEightOrangeToPrePlaceC(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getChezyRedPrePlaceCToEightOrange(), GamePiece.CUBE, ArmPoseConstants.L2_CUBE_BACK)); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getChezyBlue2Bump(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getChezyBlueNineOrangeToPrePlaceD())); command.addCommands( followWhileIntaking(container, trajectories.getChezyBlueNineOrangeToPrePlaceD(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getChezyBluePrePlaceDToEightOrange(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands(new InstantCommand(() -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW))); command.addCommands(followAndHome(container, trajectories.getChezyBlueEightOrangeToExitCommunity())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getChezyRed2Bump(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getChezyRedNineOrangeToPrePlaceD())); command.addCommands( followWhileIntaking(container, trajectories.getChezyRedNineOrangeToPrePlaceD(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getChezyRedPrePlaceDToEightOrange(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands(new InstantCommand(() -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW))); command.addCommands(followAndHome(container, trajectories.getChezyRedEightOrangeToExitCommunity())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getRedLongIntakeNoBumpThreeCubeBalance(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getRedLongIntakeOneWhiteToPrePlaceA())); command.addCommands(followWhileIntaking( container, trajectories.getRedLongIntakeOneWhiteToPrePlaceA(), GamePiece.CUBE, 1.5, ArmPoseConstants.STOW, true)); command.addCommands(followThenScore( container, trajectories.getRedLongIntakePrePlaceAToOneWhite(), GamePiece.CUBE, ArmPoseConstants.LONG_L1_CUBE_BACK, 2.5, ArmPoseConstants.ARM_UP)); command.addCommands(followWhileIntaking( container, trajectories.getRedLongIntakeOneWhiteToPrePlaceB(), GamePiece.CUBE, 1.5, ArmPoseConstants.STOW, true)); command.addCommands(followThenScore( container, trajectories.getRedLongIntakePrePlaceBToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands( followAndDoChargingStationAndHome(container, trajectories.getRedTwoWhiteToChargingStation())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // SequentialCommandGroup commandGroup = new SequentialCommandGroup(); // commandGroup.addCommands(resetDrivetrainPose(container, // trajectories.getRedLongIntakeOneWhiteToPrePlaceA())); // commandGroup.addCommands(follow(container, trajectories.getRedLongIntakeOneWhiteToPrePlaceA())); // commandGroup.addCommands(follow(container, trajectories.getRedLongIntakePrePlaceAToTwoWhite())); // commandGroup.addCommands(follow(container, trajectories.getRedLongIntakeTwoWhiteToPrePlaceB())); // commandGroup.addCommands(follow(container, trajectories.getRedLongIntakePrePlaceBToTwoWhite())); // return commandGroup; } public Command getBlueLongIntakeNoBumpThreeCubeBalance(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands( getResetPoseAndPreloadScore(container, trajectories.getBlueLongIntakeOneWhiteToPrePlaceA())); command.addCommands(followWhileIntaking( container, trajectories.getBlueLongIntakeOneWhiteToPrePlaceA(), GamePiece.CUBE, 1.5, ArmPoseConstants.STOW, true)); command.addCommands(followThenScore( container, trajectories.getBlueLongIntakePrePlaceAToOneWhite(), GamePiece.CUBE, ArmPoseConstants.LONG_L1_CUBE_BACK, 2.5, ArmPoseConstants.ARM_UP)); command.addCommands(followWhileIntaking( container, trajectories.getBlueLongIntakeOneWhiteToPrePlaceB(), GamePiece.CUBE, 1.5, ArmPoseConstants.STOW, true)); command.addCommands(followThenScore( container, trajectories.getBlueLongIntakePrePlaceBToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands( followAndDoChargingStationAndHome(container, trajectories.getBlueTwoWhiteToChargingStation())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // SequentialCommandGroup commandGroup = new SequentialCommandGroup(); // commandGroup.addCommands(resetDrivetrainPose(container, // trajectories.getBlueLongIntakeOneWhiteToPrePlaceA())); // commandGroup.addCommands(follow(container, trajectories.getBlueLongIntakeOneWhiteToPrePlaceA())); // commandGroup.addCommands(follow(container, trajectories.getBlueLongIntakePrePlaceAToTwoWhite())); // commandGroup.addCommands(follow(container, trajectories.getBlueLongIntakeTwoWhiteToPrePlaceB())); // commandGroup.addCommands(follow(container, trajectories.getBlueLongIntakePrePlaceBToTwoWhite())); // return commandGroup; } public Command getRedLongIntakeNoBumpThreeCubeSubstation(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getRedLongIntakeOneWhiteToPrePlaceA())); command.addCommands(followWhileIntaking( container, trajectories.getRedLongIntakeOneWhiteToPrePlaceA(), GamePiece.CUBE, 1.5, ArmPoseConstants.STOW, true)); command.addCommands(followThenScore( container, trajectories.getRedLongIntakePrePlaceAToOneWhite(), GamePiece.CUBE, ArmPoseConstants.LONG_L1_CUBE_BACK, 2.5, ArmPoseConstants.ARM_UP)); command.addCommands(followWhileIntaking( container, trajectories.getRedLongIntakeOneWhiteToPrePlaceB(), GamePiece.CUBE, 1.5, ArmPoseConstants.STOW, true)); command.addCommands(followThenScore( container, trajectories.getRedLongIntakePrePlaceBToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands(followAndHome(container, trajectories.getRedTwoWhiteToSubstation())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getBlueLongIntakeNoBumpThreeCubeSubstation(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands( getResetPoseAndPreloadScore(container, trajectories.getBlueLongIntakeOneWhiteToPrePlaceA())); command.addCommands(followWhileIntaking( container, trajectories.getBlueLongIntakeOneWhiteToPrePlaceA(), GamePiece.CUBE, 1.5, ArmPoseConstants.STOW, true)); command.addCommands(followThenScore( container, trajectories.getBlueLongIntakePrePlaceAToOneWhite(), GamePiece.CUBE, ArmPoseConstants.LONG_L1_CUBE_BACK, 2.5, ArmPoseConstants.ARM_UP)); command.addCommands(followWhileIntaking( container, trajectories.getBlueLongIntakeOneWhiteToPrePlaceB(), GamePiece.CUBE, 1.5, ArmPoseConstants.STOW, true)); command.addCommands(followThenScore( container, trajectories.getBlueLongIntakePrePlaceBToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); command.addCommands(followAndHome(container, trajectories.getBlueTwoWhiteToSubstation())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); } public Command getNoBumpTwoCubeBalance(RobotContainer container) { SequentialCommandGroup command = new SequentialCommandGroup(); command.addCommands( new InstantCommand(() -> container.getIntakeSubsystem().setTargetPiece(GamePiece.CONE))); command.addCommands(getResetPoseAndPreloadScore(container, trajectories.getBlueOneWhiteToPrePlaceA())); command.addCommands(followWhileIntaking(container, trajectories.getBlueOneWhiteToPrePlaceA(), GamePiece.CUBE)); command.addCommands(followThenScore( container, trajectories.getBluePrePlaceAToTwoWhite(), GamePiece.CUBE, ArmPoseConstants.L3_CUBE)); // command.addCommands(follow(container, trajectories.getTwoWhiteToChargingStation())); // command.addCommands(new AutoBalanceOnChargeStationCommand(container.getDrivetrainSubsystem())); command.addCommands( followAndDoChargingStationAndHome(container, trajectories.getRedTwoWhiteToChargingStation())); return command.finallyDo(interrupted -> container.getArmSubsystem().setTargetPose(ArmPoseConstants.STOW)); // SequentialCommandGroup command = new SequentialCommandGroup(); // command.addCommands(follow(container, trajectories.getOneWhiteToPrePlaceA())); // command.addCommands(follow(container, trajectories.getPrePlaceAToTwoWhite())); // command.addCommands(follow(container, trajectories.getTwoWhiteToChargingStation())); // return command; } /** * @param container RobotContainer to get subsystems * @param trajectory Trajectory to follow */ private Command follow(RobotContainer container, PathPlannerTrajectory trajectory) { return new FollowPathCommand(container.getDrivetrainSubsystem(), trajectory); } private Command followWithTimeout(RobotContainer container, PathPlannerTrajectory trajectory, double timeout) { return new FollowPathCommand(container.getDrivetrainSubsystem(), trajectory).withTimeout(timeout); } /** * @param container RobotContainer to get subsystems * @param trajectory Trajectory to follow * @param targetPiece Piece to intake */ private Command followWhileIntakingWithArmHoming( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece targetPiece) { SequentialCommandGroup followWhileIntakingAndHomingCommand = new SequentialCommandGroup(); Timer timer = new Timer(); followWhileIntakingAndHomingCommand.addCommands(new InstantCommand((timer::restart))); followWhileIntakingAndHomingCommand.addCommands( new ArmToPoseCommand(container.getArmSubsystem(), ArmPoseConstants.ARM_UP)); followWhileIntakingAndHomingCommand.addCommands( new ArmToPoseCommand(container.getArmSubsystem(), ArmPoseConstants.STOW)); followWhileIntakingAndHomingCommand.addCommands(new SimultaneousHomeArmCommand(container.getArmSubsystem())); followWhileIntakingAndHomingCommand.addCommands(new InstantCommand(timer::stop)); followWhileIntakingAndHomingCommand.addCommands(intake(container, targetPiece)); return follow(container, trajectory) .raceWith(followWhileIntakingAndHomingCommand) .andThen(new StowArmCommand(container.getArmSubsystem())); } private Command followAndHome(RobotContainer container, PathPlannerTrajectory trajectory) { SequentialCommandGroup followAndHomeCommand = new SequentialCommandGroup(); // followAndHomeCommand.addCommands(new ArmToPoseCommand(container.getArmSubsystem(), ArmPoseConstants.ARM_UP)); followAndHomeCommand.addCommands(new ArmToPoseCommand(container.getArmSubsystem(), ArmPoseConstants.STOW)); followAndHomeCommand.addCommands(new SimultaneousHomeArmCommand(container.getArmSubsystem())); return follow(container, trajectory).alongWith(followAndHomeCommand); } private Command followAndDoChargingStationAndHome(RobotContainer container, PathPlannerTrajectory trajectory) { SequentialCommandGroup homeArmCommand = new SequentialCommandGroup(); homeArmCommand.addCommands(new ArmToPoseCommand(container.getArmSubsystem(), ArmPoseConstants.STOW)); homeArmCommand.addCommands(new SimultaneousHomeArmCommand(container.getArmSubsystem())); SequentialCommandGroup chargingStationCommand = new SequentialCommandGroup(); chargingStationCommand.addCommands(follow(container, trajectory)); chargingStationCommand.addCommands(new AutoBalanceOnChargeStationCommand(container.getDrivetrainSubsystem())); return chargingStationCommand.alongWith(homeArmCommand); } private Command followAndDoChargingStationAndHomeAndThenScore( RobotContainer container, PathPlannerTrajectory trajectory) { SequentialCommandGroup homeArmCommand = new SequentialCommandGroup(); homeArmCommand.addCommands(new ArmToPoseCommand(container.getArmSubsystem(), ArmPoseConstants.STOW)); homeArmCommand.addCommands(new SimultaneousHomeArmCommand(container.getArmSubsystem())); SequentialCommandGroup chargingStationCommand = new SequentialCommandGroup(); chargingStationCommand.addCommands(follow(container, trajectory)); chargingStationCommand.addCommands(score(container, ArmPoseConstants.L1_CUBE_BACK, GamePiece.CUBE)); chargingStationCommand.addCommands(new AutoBalanceOnChargeStationCommand(container.getDrivetrainSubsystem())); return chargingStationCommand.alongWith(homeArmCommand); } /** * @param container RobotContainer to get subsystems * @param trajectory Trajectory to follow * @param targetPiece Piece to intake */ private Command followWhileIntaking( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece targetPiece, double waitTime, ArmPositions travelState, boolean longIntake) { ArmPositions position = ArmPoseConstants.GROUND_CONE_FLAT; if (targetPiece == GamePiece.CUBE) { position = longIntake ? ArmPoseConstants.LONG_GROUND_CUBE : ArmPoseConstants.GROUND_CUBE; } return follow(container, trajectory) .alongWith(new InstantCommand(() -> container.getArmSubsystem().setTargetPose(travelState))) .alongWith(new WaitCommand(trajectory.getTotalTimeSeconds() - waitTime) .andThen(new ArmToPoseCommand(container.getArmSubsystem(), position))) .raceWith(new SetIntakeCommand( container.getIntakeSubsystem(), () -> IntakeSubsystem.TargetIntakeStates.COLLECT, () -> targetPiece)) .andThen(new StowArmCommand(container.getArmSubsystem())); } private Command followWhileIntakingWithNoWait( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece targetPiece) { return follow(container, trajectory) .alongWith(new ArmToPoseCommand(container.getArmSubsystem(), ArmPoseConstants.GROUND_CUBE)) .raceWith(new SetIntakeCommand( container.getIntakeSubsystem(), () -> IntakeSubsystem.TargetIntakeStates.COLLECT, () -> targetPiece)); } private Command followWhileIntaking( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece targetPiece) { return followWhileIntaking(container, trajectory, targetPiece, 2, ArmPoseConstants.ARM_UP, false); } /** * @param container RobotContainer to get subsystems * @param trajectory Trajectory to follow * @param scoringPiece Piece to score */ private Command followThenScore( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece scoringPiece, ArmPositions position) { return followThenScore(container, trajectory, scoringPiece, position, 2, ArmPoseConstants.ARM_UP, false); } private Command followThenScore( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece scoringPiece, ArmPositions position, double waitTime, ArmPositions travelState) { return followThenScore(container, trajectory, scoringPiece, position, waitTime, travelState, false); } private Command followThenScore( RobotContainer container, PathPlannerTrajectory trajectory, GamePiece scoringPiece, ArmPositions position, double waitTime, ArmPositions travelState, boolean fastEject) { SequentialCommandGroup armMotionCommand = new SequentialCommandGroup(); Timer timer = new Timer(); armMotionCommand.addCommands(new InstantCommand(timer::restart)); // Restart timer armMotionCommand.addCommands(new ArmToPoseCommand(container.getArmSubsystem(), travelState)); // Put the arm up armMotionCommand.addCommands(new InstantCommand( timer::stop)); // Stop the timer such that it now stores the amount of time the arm command took armMotionCommand.addCommands(new ProxyCommand(() -> new WaitCommand(trajectory.getTotalTimeSeconds() - timer.get() - waitTime))); // Wait for the remaining time in the path minus a one second wait time armMotionCommand.addCommands(new ArmToPoseCommand( container.getArmSubsystem(), position)); // Move the arm to the scoring pose as we are one second out from hitting the drivetrain SequentialCommandGroup intakeCommand = new SequentialCommandGroup(); intakeCommand.addCommands(new WaitUntilCommand(() -> isAtScoringPose(container, trajectory))); intakeCommand.addCommands(score(container, scoringPiece, fastEject)); return follow(container, trajectory).alongWith(armMotionCommand).alongWith(intakeCommand); } /** * @param container RobotContainer to get subsystems * @param targetPiece Piece to intake */ private Command intake(RobotContainer container, GamePiece targetPiece) { ArmPositions position = ArmPoseConstants.GROUND_CONE_FLAT; if (targetPiece == GamePiece.CUBE) { // position = ArmPoseConstants.GROUND_CUBE; position = ArmPoseConstants.LONG_GROUND_CUBE; } return new ArmToPoseCommand(container.getArmSubsystem(), position) .alongWith(new SetIntakeCommand( container.getIntakeSubsystem(), () -> IntakeSubsystem.TargetIntakeStates.COLLECT, () -> targetPiece)); } /** * @param container RobotContainer to get subsystems */ private Command score(RobotContainer container, GamePiece piece) { return score(container, piece, false); } private Command score(RobotContainer container, GamePiece piece, boolean fastEject) { return new InstantCommand(() -> { container.getIntakeSubsystem().setTargetPiece(piece); container.getIntakeSubsystem().setTargetState(IntakeSubsystem.TargetIntakeStates.HOLDING); }) // .andThen(new ArmToPoseCommand(container.getArmSubsystem(), () -> position)) .andThen(new SetIntakeCommand( container.getIntakeSubsystem(), () -> fastEject ? IntakeSubsystem.TargetIntakeStates.FAST_EJECT : IntakeSubsystem.TargetIntakeStates.EJECT, () -> piece) .withTimeout(piece == GamePiece.CONE ? 0.4 : 0.2)); } private Command score(RobotContainer container, ArmPositions position, GamePiece piece) { return new InstantCommand(() -> { container.getIntakeSubsystem().setTargetPiece(piece); container.getIntakeSubsystem().setTargetState(IntakeSubsystem.TargetIntakeStates.HOLDING); }) .andThen(new ArmToPoseCommand(container.getArmSubsystem(), () -> position)) .andThen(new SetIntakeCommand( container.getIntakeSubsystem(), () -> IntakeSubsystem.TargetIntakeStates.EJECT, () -> piece) .withTimeout(piece == GamePiece.CONE ? 0.4 : 0.15)); } public boolean isAtScoringPose(RobotContainer container, PathPlannerTrajectory trajectory) {
DrivetrainSubsystem drivetrainSubsystem = container.getDrivetrainSubsystem();
1
2023-11-03 02:12:12+00:00
24k
dlsc-software-consulting-gmbh/PhoneNumberFX
phonenumberfx-demo/src/main/java/com/dlsc/phonenumberfx/demo/PhoneNumberFieldSamples.java
[ { "identifier": "PhoneNumberField", "path": "phonenumberfx/src/main/java/com/dlsc/phonenumberfx/PhoneNumberField.java", "snippet": "public class PhoneNumberField extends CustomTextField {\n\n private static final Map<Country, Image> FLAG_IMAGES = new HashMap<>();\n\n static {\n for (Country...
import com.dlsc.phonenumberfx.PhoneNumberField; import com.dlsc.phonenumberfx.PhoneNumberField.Country; import com.dlsc.phonenumberfx.PhoneNumberLabel; import com.google.i18n.phonenumbers.PhoneNumberUtil; import javafx.beans.binding.Bindings; import javafx.beans.value.ObservableValue; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import java.util.function.Function;
19,308
package com.dlsc.phonenumberfx.demo; public final class PhoneNumberFieldSamples { private static final Function<Object, String> COUNTRY_CODE_CONVERTER = c -> { if (c == null) { return null; } Country code = (Country) c; return "(" + code.phonePrefix() + ")" + code; }; private PhoneNumberFieldSamples() { super(); } public static Node buildDefaultEmptySample() { PhoneNumberField field = new PhoneNumberField(); String title = "Default Settings"; String description = "A control without any changes to its properties."; return buildSample(title, description, field); } public static Node buildDefaultPrefilledSample() { PhoneNumberField field = new PhoneNumberField(); field.setText("+573003767182"); String title = "Initial Value"; String description = "A control with default settings and a value set through code."; return buildSample(title, description, field); } public static Node buildCustomAvailableCountriesSample() { PhoneNumberField field = new PhoneNumberField(); field.getAvailableCountries().setAll( Country.COLOMBIA, Country.GERMANY, Country.UNITED_STATES, Country.UNITED_KINGDOM, Country.SWITZERLAND); String title = "Available Countries (Customized)"; String description = "A control with modified list of available countries."; return buildSample(title, description, field); } public static Node buildPreferredCountriesSample() { PhoneNumberField field = new PhoneNumberField(); field.getPreferredCountries().setAll( Country.SWITZERLAND, Country.GERMANY, Country.UNITED_KINGDOM); String title = "Preferred Countries"; String description = "Preferred countries all shown at the top of the list always."; return buildSample(title, description, field); } public static Node buildDisabledCountrySelectorSample() { PhoneNumberField field = new PhoneNumberField(); field.setSelectedCountry(Country.GERMANY); field.setDisableCountryDropdown(true); field.setExpectedPhoneNumberType(PhoneNumberUtil.PhoneNumberType.PERSONAL_NUMBER); String title = "Disabled Country Selector"; String description = "Disables the country selector button so it forces the control to keep always the same country."; return buildSample(title, description, field); } public static Node buildExpectedPhoneNumberTypeSample() { PhoneNumberField field = new PhoneNumberField(); field.setExpectedPhoneNumberType(PhoneNumberUtil.PhoneNumberType.MOBILE); field.setSelectedCountry(Country.COLOMBIA); String title = "Fixed Phone Number Type (MOBILE)"; String description = "Establish an expected phone number type, performs validations against the type and shows an example of the phone number."; return buildSample(title, description, field); } public static Node buildSample(String title, String description, PhoneNumberField field) { Label titleLabel = new Label(title); titleLabel.setStyle("-fx-font-weight: bold; -fx-font-size: 1.4em;"); Label descriptionLabel = new Label(description); descriptionLabel.setWrapText(true); VBox leftBox = new VBox(20); leftBox.setAlignment(Pos.CENTER_LEFT); leftBox.getChildren().addAll(titleLabel, descriptionLabel, field); leftBox.setPrefWidth(400); ColumnConstraints column1 = new ColumnConstraints(); column1.setPercentWidth(35); ColumnConstraints column2 = new ColumnConstraints(); column2.setPercentWidth(65); GridPane rightBox = new GridPane(); rightBox.setHgap(10); rightBox.setVgap(10); rightBox.getColumnConstraints().addAll(column1, column2); rightBox.setPrefWidth(400);
package com.dlsc.phonenumberfx.demo; public final class PhoneNumberFieldSamples { private static final Function<Object, String> COUNTRY_CODE_CONVERTER = c -> { if (c == null) { return null; } Country code = (Country) c; return "(" + code.phonePrefix() + ")" + code; }; private PhoneNumberFieldSamples() { super(); } public static Node buildDefaultEmptySample() { PhoneNumberField field = new PhoneNumberField(); String title = "Default Settings"; String description = "A control without any changes to its properties."; return buildSample(title, description, field); } public static Node buildDefaultPrefilledSample() { PhoneNumberField field = new PhoneNumberField(); field.setText("+573003767182"); String title = "Initial Value"; String description = "A control with default settings and a value set through code."; return buildSample(title, description, field); } public static Node buildCustomAvailableCountriesSample() { PhoneNumberField field = new PhoneNumberField(); field.getAvailableCountries().setAll( Country.COLOMBIA, Country.GERMANY, Country.UNITED_STATES, Country.UNITED_KINGDOM, Country.SWITZERLAND); String title = "Available Countries (Customized)"; String description = "A control with modified list of available countries."; return buildSample(title, description, field); } public static Node buildPreferredCountriesSample() { PhoneNumberField field = new PhoneNumberField(); field.getPreferredCountries().setAll( Country.SWITZERLAND, Country.GERMANY, Country.UNITED_KINGDOM); String title = "Preferred Countries"; String description = "Preferred countries all shown at the top of the list always."; return buildSample(title, description, field); } public static Node buildDisabledCountrySelectorSample() { PhoneNumberField field = new PhoneNumberField(); field.setSelectedCountry(Country.GERMANY); field.setDisableCountryDropdown(true); field.setExpectedPhoneNumberType(PhoneNumberUtil.PhoneNumberType.PERSONAL_NUMBER); String title = "Disabled Country Selector"; String description = "Disables the country selector button so it forces the control to keep always the same country."; return buildSample(title, description, field); } public static Node buildExpectedPhoneNumberTypeSample() { PhoneNumberField field = new PhoneNumberField(); field.setExpectedPhoneNumberType(PhoneNumberUtil.PhoneNumberType.MOBILE); field.setSelectedCountry(Country.COLOMBIA); String title = "Fixed Phone Number Type (MOBILE)"; String description = "Establish an expected phone number type, performs validations against the type and shows an example of the phone number."; return buildSample(title, description, field); } public static Node buildSample(String title, String description, PhoneNumberField field) { Label titleLabel = new Label(title); titleLabel.setStyle("-fx-font-weight: bold; -fx-font-size: 1.4em;"); Label descriptionLabel = new Label(description); descriptionLabel.setWrapText(true); VBox leftBox = new VBox(20); leftBox.setAlignment(Pos.CENTER_LEFT); leftBox.getChildren().addAll(titleLabel, descriptionLabel, field); leftBox.setPrefWidth(400); ColumnConstraints column1 = new ColumnConstraints(); column1.setPercentWidth(35); ColumnConstraints column2 = new ColumnConstraints(); column2.setPercentWidth(65); GridPane rightBox = new GridPane(); rightBox.setHgap(10); rightBox.setVgap(10); rightBox.getColumnConstraints().addAll(column1, column2); rightBox.setPrefWidth(400);
PhoneNumberLabel phoneNumberLabel = new PhoneNumberLabel();
2
2023-11-09 16:10:00+00:00
24k
estkme-group/InfiLPA
core/src/main/java/com/infineon/esim/lpa/core/es9plus/messages/response/AuthenticateClientResp.java
[ { "identifier": "Certificate", "path": "messages/src/main/java/com/gsma/sgp/messages/pkix1explicit88/Certificate.java", "snippet": "public class Certificate implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic static final BerTag tag = new BerTag(BerTag.UN...
import com.gsma.sgp.messages.rspdefinitions.StoreMetadataRequest; import com.gsma.sgp.messages.rspdefinitions.TransactionId; import com.infineon.esim.lpa.core.es9plus.messages.response.base.ResponseMsgBody; import com.infineon.esim.messages.Ber; import com.infineon.esim.util.Bytes; import androidx.annotation.NonNull; import com.beanit.jasn1.ber.types.BerOctetString; import com.gsma.sgp.messages.pkix1explicit88.Certificate; import com.gsma.sgp.messages.rspdefinitions.AuthenticateClientOk; import com.gsma.sgp.messages.rspdefinitions.AuthenticateClientResponseEs9; import com.gsma.sgp.messages.rspdefinitions.SmdpSigned2;
19,649
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.es9plus.messages.response; public class AuthenticateClientResp extends ResponseMsgBody { private String transactionId; private String profileMetadata; private String smdpSigned2; private String smdpSignature2; private String smdpCertificate; public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public String getProfileMetadata() { return profileMetadata; } public void setProfileMetadata(String profileMetadata) { this.profileMetadata = profileMetadata; } public String getSmdpSigned2() { return smdpSigned2; } public void setSmdpSigned2(String smdpSigned2) { this.smdpSigned2 = smdpSigned2; } public String getSmdpSignature2() { return smdpSignature2; } public void setSmdpSignature2(String smdpSignature2) { this.smdpSignature2 = smdpSignature2; } public String getSmdpCertificate() { return smdpCertificate; } public void setSmdpCertificate(String smdpCertificate) { this.smdpCertificate = smdpCertificate; } public AuthenticateClientResponseEs9 getResponse() { AuthenticateClientOk authenticateClientOk = new AuthenticateClientOk(); authenticateClientOk.setTransactionId(this.getTransactionIdParsed()); authenticateClientOk.setProfileMetaData(this.getProfileMetadataParsed()); authenticateClientOk.setSmdpSigned2(this.getSmdpSigned2Parsed()); authenticateClientOk.setSmdpSignature2(this.getSmdpSignature2Parsed()); authenticateClientOk.setSmdpCertificate(this.getSmdpCertificateParsed()); AuthenticateClientResponseEs9 authenticateClientResponseEs9 = new AuthenticateClientResponseEs9(); authenticateClientResponseEs9.setAuthenticateClientOk(authenticateClientOk); return authenticateClientResponseEs9; } public void setResponse(AuthenticateClientResponseEs9 authenticateClientResponseEs9) { TransactionId transactionID = authenticateClientResponseEs9.getAuthenticateClientOk().getTransactionId();
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.es9plus.messages.response; public class AuthenticateClientResp extends ResponseMsgBody { private String transactionId; private String profileMetadata; private String smdpSigned2; private String smdpSignature2; private String smdpCertificate; public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public String getProfileMetadata() { return profileMetadata; } public void setProfileMetadata(String profileMetadata) { this.profileMetadata = profileMetadata; } public String getSmdpSigned2() { return smdpSigned2; } public void setSmdpSigned2(String smdpSigned2) { this.smdpSigned2 = smdpSigned2; } public String getSmdpSignature2() { return smdpSignature2; } public void setSmdpSignature2(String smdpSignature2) { this.smdpSignature2 = smdpSignature2; } public String getSmdpCertificate() { return smdpCertificate; } public void setSmdpCertificate(String smdpCertificate) { this.smdpCertificate = smdpCertificate; } public AuthenticateClientResponseEs9 getResponse() { AuthenticateClientOk authenticateClientOk = new AuthenticateClientOk(); authenticateClientOk.setTransactionId(this.getTransactionIdParsed()); authenticateClientOk.setProfileMetaData(this.getProfileMetadataParsed()); authenticateClientOk.setSmdpSigned2(this.getSmdpSigned2Parsed()); authenticateClientOk.setSmdpSignature2(this.getSmdpSignature2Parsed()); authenticateClientOk.setSmdpCertificate(this.getSmdpCertificateParsed()); AuthenticateClientResponseEs9 authenticateClientResponseEs9 = new AuthenticateClientResponseEs9(); authenticateClientResponseEs9.setAuthenticateClientOk(authenticateClientOk); return authenticateClientResponseEs9; } public void setResponse(AuthenticateClientResponseEs9 authenticateClientResponseEs9) { TransactionId transactionID = authenticateClientResponseEs9.getAuthenticateClientOk().getTransactionId();
StoreMetadataRequest profileMetadata = authenticateClientResponseEs9.getAuthenticateClientOk().getProfileMetaData();
4
2023-11-06 02:41:13+00:00
24k
CxyJerry/pilipala
src/main/java/com/jerry/pilipala/interfaces/web/FileController.java
[ { "identifier": "UploadVO", "path": "src/main/java/com/jerry/pilipala/application/vo/vod/UploadVO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class UploadVO {\n private String token;\n private String filename;\n}" }, { "identifier": "FileService", "path": "src/main/java/...
import cn.dev33.satoken.annotation.SaCheckPermission; import com.jerry.pilipala.application.vo.vod.UploadVO; import com.jerry.pilipala.domain.vod.service.FileService; import com.jerry.pilipala.domain.vod.service.VodService; import com.jerry.pilipala.domain.vod.service.impl.FileServiceImpl; import com.jerry.pilipala.domain.vod.service.impl.VodServiceImpl; import com.jerry.pilipala.infrastructure.annotations.RateLimiter; import com.jerry.pilipala.infrastructure.common.response.CommonResponse; import com.jerry.pilipala.infrastructure.config.Qiniu; import com.jerry.pilipala.infrastructure.enums.LimitType; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.InputStreamResource; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull;
15,239
package com.jerry.pilipala.interfaces.web; @Slf4j @RestController @RequestMapping("/file") public class FileController { private final FileService fileService; private final VodService vodService; private final Qiniu qiniu; private final HttpServletResponse response; public FileController(FileServiceImpl fileService, VodServiceImpl vodService, Qiniu qiniu, HttpServletResponse response) { this.fileService = fileService; this.vodService = vodService; this.qiniu = qiniu; this.response = response; } /** * 正式上传文件 * * @param cid 预上传生产的稿件id * @return success */ @ApiOperation("上传视频文件") @SaCheckPermission("post-vod") @RateLimiter(key = "vod-limit:upload", count = 3, message = "上传速度过快,请稍后再试试吧", limitType = LimitType.IP) @GetMapping("/upload") public CommonResponse<?> upload(@RequestParam("cid") @NotNull(message = "稿件ID不得为空") Long cid) {
package com.jerry.pilipala.interfaces.web; @Slf4j @RestController @RequestMapping("/file") public class FileController { private final FileService fileService; private final VodService vodService; private final Qiniu qiniu; private final HttpServletResponse response; public FileController(FileServiceImpl fileService, VodServiceImpl vodService, Qiniu qiniu, HttpServletResponse response) { this.fileService = fileService; this.vodService = vodService; this.qiniu = qiniu; this.response = response; } /** * 正式上传文件 * * @param cid 预上传生产的稿件id * @return success */ @ApiOperation("上传视频文件") @SaCheckPermission("post-vod") @RateLimiter(key = "vod-limit:upload", count = 3, message = "上传速度过快,请稍后再试试吧", limitType = LimitType.IP) @GetMapping("/upload") public CommonResponse<?> upload(@RequestParam("cid") @NotNull(message = "稿件ID不得为空") Long cid) {
UploadVO uploadVO = fileService.uploadVideo(cid);
0
2023-11-03 10:05:02+00:00
24k
giteecode/oaSystemPublic
src/main/java/cn/gson/oasys/controller/inform/InformManageController.java
[ { "identifier": "BindingResultVOUtil", "path": "src/main/java/cn/gson/oasys/common/formValid/BindingResultVOUtil.java", "snippet": "public class BindingResultVOUtil {\n /**\n * 表单验证,返回形式ResultVO\n *\n * @param br\n * @return\n */\n public static ResultVO hasErrors(BindingResult...
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.gson.oasys.common.formValid.BindingResultVOUtil; import cn.gson.oasys.common.formValid.MapToList; import cn.gson.oasys.common.formValid.ResultEnum; import cn.gson.oasys.common.formValid.ResultVO; import cn.gson.oasys.mappers.NoticeMapper; import cn.gson.oasys.model.dao.informdao.InformDao; import cn.gson.oasys.model.dao.informdao.InformRelationDao; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.notice.NoticeUserRelation; import cn.gson.oasys.model.entity.notice.NoticeVO; import cn.gson.oasys.model.entity.notice.NoticesList; import cn.gson.oasys.model.entity.system.SystemMenu; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User; import cn.gson.oasys.services.inform.InformRelationService; import cn.gson.oasys.services.inform.InformService;
14,574
if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId"); List<SystemTypeList> typeList = typeDao.findByTypeModel("inform"); List<SystemStatusList> statusList = statusDao.findByStatusModel("inform"); if (!StringUtils.isEmpty(req.getAttribute("errormess"))) { req.setAttribute("errormess", req.getAttribute("errormess")); } if (!StringUtils.isEmpty(req.getAttribute("success"))) { req.setAttribute("success", "数据保存成功"); } req.setAttribute("typeList", typeList); req.setAttribute("statusList", statusList); if (!StringUtils.isEmpty(req.getParameter("id"))) { Long noticeId = Long.parseLong(req.getParameter("id")); NoticesList noticeList = informDao.findOne(noticeId); model.addAttribute("noticeList", noticeList); model.addAttribute("typeName", typeDao.findOne(noticeList.getTypeId()).getTypeName()); model.addAttribute("statusName", statusDao.findOne(noticeList.getStatusId()).getStatusName()); session.setAttribute("noticeId", noticeId); } return "inform/informedit"; } /** * 详细通知显示 */ @RequestMapping("informshow") public String informShow(HttpServletRequest req, Model model) { Long noticeId = Long.parseLong(req.getParameter("id")); if (!StringUtils.isEmpty(req.getParameter("read"))) { if (("0").equals(req.getParameter("read"))) { Long relationId = Long.parseLong(req.getParameter("relationid")); NoticeUserRelation relation = informrelationDao.findOne(relationId); relation.setRead(true); informrelationservice.save(relation); } } NoticesList notice = informDao.findOne(noticeId); User user = uDao.findOne(notice.getUserId()); model.addAttribute("notice", notice); model.addAttribute("userName", user.getUserName()); return "inform/informshow"; } /** * 系统管理表单验证 * * @param req * @param menu * @param br * 后台校验表单数据,不通过则回填数据,显示错误信息;通过则直接执行业务,例如新增、编辑等; * @return */ @RequestMapping("informcheck") public String testMess(HttpServletRequest req, @Valid NoticesList menu, BindingResult br) { HttpSession session = req.getSession(); Long menuId = null; req.setAttribute("menuObj", menu); Long userId = Long.parseLong(session.getAttribute("userId") + ""); menu.setUserId(userId); // 这里返回ResultVO对象,如果校验通过,ResultEnum.SUCCESS.getCode()返回的值为200;否则就是没有通过; ResultVO res = BindingResultVOUtil.hasErrors(br); // 校验失败 if (!ResultEnum.SUCCESS.getCode().equals(res.getCode())) {
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){ List<User> users=uDao.findByFatherId(userId); NoticesList nl=informDao.findOne(noticeId); List<NoticeUserRelation> nurs=new ArrayList<>(); for (User user : users) { nurs.add(new NoticeUserRelation(nl, user, false)); } informrelationservice.saves(nurs); return "redirect:/infromlist"; } // demo // @RequestMapping("cccc") // public @ResponseBody Page<NoticesList> ddd(@RequestParam(value = "page", defaultValue = "0") int page, // @RequestParam(value = "size", defaultValue = "10") int size, // @RequestParam(value = "baseKey", required = false) String baseKey, @SessionAttribute("userId") Long userId, // Model model) { // Page<NoticesList> page2 = informService.pageThis(page, size, userId,baseKey,null,null,null); // List<NoticesList> noticeList=page2.getContent(); // Long sum=page2.getTotalElements(); // int size2=page2.getSize(); // int pages=page2.getTotalPages(); // int number=page2.getNumber(); // model.addAttribute("list", noticeList); // model.addAttribute("page", page2); // return page2; // List<NoticesList> noticeList=informDao.findByUserId(userId); // List<NoticesList> // noticeList=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // true); // List<NoticesList> // noticeList2=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // false); // noticeList.addAll(noticeList2); // List<Map<String, Object>> list=informService.fengZhuang(noticeList); // model.addAttribute("list",list); // } /** * 通知管理删除 */ @RequestMapping("infromdelete") public String infromDelete(HttpSession session, HttpServletRequest req) { Long noticeId = Long.parseLong(req.getParameter("id")); Long userId = Long.parseLong(session.getAttribute("userId") + ""); NoticesList notice = informDao.findOne(noticeId); if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId"); List<SystemTypeList> typeList = typeDao.findByTypeModel("inform"); List<SystemStatusList> statusList = statusDao.findByStatusModel("inform"); if (!StringUtils.isEmpty(req.getAttribute("errormess"))) { req.setAttribute("errormess", req.getAttribute("errormess")); } if (!StringUtils.isEmpty(req.getAttribute("success"))) { req.setAttribute("success", "数据保存成功"); } req.setAttribute("typeList", typeList); req.setAttribute("statusList", statusList); if (!StringUtils.isEmpty(req.getParameter("id"))) { Long noticeId = Long.parseLong(req.getParameter("id")); NoticesList noticeList = informDao.findOne(noticeId); model.addAttribute("noticeList", noticeList); model.addAttribute("typeName", typeDao.findOne(noticeList.getTypeId()).getTypeName()); model.addAttribute("statusName", statusDao.findOne(noticeList.getStatusId()).getStatusName()); session.setAttribute("noticeId", noticeId); } return "inform/informedit"; } /** * 详细通知显示 */ @RequestMapping("informshow") public String informShow(HttpServletRequest req, Model model) { Long noticeId = Long.parseLong(req.getParameter("id")); if (!StringUtils.isEmpty(req.getParameter("read"))) { if (("0").equals(req.getParameter("read"))) { Long relationId = Long.parseLong(req.getParameter("relationid")); NoticeUserRelation relation = informrelationDao.findOne(relationId); relation.setRead(true); informrelationservice.save(relation); } } NoticesList notice = informDao.findOne(noticeId); User user = uDao.findOne(notice.getUserId()); model.addAttribute("notice", notice); model.addAttribute("userName", user.getUserName()); return "inform/informshow"; } /** * 系统管理表单验证 * * @param req * @param menu * @param br * 后台校验表单数据,不通过则回填数据,显示错误信息;通过则直接执行业务,例如新增、编辑等; * @return */ @RequestMapping("informcheck") public String testMess(HttpServletRequest req, @Valid NoticesList menu, BindingResult br) { HttpSession session = req.getSession(); Long menuId = null; req.setAttribute("menuObj", menu); Long userId = Long.parseLong(session.getAttribute("userId") + ""); menu.setUserId(userId); // 这里返回ResultVO对象,如果校验通过,ResultEnum.SUCCESS.getCode()返回的值为200;否则就是没有通过; ResultVO res = BindingResultVOUtil.hasErrors(br); // 校验失败 if (!ResultEnum.SUCCESS.getCode().equals(res.getCode())) {
List<Object> list = new MapToList<>().mapToList(res.getData());
1
2023-11-03 02:29:57+00:00
24k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/util/MoneyGiver.java
[ { "identifier": "Main", "path": "Core/src/main/java/org/by1337/bauction/Main.java", "snippet": "public final class Main extends JavaPlugin {\n private static Message message;\n private static Plugin instance;\n private static Config cfg;\n private static FileDataBase storage;\n private Co...
import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.by1337.bauction.Main; import org.by1337.bauction.db.kernel.MysqlDb; import org.by1337.bauction.network.PacketConnection; import org.by1337.bauction.network.PacketType; import org.by1337.bauction.network.WaitNotifyCallBack; import org.by1337.bauction.network.in.PlayInGiveMoneyRequest; import org.by1337.bauction.network.in.PlayInGiveMoneyResponse; import org.by1337.bauction.network.out.PlayOutGiveMoneyRequest; import org.by1337.bauction.network.out.PlayOutGiveMoneyResponse; import org.jetbrains.annotations.Nullable; import java.util.Map; import java.util.UUID; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger;
14,773
package org.by1337.bauction.util; public class MoneyGiver { private final PacketConnection connection;
package org.by1337.bauction.util; public class MoneyGiver { private final PacketConnection connection;
private final MysqlDb mysqlDb;
1
2023-11-08 18:25:18+00:00
24k
txline0420/nacos-dm
plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/dm/ConfigInfoMapperByDm.java
[ { "identifier": "NamespaceUtil", "path": "common/src/main/java/com/alibaba/nacos/common/utils/NamespaceUtil.java", "snippet": "public class NamespaceUtil {\n\n private NamespaceUtil() {\n }\n \n private static final String NAMESPACE_PUBLIC_KEY = \"public\";\n \n /**\n * public id,默...
import com.alibaba.nacos.common.utils.NamespaceUtil; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoMapper; import java.sql.Timestamp; import java.util.Map;
14,670
/* * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.plugin.datasource.impl.dm; /** * The DM implementation of ConfigInfoMapper. * * @author TXLINE **/ public class ConfigInfoMapperByDm extends AbstractMapper implements ConfigInfoMapper { private static final String DATA_ID = "dataId"; private static final String GROUP = "group"; private static final String APP_NAME = "appName"; private static final String CONTENT = "content"; private static final String TENANT = "tenant"; @Override public String findConfigInfoByAppFetchRows(int startRow, int pageSize) { return "SELECT id,data_id,group_id,tenant_id,app_name,content FROM config_info" + " WHERE tenant_id LIKE ? AND app_name= ?" + " LIMIT " + startRow + "," + pageSize; } @Override public String getTenantIdList(int startRow, int pageSize) { return "SELECT tenant_id FROM config_info WHERE tenant_id != '" + NamespaceUtil.getNamespaceDefaultId() + "' GROUP BY tenant_id LIMIT " + startRow + "," + pageSize; } @Override public String getGroupIdList(int startRow, int pageSize) { return "SELECT group_id FROM config_info WHERE tenant_id ='" + NamespaceUtil.getNamespaceDefaultId() + "' GROUP BY group_id LIMIT " + startRow + "," + pageSize; } @Override public String findAllConfigKey(int startRow, int pageSize) { return " SELECT data_id,group_id,app_name FROM ( " + " SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT " + startRow + "," + pageSize + " )" + " g, config_info t WHERE g.id = t.id "; } @Override public String findAllConfigInfoBaseFetchRows(int startRow, int pageSize) { return "SELECT t.id,data_id,group_id,content,md5" + " FROM ( SELECT id FROM config_info ORDER BY id LIMIT ?,? ) " + " g, config_info t WHERE g.id = t.id "; } @Override public String findAllConfigInfoFragment(int startRow, int pageSize) { return "SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type,encrypted_data_key " + "FROM config_info WHERE id > ? ORDER BY id ASC LIMIT " + startRow + "," + pageSize; } @Override public String findChangeConfigFetchRows(Map<String, String> params, final Timestamp startTime, final Timestamp endTime, int startRow, int pageSize, long lastMaxId) { final String tenant = params.get(TENANT); final String dataId = params.get(DATA_ID); final String group = params.get(GROUP); final String appName = params.get(APP_NAME);
/* * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.plugin.datasource.impl.dm; /** * The DM implementation of ConfigInfoMapper. * * @author TXLINE **/ public class ConfigInfoMapperByDm extends AbstractMapper implements ConfigInfoMapper { private static final String DATA_ID = "dataId"; private static final String GROUP = "group"; private static final String APP_NAME = "appName"; private static final String CONTENT = "content"; private static final String TENANT = "tenant"; @Override public String findConfigInfoByAppFetchRows(int startRow, int pageSize) { return "SELECT id,data_id,group_id,tenant_id,app_name,content FROM config_info" + " WHERE tenant_id LIKE ? AND app_name= ?" + " LIMIT " + startRow + "," + pageSize; } @Override public String getTenantIdList(int startRow, int pageSize) { return "SELECT tenant_id FROM config_info WHERE tenant_id != '" + NamespaceUtil.getNamespaceDefaultId() + "' GROUP BY tenant_id LIMIT " + startRow + "," + pageSize; } @Override public String getGroupIdList(int startRow, int pageSize) { return "SELECT group_id FROM config_info WHERE tenant_id ='" + NamespaceUtil.getNamespaceDefaultId() + "' GROUP BY group_id LIMIT " + startRow + "," + pageSize; } @Override public String findAllConfigKey(int startRow, int pageSize) { return " SELECT data_id,group_id,app_name FROM ( " + " SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT " + startRow + "," + pageSize + " )" + " g, config_info t WHERE g.id = t.id "; } @Override public String findAllConfigInfoBaseFetchRows(int startRow, int pageSize) { return "SELECT t.id,data_id,group_id,content,md5" + " FROM ( SELECT id FROM config_info ORDER BY id LIMIT ?,? ) " + " g, config_info t WHERE g.id = t.id "; } @Override public String findAllConfigInfoFragment(int startRow, int pageSize) { return "SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type,encrypted_data_key " + "FROM config_info WHERE id > ? ORDER BY id ASC LIMIT " + startRow + "," + pageSize; } @Override public String findChangeConfigFetchRows(Map<String, String> params, final Timestamp startTime, final Timestamp endTime, int startRow, int pageSize, long lastMaxId) { final String tenant = params.get(TENANT); final String dataId = params.get(DATA_ID); final String group = params.get(GROUP); final String appName = params.get(APP_NAME);
final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
1
2023-11-02 01:34:09+00:00
24k
ynwynw/oaSystemPublic
src/main/java/cn/gson/oasys/controller/inform/InformManageController.java
[ { "identifier": "BindingResultVOUtil", "path": "src/main/java/cn/gson/oasys/common/formValid/BindingResultVOUtil.java", "snippet": "public class BindingResultVOUtil {\n /**\n * 表单验证,返回形式ResultVO\n *\n * @param br\n * @return\n */\n public static ResultVO hasErrors(BindingResult...
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.gson.oasys.common.formValid.BindingResultVOUtil; import cn.gson.oasys.common.formValid.MapToList; import cn.gson.oasys.common.formValid.ResultEnum; import cn.gson.oasys.common.formValid.ResultVO; import cn.gson.oasys.mappers.NoticeMapper; import cn.gson.oasys.model.dao.informdao.InformDao; import cn.gson.oasys.model.dao.informdao.InformRelationDao; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.notice.NoticeUserRelation; import cn.gson.oasys.model.entity.notice.NoticeVO; import cn.gson.oasys.model.entity.notice.NoticesList; import cn.gson.oasys.model.entity.system.SystemMenu; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User; import cn.gson.oasys.services.inform.InformRelationService; import cn.gson.oasys.services.inform.InformService;
14,574
if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId"); List<SystemTypeList> typeList = typeDao.findByTypeModel("inform"); List<SystemStatusList> statusList = statusDao.findByStatusModel("inform"); if (!StringUtils.isEmpty(req.getAttribute("errormess"))) { req.setAttribute("errormess", req.getAttribute("errormess")); } if (!StringUtils.isEmpty(req.getAttribute("success"))) { req.setAttribute("success", "数据保存成功"); } req.setAttribute("typeList", typeList); req.setAttribute("statusList", statusList); if (!StringUtils.isEmpty(req.getParameter("id"))) { Long noticeId = Long.parseLong(req.getParameter("id")); NoticesList noticeList = informDao.findOne(noticeId); model.addAttribute("noticeList", noticeList); model.addAttribute("typeName", typeDao.findOne(noticeList.getTypeId()).getTypeName()); model.addAttribute("statusName", statusDao.findOne(noticeList.getStatusId()).getStatusName()); session.setAttribute("noticeId", noticeId); } return "inform/informedit"; } /** * 详细通知显示 */ @RequestMapping("informshow") public String informShow(HttpServletRequest req, Model model) { Long noticeId = Long.parseLong(req.getParameter("id")); if (!StringUtils.isEmpty(req.getParameter("read"))) { if (("0").equals(req.getParameter("read"))) { Long relationId = Long.parseLong(req.getParameter("relationid")); NoticeUserRelation relation = informrelationDao.findOne(relationId); relation.setRead(true); informrelationservice.save(relation); } } NoticesList notice = informDao.findOne(noticeId); User user = uDao.findOne(notice.getUserId()); model.addAttribute("notice", notice); model.addAttribute("userName", user.getUserName()); return "inform/informshow"; } /** * 系统管理表单验证 * * @param req * @param menu * @param br * 后台校验表单数据,不通过则回填数据,显示错误信息;通过则直接执行业务,例如新增、编辑等; * @return */ @RequestMapping("informcheck") public String testMess(HttpServletRequest req, @Valid NoticesList menu, BindingResult br) { HttpSession session = req.getSession(); Long menuId = null; req.setAttribute("menuObj", menu); Long userId = Long.parseLong(session.getAttribute("userId") + ""); menu.setUserId(userId); // 这里返回ResultVO对象,如果校验通过,ResultEnum.SUCCESS.getCode()返回的值为200;否则就是没有通过; ResultVO res = BindingResultVOUtil.hasErrors(br); // 校验失败 if (!ResultEnum.SUCCESS.getCode().equals(res.getCode())) {
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){ List<User> users=uDao.findByFatherId(userId); NoticesList nl=informDao.findOne(noticeId); List<NoticeUserRelation> nurs=new ArrayList<>(); for (User user : users) { nurs.add(new NoticeUserRelation(nl, user, false)); } informrelationservice.saves(nurs); return "redirect:/infromlist"; } // demo // @RequestMapping("cccc") // public @ResponseBody Page<NoticesList> ddd(@RequestParam(value = "page", defaultValue = "0") int page, // @RequestParam(value = "size", defaultValue = "10") int size, // @RequestParam(value = "baseKey", required = false) String baseKey, @SessionAttribute("userId") Long userId, // Model model) { // Page<NoticesList> page2 = informService.pageThis(page, size, userId,baseKey,null,null,null); // List<NoticesList> noticeList=page2.getContent(); // Long sum=page2.getTotalElements(); // int size2=page2.getSize(); // int pages=page2.getTotalPages(); // int number=page2.getNumber(); // model.addAttribute("list", noticeList); // model.addAttribute("page", page2); // return page2; // List<NoticesList> noticeList=informDao.findByUserId(userId); // List<NoticesList> // noticeList=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // true); // List<NoticesList> // noticeList2=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // false); // noticeList.addAll(noticeList2); // List<Map<String, Object>> list=informService.fengZhuang(noticeList); // model.addAttribute("list",list); // } /** * 通知管理删除 */ @RequestMapping("infromdelete") public String infromDelete(HttpSession session, HttpServletRequest req) { Long noticeId = Long.parseLong(req.getParameter("id")); Long userId = Long.parseLong(session.getAttribute("userId") + ""); NoticesList notice = informDao.findOne(noticeId); if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId"); List<SystemTypeList> typeList = typeDao.findByTypeModel("inform"); List<SystemStatusList> statusList = statusDao.findByStatusModel("inform"); if (!StringUtils.isEmpty(req.getAttribute("errormess"))) { req.setAttribute("errormess", req.getAttribute("errormess")); } if (!StringUtils.isEmpty(req.getAttribute("success"))) { req.setAttribute("success", "数据保存成功"); } req.setAttribute("typeList", typeList); req.setAttribute("statusList", statusList); if (!StringUtils.isEmpty(req.getParameter("id"))) { Long noticeId = Long.parseLong(req.getParameter("id")); NoticesList noticeList = informDao.findOne(noticeId); model.addAttribute("noticeList", noticeList); model.addAttribute("typeName", typeDao.findOne(noticeList.getTypeId()).getTypeName()); model.addAttribute("statusName", statusDao.findOne(noticeList.getStatusId()).getStatusName()); session.setAttribute("noticeId", noticeId); } return "inform/informedit"; } /** * 详细通知显示 */ @RequestMapping("informshow") public String informShow(HttpServletRequest req, Model model) { Long noticeId = Long.parseLong(req.getParameter("id")); if (!StringUtils.isEmpty(req.getParameter("read"))) { if (("0").equals(req.getParameter("read"))) { Long relationId = Long.parseLong(req.getParameter("relationid")); NoticeUserRelation relation = informrelationDao.findOne(relationId); relation.setRead(true); informrelationservice.save(relation); } } NoticesList notice = informDao.findOne(noticeId); User user = uDao.findOne(notice.getUserId()); model.addAttribute("notice", notice); model.addAttribute("userName", user.getUserName()); return "inform/informshow"; } /** * 系统管理表单验证 * * @param req * @param menu * @param br * 后台校验表单数据,不通过则回填数据,显示错误信息;通过则直接执行业务,例如新增、编辑等; * @return */ @RequestMapping("informcheck") public String testMess(HttpServletRequest req, @Valid NoticesList menu, BindingResult br) { HttpSession session = req.getSession(); Long menuId = null; req.setAttribute("menuObj", menu); Long userId = Long.parseLong(session.getAttribute("userId") + ""); menu.setUserId(userId); // 这里返回ResultVO对象,如果校验通过,ResultEnum.SUCCESS.getCode()返回的值为200;否则就是没有通过; ResultVO res = BindingResultVOUtil.hasErrors(br); // 校验失败 if (!ResultEnum.SUCCESS.getCode().equals(res.getCode())) {
List<Object> list = new MapToList<>().mapToList(res.getData());
1
2023-11-03 02:08:22+00:00
24k
firstdarkdev/modfusioner
src/main/java/com/hypherionmc/modfusioner/task/JarFuseTask.java
[ { "identifier": "Constants", "path": "src/main/java/com/hypherionmc/modfusioner/Constants.java", "snippet": "public class Constants {\n\n public static final String TASK_GROUP = \"modfusioner\";\n public static final String TASK_NAME = \"fusejars\";\n public static final String EXTENSION_NAME =...
import com.hypherionmc.modfusioner.Constants; import com.hypherionmc.modfusioner.actions.JarMergeAction; import com.hypherionmc.modfusioner.plugin.FusionerExtension; import com.hypherionmc.modfusioner.plugin.ModFusionerPlugin; import com.hypherionmc.modfusioner.utils.FileChecks; import com.hypherionmc.modfusioner.utils.FileTools; import org.apache.commons.io.FileUtils; import org.gradle.api.Project; import org.gradle.api.internal.file.copy.CopyAction; import org.gradle.api.tasks.WorkResults; import org.gradle.jvm.tasks.Jar; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.modFusionerExtension; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.rootProject;
14,978
if (customConfigurations != null) { for (FusionerExtension.CustomConfiguration customSettings : customConfigurations) { try { customProjects.put(rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equals(customSettings.getProjectName())).findFirst().get(), customSettings); validation.add(true); } catch (NoSuchElementException ignored) { } } } // Check that at least 2 projects are defined if (validation.size() < 2) { if (validation.size() == 1) ModFusionerPlugin.logger.error("Only one project was found. Skipping fusejars task."); if (validation.size() == 0) ModFusionerPlugin.logger.error("No projects were found. Skipping fusejars task."); return; } validation.clear(); // Try to automatically determine the input jar from the projects File forgeJar = null; File fabricJar = null; File quiltJar = null; Map<FusionerExtension.CustomConfiguration, File> customJars = new HashMap<>(); if (forgeProject != null && forgeConfiguration != null) { forgeJar = getInputFile(forgeConfiguration.getInputFile(), forgeConfiguration.getInputTaskName(), forgeProject); } if (fabricProject != null && fabricConfiguration != null) { fabricJar = getInputFile(fabricConfiguration.getInputFile(), fabricConfiguration.getInputTaskName(), fabricProject); } if (quiltProject != null && quiltConfiguration != null) { quiltJar = getInputFile(quiltConfiguration.getInputFile(), quiltConfiguration.getInputTaskName(), quiltProject); } for (Map.Entry<Project, FusionerExtension.CustomConfiguration> entry : customProjects.entrySet()) { File f = getInputFile(entry.getValue().getInputFile(), entry.getValue().getInputTaskName(), entry.getKey()); if (f != null) customJars.put(entry.getValue(), f); } // Set up the final output jar if (mergedJar.exists()) FileUtils.forceDelete(mergedJar); if (!mergedJar.getParentFile().exists()) mergedJar.getParentFile().mkdirs(); // Set up the jar merge action JarMergeAction mergeAction = JarMergeAction.of( customJars, modFusionerExtension.getDuplicateRelocations(), modFusionerExtension.getPackageGroup(), new File(rootProject.getRootDir(), ".gradle" + File.separator + "fusioner"), getArchiveFileName().get() ); // Forge mergeAction.setForgeInput(forgeJar); mergeAction.setForgeRelocations(forgeConfiguration == null ? new HashMap<>() : forgeConfiguration.getRelocations()); mergeAction.setForgeMixins(forgeConfiguration == null ? new ArrayList<>() : forgeConfiguration.getMixins()); // Fabric mergeAction.setFabricInput(fabricJar); mergeAction.setFabricRelocations(fabricConfiguration == null ? new HashMap<>() : fabricConfiguration.getRelocations()); // Quilt mergeAction.setQuiltInput(quiltJar); mergeAction.setQuiltRelocations(quiltConfiguration == null ? new HashMap<>() : quiltConfiguration.getRelocations()); // Merge them jars Path tempMergedJarPath = mergeAction.mergeJars(false).toPath(); // Move the merged jar to the specified output directory Files.move(tempMergedJarPath, mergedJar.toPath(), StandardCopyOption.REPLACE_EXISTING); try { Files.setPosixFilePermissions(mergedJar.toPath(), Constants.filePerms); } catch (UnsupportedOperationException | IOException | SecurityException ignored) { } // Cleanup mergeAction.clean(); ModFusionerPlugin.logger.lifecycle("Fused jar created in " + (System.currentTimeMillis() - time) / 1000.0 + " seconds."); hasRun.set(true); } /** * Run the main task logic and copy the files to the correct locations * @return - Just returns true to say the task executed */ @Override protected @NotNull CopyAction createCopyAction() { return copyActionProcessingStream -> { copyActionProcessingStream.process(fileCopyDetailsInternal -> { if (!hasRun.get()) try { fuseJars(); } catch (IOException e) { throw new RuntimeException(e); } }); return WorkResults.didWork(true); }; } /** * Try to determine the input jar of a project * @param jarLocation - The user defined jar location * @param inProject - The project the file should be for or from * @return - The jar file or null */ @Nullable private File getInputFile(@Nullable String jarLocation, String inputTaskName, Project inProject) { if (jarLocation != null && !jarLocation.isEmpty()) { return new File(inProject.getProjectDir(), jarLocation); } else if (inputTaskName != null && !inputTaskName.isEmpty()) { return FileTools.resolveFile(inProject, inputTaskName); } else { int i = 0; for (File file : new File(inProject.getBuildDir(), "libs").listFiles()) { if (file.isDirectory()) continue;
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension getArchiveBaseName().set(modFusionerExtension.getMergedJarName()); getArchiveVersion().set(modFusionerExtension.getJarVersion()); getDestinationDirectory().set(getProject().file(modFusionerExtension.getOutputDirectory())); // We don't allow custom input files, when the user defines their own task getInputs().files(); // Only allow the task to run once per cycle getOutputs().upToDateWhen(spec -> hasRun.get()); // Set output file mergedJar = new File(getDestinationDirectory().get().getAsFile(), getArchiveFileName().get()); getOutputs().file(mergedJar); } /** * Main task logic * @throws IOException - Thrown when an IO error occurs */ void fuseJars() throws IOException { long time = System.currentTimeMillis(); ModFusionerPlugin.logger.lifecycle("Start Fusing Jars"); // Get settings from extension FusionerExtension.ForgeConfiguration forgeConfiguration = modFusionerExtension.getForgeConfiguration(); FusionerExtension.FabricConfiguration fabricConfiguration = modFusionerExtension.getFabricConfiguration(); FusionerExtension.QuiltConfiguration quiltConfiguration = modFusionerExtension.getQuiltConfiguration(); List<FusionerExtension.CustomConfiguration> customConfigurations = modFusionerExtension.getCustomConfigurations(); // Try to resolve the projects specific in the extension config Project forgeProject = null; Project fabricProject = null; Project quiltProject = null; Map<Project, FusionerExtension.CustomConfiguration> customProjects = new HashMap<>(); List<Boolean> validation = new ArrayList<>(); if (forgeConfiguration != null) { try { forgeProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(forgeConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (fabricConfiguration != null) { try { fabricProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(fabricConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (quiltConfiguration != null) { try { quiltProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(quiltConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (customConfigurations != null) { for (FusionerExtension.CustomConfiguration customSettings : customConfigurations) { try { customProjects.put(rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equals(customSettings.getProjectName())).findFirst().get(), customSettings); validation.add(true); } catch (NoSuchElementException ignored) { } } } // Check that at least 2 projects are defined if (validation.size() < 2) { if (validation.size() == 1) ModFusionerPlugin.logger.error("Only one project was found. Skipping fusejars task."); if (validation.size() == 0) ModFusionerPlugin.logger.error("No projects were found. Skipping fusejars task."); return; } validation.clear(); // Try to automatically determine the input jar from the projects File forgeJar = null; File fabricJar = null; File quiltJar = null; Map<FusionerExtension.CustomConfiguration, File> customJars = new HashMap<>(); if (forgeProject != null && forgeConfiguration != null) { forgeJar = getInputFile(forgeConfiguration.getInputFile(), forgeConfiguration.getInputTaskName(), forgeProject); } if (fabricProject != null && fabricConfiguration != null) { fabricJar = getInputFile(fabricConfiguration.getInputFile(), fabricConfiguration.getInputTaskName(), fabricProject); } if (quiltProject != null && quiltConfiguration != null) { quiltJar = getInputFile(quiltConfiguration.getInputFile(), quiltConfiguration.getInputTaskName(), quiltProject); } for (Map.Entry<Project, FusionerExtension.CustomConfiguration> entry : customProjects.entrySet()) { File f = getInputFile(entry.getValue().getInputFile(), entry.getValue().getInputTaskName(), entry.getKey()); if (f != null) customJars.put(entry.getValue(), f); } // Set up the final output jar if (mergedJar.exists()) FileUtils.forceDelete(mergedJar); if (!mergedJar.getParentFile().exists()) mergedJar.getParentFile().mkdirs(); // Set up the jar merge action JarMergeAction mergeAction = JarMergeAction.of( customJars, modFusionerExtension.getDuplicateRelocations(), modFusionerExtension.getPackageGroup(), new File(rootProject.getRootDir(), ".gradle" + File.separator + "fusioner"), getArchiveFileName().get() ); // Forge mergeAction.setForgeInput(forgeJar); mergeAction.setForgeRelocations(forgeConfiguration == null ? new HashMap<>() : forgeConfiguration.getRelocations()); mergeAction.setForgeMixins(forgeConfiguration == null ? new ArrayList<>() : forgeConfiguration.getMixins()); // Fabric mergeAction.setFabricInput(fabricJar); mergeAction.setFabricRelocations(fabricConfiguration == null ? new HashMap<>() : fabricConfiguration.getRelocations()); // Quilt mergeAction.setQuiltInput(quiltJar); mergeAction.setQuiltRelocations(quiltConfiguration == null ? new HashMap<>() : quiltConfiguration.getRelocations()); // Merge them jars Path tempMergedJarPath = mergeAction.mergeJars(false).toPath(); // Move the merged jar to the specified output directory Files.move(tempMergedJarPath, mergedJar.toPath(), StandardCopyOption.REPLACE_EXISTING); try { Files.setPosixFilePermissions(mergedJar.toPath(), Constants.filePerms); } catch (UnsupportedOperationException | IOException | SecurityException ignored) { } // Cleanup mergeAction.clean(); ModFusionerPlugin.logger.lifecycle("Fused jar created in " + (System.currentTimeMillis() - time) / 1000.0 + " seconds."); hasRun.set(true); } /** * Run the main task logic and copy the files to the correct locations * @return - Just returns true to say the task executed */ @Override protected @NotNull CopyAction createCopyAction() { return copyActionProcessingStream -> { copyActionProcessingStream.process(fileCopyDetailsInternal -> { if (!hasRun.get()) try { fuseJars(); } catch (IOException e) { throw new RuntimeException(e); } }); return WorkResults.didWork(true); }; } /** * Try to determine the input jar of a project * @param jarLocation - The user defined jar location * @param inProject - The project the file should be for or from * @return - The jar file or null */ @Nullable private File getInputFile(@Nullable String jarLocation, String inputTaskName, Project inProject) { if (jarLocation != null && !jarLocation.isEmpty()) { return new File(inProject.getProjectDir(), jarLocation); } else if (inputTaskName != null && !inputTaskName.isEmpty()) { return FileTools.resolveFile(inProject, inputTaskName); } else { int i = 0; for (File file : new File(inProject.getBuildDir(), "libs").listFiles()) { if (file.isDirectory()) continue;
if (FileChecks.isZipFile(file)) {
4
2023-11-03 23:19:08+00:00
24k
data-harness-cloud/data_harness-be
common/common-dict/src/main/java/supie/common/dict/util/GlobalDictOperationHelper.java
[ { "identifier": "ResponseResult", "path": "common/common-core/src/main/java/supie/common/core/object/ResponseResult.java", "snippet": "@Slf4j\n@Data\npublic class ResponseResult<T> {\n\n /**\n * 为了优化性能,所有没有携带数据的正确结果,均可用该对象表示。\n */\n private static final ResponseResult<Void> OK = new Respon...
import com.github.pagehelper.Page; import com.github.pagehelper.page.PageMethod; import supie.common.core.object.ResponseResult; import supie.common.core.object.MyPageData; import supie.common.core.object.MyPageParam; import supie.common.core.util.MyModelUtil; import supie.common.core.util.MyPageUtil; import supie.common.dict.dto.GlobalDictDto; import supie.common.dict.model.GlobalDict; import supie.common.dict.service.GlobalDictService; import supie.common.dict.vo.GlobalDictVo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List;
15,929
package supie.common.dict.util; /** * 全局编码字典操作的通用帮助对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @Slf4j @Component public class GlobalDictOperationHelper { @Autowired private GlobalDictService globalDictService; /** * 获取全部编码字典列表。 * * @param globalDictDtoFilter 过滤对象。 * @param pageParam 分页参数。 * @return 字典的数据列表。 */ public ResponseResult<MyPageData<GlobalDictVo>> listAllGlobalDict( GlobalDictDto globalDictDtoFilter, MyPageParam pageParam) { if (pageParam != null) { PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize()); } GlobalDict filter = MyModelUtil.copyTo(globalDictDtoFilter, GlobalDict.class); List<GlobalDict> dictList = globalDictService.getGlobalDictList(filter, null); List<GlobalDictVo> dictVoList = MyModelUtil.copyCollectionTo(dictList, GlobalDictVo.class); long totalCount = 0L; if (dictList instanceof Page) { totalCount = ((Page<GlobalDict>) dictList).getTotal(); }
package supie.common.dict.util; /** * 全局编码字典操作的通用帮助对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @Slf4j @Component public class GlobalDictOperationHelper { @Autowired private GlobalDictService globalDictService; /** * 获取全部编码字典列表。 * * @param globalDictDtoFilter 过滤对象。 * @param pageParam 分页参数。 * @return 字典的数据列表。 */ public ResponseResult<MyPageData<GlobalDictVo>> listAllGlobalDict( GlobalDictDto globalDictDtoFilter, MyPageParam pageParam) { if (pageParam != null) { PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize()); } GlobalDict filter = MyModelUtil.copyTo(globalDictDtoFilter, GlobalDict.class); List<GlobalDict> dictList = globalDictService.getGlobalDictList(filter, null); List<GlobalDictVo> dictVoList = MyModelUtil.copyCollectionTo(dictList, GlobalDictVo.class); long totalCount = 0L; if (dictList instanceof Page) { totalCount = ((Page<GlobalDict>) dictList).getTotal(); }
return ResponseResult.success(MyPageUtil.makeResponseData(dictVoList, totalCount));
4
2023-11-04 12:36:44+00:00
24k
momentohq/momento-dynamodb-lock-client
src/main/java/com/amazonaws/services/dynamodbv2/MomentoDynamoDBLockClient.java
[ { "identifier": "LockItemUtils", "path": "src/main/java/momento/lock/client/LockItemUtils.java", "snippet": "public class LockItemUtils {\n\n private static final ObjectMapper MAPPER = new ObjectMapper();\n\n public static byte[] serialize(final MomentoLockItem lockItem) {\n try {\n ...
import com.amazonaws.services.dynamodbv2.model.LockCurrentlyUnavailableException; import com.amazonaws.services.dynamodbv2.model.LockNotGrantedException; import com.amazonaws.services.dynamodbv2.util.LockClientUtils; import momento.lock.client.LockItemUtils; import momento.lock.client.LockStorage; import momento.lock.client.MomentoDynamoDBLockClientOptions; import momento.lock.client.MomentoLockClient; import momento.lock.client.MomentoLockClientHeartbeatHandler; import momento.lock.client.MomentoLockItem; import momento.lock.client.NoopDynamoDbClient; import momento.lock.client.model.MomentoClientException; import momento.sdk.CacheClient; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import software.amazon.awssdk.core.exception.SdkClientException; import java.io.Closeable; import java.io.IOException; import java.time.Duration; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Stream;
18,742
/* * This Java source file was generated by the Gradle 'init' task. */ package com.amazonaws.services.dynamodbv2; /** * <p> * Provides a simple library for using DynamoDB's consistent read/write feature to use it for managing distributed locks. * </p> * <p> * In order to use this library, the client must create a cache in Momento, although the library provides a convenience method * for creating that cache (createLockCache.) * </p> * <p> * Here is some example code for how to use the lock client for leader election to work on a resource called "host-2" (it * assumes you already have a Momento cache named lockCache, which can be created with the * {@code createLockCache} helper method): * </p> * <pre> * {@code * AmazonDynamoDBLockClient lockClient = new MomentoDynamoDBLockClient( * MomentoDynamoDBLockClientOptions.builder(dynamoDBClient, "lockTable").build(); * try { * // Attempt to acquire the lock indefinitely, polling Momento every 2 seconds for the lock * LockItem lockItem = lockClient.acquireLock( * AcquireLockOptions.builder("host-2") * .withRefreshPeriod(120L) * .withAdditionalTimeToWaitForLock(Long.MAX_VALUE / 2L) * .withTimeUnit(TimeUnit.MILLISECONDS) * .build()); * if (!lockItem.isExpired()) { * // do business logic, you can call lockItem.isExpired() to periodically check to make sure you still have the lock * // the background thread will keep the lock valid for you by sending heartbeats (default is every 5 seconds) * } * } catch (LockNotGrantedException x) { * // Should only be thrown if the lock could not be acquired for Long.MAX_VALUE / 2L milliseconds. * } * } * </pre> */ public class MomentoDynamoDBLockClient extends AmazonDynamoDBLockClient implements Closeable { private static final Log logger = LogFactory.getLog(MomentoDynamoDBLockClient.class); private final String lockCacheName; private final CacheClient cacheClient; private static final long DEFAULT_BUFFER_MS = 1000; private static final int TTL_GRACE_MILLIS = 200; private final long leaseDurationMillis; private final long heartbeatPeriodInMilliseconds; private final String owner; private final ConcurrentHashMap<String, Thread> sessionMonitors; private final LockStorage lockStorage; private final Function<String, ThreadFactory> namedThreadCreator; private ScheduledExecutorService heartbeatExecutor;
/* * This Java source file was generated by the Gradle 'init' task. */ package com.amazonaws.services.dynamodbv2; /** * <p> * Provides a simple library for using DynamoDB's consistent read/write feature to use it for managing distributed locks. * </p> * <p> * In order to use this library, the client must create a cache in Momento, although the library provides a convenience method * for creating that cache (createLockCache.) * </p> * <p> * Here is some example code for how to use the lock client for leader election to work on a resource called "host-2" (it * assumes you already have a Momento cache named lockCache, which can be created with the * {@code createLockCache} helper method): * </p> * <pre> * {@code * AmazonDynamoDBLockClient lockClient = new MomentoDynamoDBLockClient( * MomentoDynamoDBLockClientOptions.builder(dynamoDBClient, "lockTable").build(); * try { * // Attempt to acquire the lock indefinitely, polling Momento every 2 seconds for the lock * LockItem lockItem = lockClient.acquireLock( * AcquireLockOptions.builder("host-2") * .withRefreshPeriod(120L) * .withAdditionalTimeToWaitForLock(Long.MAX_VALUE / 2L) * .withTimeUnit(TimeUnit.MILLISECONDS) * .build()); * if (!lockItem.isExpired()) { * // do business logic, you can call lockItem.isExpired() to periodically check to make sure you still have the lock * // the background thread will keep the lock valid for you by sending heartbeats (default is every 5 seconds) * } * } catch (LockNotGrantedException x) { * // Should only be thrown if the lock could not be acquired for Long.MAX_VALUE / 2L milliseconds. * } * } * </pre> */ public class MomentoDynamoDBLockClient extends AmazonDynamoDBLockClient implements Closeable { private static final Log logger = LogFactory.getLog(MomentoDynamoDBLockClient.class); private final String lockCacheName; private final CacheClient cacheClient; private static final long DEFAULT_BUFFER_MS = 1000; private static final int TTL_GRACE_MILLIS = 200; private final long leaseDurationMillis; private final long heartbeatPeriodInMilliseconds; private final String owner; private final ConcurrentHashMap<String, Thread> sessionMonitors; private final LockStorage lockStorage; private final Function<String, ThreadFactory> namedThreadCreator; private ScheduledExecutorService heartbeatExecutor;
private MomentoLockClientHeartbeatHandler heartbeatHandler;
4
2023-11-07 03:56:11+00:00
24k
beminder/BeautyMinder
java/src/main/java/app/beautyminder/controller/user/UserController.java
[ { "identifier": "Cosmetic", "path": "java/src/main/java/app/beautyminder/domain/Cosmetic.java", "snippet": "@Document(collection = \"cosmetics\") // mongodb\n@AllArgsConstructor\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@Getter\n@Builder\npublic class Cosmetic {\n\n @Id\n private String...
import app.beautyminder.domain.Cosmetic; import app.beautyminder.domain.PasswordResetToken; import app.beautyminder.domain.Review; import app.beautyminder.domain.User; import app.beautyminder.dto.PasswordResetResponse; import app.beautyminder.dto.sms.SmsResponseDTO; import app.beautyminder.dto.user.*; import app.beautyminder.repository.CosmeticRepository; import app.beautyminder.repository.ReviewRepository; import app.beautyminder.service.FileStorageService; import app.beautyminder.service.MongoService; import app.beautyminder.service.auth.SmsService; import app.beautyminder.service.auth.TokenService; import app.beautyminder.service.auth.UserService; import app.beautyminder.service.cosmetic.CosmeticRankService; import app.beautyminder.util.AuthenticatedUser; import com.fasterxml.jackson.core.JsonProcessingException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.ExampleObject; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestClientException; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import static java.util.function.Predicate.not;
16,951
package app.beautyminder.controller.user; @Slf4j @RequiredArgsConstructor @RestController @RequestMapping("/user") // Base path for all routes in this controller public class UserController { private final UserService userService; private final MongoService mongoService; private final SmsService smsService; private final TokenService tokenService; private final FileStorageService fileStorageService; private final CosmeticRepository cosmeticRepository; private final ReviewRepository reviewRepository; private final CosmeticRankService cosmeticRankService; @Value("${server.default.user}") private String defaultUserProfilePic; @Value("${server.default.admin}") private String defaultAdminProfilePic; @Operation(summary = "Request Email verification", description = "이메일 인증 요청입니다.", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "User signup details"), tags = {"User Operations"}, responses = {@ApiResponse(responseCode = "200", description = "사용자가 생성됨", content = @Content(schema = @Schema(implementation = SignUpResponse.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = SignUpResponse.class)))}) @PostMapping("/email-verification/request") public ResponseEntity<?> requestVerificationToken(@RequestParam String email) { // Check if email already exists in the system if (userService.findByEmail(email).isPresent()) { return ResponseEntity.badRequest().body("Email already in use."); } var token = userService.requestPassCode(email); return ResponseEntity.ok(token); } @Operation(summary = "Verify Email", description = "이메일 인증 확인입니다.") @PostMapping("/email-verification/verify") // Here if the token is valid, it sets verified. public ResponseEntity<?> verifyEmail(@RequestParam String token) { // Validate the token boolean isValid = tokenService.validateVerificationToken(token); if (!isValid) { // Handle invalid or expired token return ResponseEntity.badRequest().body("Invalid or expired token."); } // Token is valid return ResponseEntity.ok("Email verified successfully."); } // Standard user sign-up @Operation(summary = "Standard User Signup", description = "표준 사용자 등록을 처리합니다.", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "User signup details"), tags = {"User Operations"}, responses = {@ApiResponse(responseCode = "200", description = "사용자가 생성됨", content = @Content(schema = @Schema(implementation = SignUpResponse.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = SignUpResponse.class)))}) @PostMapping("/signup") public ResponseEntity<SignUpResponse> signUp(@Valid @org.springframework.web.bind.annotation.RequestBody AddUserRequest request) { // Check if email is verified if (!tokenService.isEmailVerified(request.getEmail())) { return ResponseEntity.badRequest().body(new SignUpResponse("Email not verified.", null)); } try { String userId = userService.saveUser(request).getId(); User user = userService.findById(userId); tokenService.removePassCodeFor(request.getEmail()); return ResponseEntity.ok(new SignUpResponse("A user is created", user)); } catch (Exception e) { // On error, check whether the token is expired, if so remove tokenService.validateAgainAndRemove(request.getEmail()); return ResponseEntity.badRequest().body(new SignUpResponse(e.getMessage(), null)); } } // Admin sign-up @Operation(summary = "Admin User Signup", description = "관리자 사용자 등록을 처리합니다.", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "Admin signup details"), tags = {"User Operations"}, responses = {@ApiResponse(responseCode = "200", description = "관리자가 생성됨", content = @Content(schema = @Schema(implementation = SignUpResponse.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = SignUpResponse.class)))}) @PostMapping("/signup-admin") public ResponseEntity<SignUpResponse> signUpAdmin(@RequestBody AddUserRequest request) { try { String userId = userService.saveAdmin(request).getId(); User user = userService.findById(userId); return ResponseEntity.ok(new SignUpResponse("A user is created", user)); } catch (IllegalArgumentException e) { return ResponseEntity.badRequest().body(new SignUpResponse(e.getMessage(), null)); } } @Operation(summary = "User Logout", description = "사용자 로그아웃", tags = {"User Operations"}, responses = {@ApiResponse(responseCode = "200", description = "성공적으로 로그아웃됨", content = @Content(schema = @Schema(implementation = String.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content)}) @GetMapping("/logout") public ResponseEntity<String> logout(HttpServletRequest request, HttpServletResponse response) { new SecurityContextLogoutHandler().logout(request, response, SecurityContextHolder.getContext().getAuthentication()); return ResponseEntity.ok("Logged out successfully"); } @Operation(summary = "User Deletion", description = "사용자 삭제 by userId [USER 권한 필요]", tags = {"User Operations"}) @DeleteMapping("/delete") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<?> deleteUser(@Parameter(hidden = true) @AuthenticatedUser User user) { userService.deleteUserAndRelatedData(user.getId()); return ResponseEntity.ok("a user is deleted successfully"); } @Operation(summary = "Get user profile", description = "사용자 프로필 가져오기 [USER 권한 필요]", tags = {"User Profile Operations"}, responses = {@ApiResponse(responseCode = "200", description = "유저 데이터 성공적으로 불러옴", content = @Content(schema = @Schema(implementation = User.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = User.class)))}) @GetMapping("/me") public ResponseEntity<User> getProfile(@Parameter(hidden = true) @AuthenticatedUser User user) { return ResponseEntity.ok(user); } @Operation(summary = "Update user profile", description = "사용자 프로필 업데이트 [USER 권한 필요]", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(schema = @Schema(implementation = Map.class), examples = @ExampleObject(name = "typicalResponses", value = """ { "baumann": "DSNT", "nickname": "Que" } """, summary = "지원 필드: nickname, profileImage, phoneNumber\n프사는 http 링크, phoneNumber은 중복을 체크함. (01012345678 형식, - 없음)")), description = "Profile updates"), tags = {"User Profile Operations"}, responses = {@ApiResponse(responseCode = "200", description = "유저 업데이트 완료", content = @Content(schema = @Schema(implementation = User.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = User.class)))}) // org.springframework.web.bind.annotation. // Can take any field in User class @PatchMapping("/update") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<?> updateProfile(@Parameter(hidden = true) @AuthenticatedUser User user, @RequestBody Map<String, Object> updates) { // 전화번호 미리 체크 if (updates.containsKey("phoneNumber")) { String phoneNumber = (String) updates.get("phoneNumber"); if (!mongoService.isValidKoreanPhoneNumber(phoneNumber)) { return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("Phone number should be formatted."); } boolean phoneNumberExists = userService.findUserByPhoneNumber(phoneNumber).isPresent(); if (phoneNumberExists) { return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("Phone number already exists for another user."); } } Optional<User> optionalUser = mongoService.updateFields(user.getId(), updates, User.class); if (optionalUser.isPresent()) { return ResponseEntity.ok(optionalUser.get()); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"); } } @Operation(summary = "Add to User Favorite", description = "사용자의 즐겨찾기에 화장품을 추가합니다. [USER 권한 필요]", tags = {"User Profile Operations"}, parameters = {@Parameter(name = "cosmeticId", description = "화장품의 ID")}, responses = {@ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema(implementation = User.class))), @ApiResponse(responseCode = "404", description = "사용자 또는 화장품을 찾을 수 없음", content = @Content(schema = @Schema(implementation = String.class)))}) @PostMapping("/favorites/{cosmeticId}") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<User> addToUserFavorite(@Parameter(hidden = true) @AuthenticatedUser User user, @PathVariable String cosmeticId) { return cosmeticRepository.findById(cosmeticId) .map(cosmetic -> { boolean wasNotFavoriteBefore = !user.getCosmeticIds().contains(cosmeticId); // Add to user db var updatedUser = userService.addCosmeticById(user.getId(), cosmeticId); if (wasNotFavoriteBefore) { // Update cosmetic's favCount only if it was not already a favorite
package app.beautyminder.controller.user; @Slf4j @RequiredArgsConstructor @RestController @RequestMapping("/user") // Base path for all routes in this controller public class UserController { private final UserService userService; private final MongoService mongoService; private final SmsService smsService; private final TokenService tokenService; private final FileStorageService fileStorageService; private final CosmeticRepository cosmeticRepository; private final ReviewRepository reviewRepository; private final CosmeticRankService cosmeticRankService; @Value("${server.default.user}") private String defaultUserProfilePic; @Value("${server.default.admin}") private String defaultAdminProfilePic; @Operation(summary = "Request Email verification", description = "이메일 인증 요청입니다.", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "User signup details"), tags = {"User Operations"}, responses = {@ApiResponse(responseCode = "200", description = "사용자가 생성됨", content = @Content(schema = @Schema(implementation = SignUpResponse.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = SignUpResponse.class)))}) @PostMapping("/email-verification/request") public ResponseEntity<?> requestVerificationToken(@RequestParam String email) { // Check if email already exists in the system if (userService.findByEmail(email).isPresent()) { return ResponseEntity.badRequest().body("Email already in use."); } var token = userService.requestPassCode(email); return ResponseEntity.ok(token); } @Operation(summary = "Verify Email", description = "이메일 인증 확인입니다.") @PostMapping("/email-verification/verify") // Here if the token is valid, it sets verified. public ResponseEntity<?> verifyEmail(@RequestParam String token) { // Validate the token boolean isValid = tokenService.validateVerificationToken(token); if (!isValid) { // Handle invalid or expired token return ResponseEntity.badRequest().body("Invalid or expired token."); } // Token is valid return ResponseEntity.ok("Email verified successfully."); } // Standard user sign-up @Operation(summary = "Standard User Signup", description = "표준 사용자 등록을 처리합니다.", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "User signup details"), tags = {"User Operations"}, responses = {@ApiResponse(responseCode = "200", description = "사용자가 생성됨", content = @Content(schema = @Schema(implementation = SignUpResponse.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = SignUpResponse.class)))}) @PostMapping("/signup") public ResponseEntity<SignUpResponse> signUp(@Valid @org.springframework.web.bind.annotation.RequestBody AddUserRequest request) { // Check if email is verified if (!tokenService.isEmailVerified(request.getEmail())) { return ResponseEntity.badRequest().body(new SignUpResponse("Email not verified.", null)); } try { String userId = userService.saveUser(request).getId(); User user = userService.findById(userId); tokenService.removePassCodeFor(request.getEmail()); return ResponseEntity.ok(new SignUpResponse("A user is created", user)); } catch (Exception e) { // On error, check whether the token is expired, if so remove tokenService.validateAgainAndRemove(request.getEmail()); return ResponseEntity.badRequest().body(new SignUpResponse(e.getMessage(), null)); } } // Admin sign-up @Operation(summary = "Admin User Signup", description = "관리자 사용자 등록을 처리합니다.", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "Admin signup details"), tags = {"User Operations"}, responses = {@ApiResponse(responseCode = "200", description = "관리자가 생성됨", content = @Content(schema = @Schema(implementation = SignUpResponse.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = SignUpResponse.class)))}) @PostMapping("/signup-admin") public ResponseEntity<SignUpResponse> signUpAdmin(@RequestBody AddUserRequest request) { try { String userId = userService.saveAdmin(request).getId(); User user = userService.findById(userId); return ResponseEntity.ok(new SignUpResponse("A user is created", user)); } catch (IllegalArgumentException e) { return ResponseEntity.badRequest().body(new SignUpResponse(e.getMessage(), null)); } } @Operation(summary = "User Logout", description = "사용자 로그아웃", tags = {"User Operations"}, responses = {@ApiResponse(responseCode = "200", description = "성공적으로 로그아웃됨", content = @Content(schema = @Schema(implementation = String.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content)}) @GetMapping("/logout") public ResponseEntity<String> logout(HttpServletRequest request, HttpServletResponse response) { new SecurityContextLogoutHandler().logout(request, response, SecurityContextHolder.getContext().getAuthentication()); return ResponseEntity.ok("Logged out successfully"); } @Operation(summary = "User Deletion", description = "사용자 삭제 by userId [USER 권한 필요]", tags = {"User Operations"}) @DeleteMapping("/delete") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<?> deleteUser(@Parameter(hidden = true) @AuthenticatedUser User user) { userService.deleteUserAndRelatedData(user.getId()); return ResponseEntity.ok("a user is deleted successfully"); } @Operation(summary = "Get user profile", description = "사용자 프로필 가져오기 [USER 권한 필요]", tags = {"User Profile Operations"}, responses = {@ApiResponse(responseCode = "200", description = "유저 데이터 성공적으로 불러옴", content = @Content(schema = @Schema(implementation = User.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = User.class)))}) @GetMapping("/me") public ResponseEntity<User> getProfile(@Parameter(hidden = true) @AuthenticatedUser User user) { return ResponseEntity.ok(user); } @Operation(summary = "Update user profile", description = "사용자 프로필 업데이트 [USER 권한 필요]", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(schema = @Schema(implementation = Map.class), examples = @ExampleObject(name = "typicalResponses", value = """ { "baumann": "DSNT", "nickname": "Que" } """, summary = "지원 필드: nickname, profileImage, phoneNumber\n프사는 http 링크, phoneNumber은 중복을 체크함. (01012345678 형식, - 없음)")), description = "Profile updates"), tags = {"User Profile Operations"}, responses = {@ApiResponse(responseCode = "200", description = "유저 업데이트 완료", content = @Content(schema = @Schema(implementation = User.class))), @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = User.class)))}) // org.springframework.web.bind.annotation. // Can take any field in User class @PatchMapping("/update") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<?> updateProfile(@Parameter(hidden = true) @AuthenticatedUser User user, @RequestBody Map<String, Object> updates) { // 전화번호 미리 체크 if (updates.containsKey("phoneNumber")) { String phoneNumber = (String) updates.get("phoneNumber"); if (!mongoService.isValidKoreanPhoneNumber(phoneNumber)) { return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("Phone number should be formatted."); } boolean phoneNumberExists = userService.findUserByPhoneNumber(phoneNumber).isPresent(); if (phoneNumberExists) { return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("Phone number already exists for another user."); } } Optional<User> optionalUser = mongoService.updateFields(user.getId(), updates, User.class); if (optionalUser.isPresent()) { return ResponseEntity.ok(optionalUser.get()); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"); } } @Operation(summary = "Add to User Favorite", description = "사용자의 즐겨찾기에 화장품을 추가합니다. [USER 권한 필요]", tags = {"User Profile Operations"}, parameters = {@Parameter(name = "cosmeticId", description = "화장품의 ID")}, responses = {@ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema(implementation = User.class))), @ApiResponse(responseCode = "404", description = "사용자 또는 화장품을 찾을 수 없음", content = @Content(schema = @Schema(implementation = String.class)))}) @PostMapping("/favorites/{cosmeticId}") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<User> addToUserFavorite(@Parameter(hidden = true) @AuthenticatedUser User user, @PathVariable String cosmeticId) { return cosmeticRepository.findById(cosmeticId) .map(cosmetic -> { boolean wasNotFavoriteBefore = !user.getCosmeticIds().contains(cosmeticId); // Add to user db var updatedUser = userService.addCosmeticById(user.getId(), cosmeticId); if (wasNotFavoriteBefore) { // Update cosmetic's favCount only if it was not already a favorite
mongoService.updateFields(cosmeticId, Map.of("favCount", cosmetic.getFavCount() + 1), Cosmetic.class);
0
2023-11-01 12:37:16+00:00
24k
FallenDeity/GameEngine2DJava
src/main/java/engine/scenes/LevelEditorScene.java
[ { "identifier": "Sprite", "path": "src/main/java/engine/components/sprites/Sprite.java", "snippet": "public class Sprite {\n\tprivate Texture texture = null;\n\tprivate float width = 0, height = 0;\n\tprivate Vector2f[] texCoords =\n\t\t\tnew Vector2f[]{\n\t\t\t\t\tnew Vector2f(1, 1), new Vector2f(1, 0)...
import engine.components.*; import engine.components.sprites.Sprite; import engine.components.sprites.SpriteSheet; import engine.editor.JImGui; import engine.physics2d.components.Box2DCollider; import engine.physics2d.components.RigidBody2D; import engine.physics2d.enums.BodyType; import engine.renderer.Sound; import engine.ruby.Window; import engine.util.AssetPool; import engine.util.CONSTANTS; import engine.util.PipeDirection; import engine.util.Prefabs; import imgui.ImGui; import imgui.ImVec2; import org.joml.Vector2f; import java.io.File; import java.util.ArrayList; import java.util.List;
16,342
package engine.scenes; public class LevelEditorScene extends Scene { private final SpriteSheet blocks; private final GameObject editor; public LevelEditorScene() { editor = createGameObject("Editor"); editor.setNotSerializable(); editor.addComponent(new MouseControls()); editor.addComponent(new KeyControls()); editor.addComponent(new GridLines()); editor.addComponent(new EditorCamera(camera)); editor.addComponent(new GizmoSystem(this, editor)); blocks = AssetPool.getSpriteSheet(CONSTANTS.BLOCK_SHEET_PATH.getValue(), 16, 16, 0, 81); addGameObjectToScene(editor); AssetPool.getSound(CONSTANTS.SOUNDS_PATH.getValue() + "main-theme-overworld.ogg").stop(); } public boolean gizmoActive() { GizmoSystem gizmoSystem = editor.getComponent(GizmoSystem.class); return gizmoSystem.gizmoActive(); } private List<Sound> loadSounds() { String sound_dir = CONSTANTS.SOUNDS_PATH.getValue(); File[] files = new File(sound_dir).listFiles(); if (files != null) { for (File file : files) { if (file.isFile() && file.getName().endsWith(".ogg")) { String path = file.getAbsolutePath(); AssetPool.getSound(path, false); } } } return new ArrayList<>(AssetPool.getSounds()); } private void addBlock(SpriteSheet sheet, int i, ImVec2 windowSize, ImVec2 itemSpacing, float windowX, boolean decoration) { Sprite sprite = sheet.getSprite(i); float spriteWidth = sprite.getWidth() * 3, spriteHeight = sprite.getHeight() * 3; Vector2f[] texCoords = sprite.getTexCoords(); int id = sprite.getTextureID(); ImGui.pushID(i); if (ImGui.imageButton( id, spriteWidth, spriteHeight, texCoords[2].x, texCoords[0].y, texCoords[0].x, texCoords[2].y)) { GameObject ob = Prefabs.generateSpriteObject(sprite, CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue()); if (!decoration) { RigidBody2D rb = new RigidBody2D(); rb.setBodyType(BodyType.STATIC); ob.addComponent(rb); Box2DCollider collider = new Box2DCollider(); collider.setHalfSize(new Vector2f(CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue())); ob.addComponent(collider); ob.addComponent(new Ground()); if (i == 12 || i == 33) ob.addComponent(new BreakableBrick()); } editor.getComponent(MouseControls.class).setActiveGameObject(ob); } ImGui.popID(); ImVec2 lastButtonPos = ImGui.getItemRectMax(); float lastButtonX = lastButtonPos.x; float nextButtonX = lastButtonX + itemSpacing.x + sprite.getWidth() * 3; if (i + 1 < blocks.getNumSprites() && nextButtonX < windowX + windowSize.x - 30) { ImGui.sameLine(); } } @Override public void imGui() { ImGui.begin("Editor");
package engine.scenes; public class LevelEditorScene extends Scene { private final SpriteSheet blocks; private final GameObject editor; public LevelEditorScene() { editor = createGameObject("Editor"); editor.setNotSerializable(); editor.addComponent(new MouseControls()); editor.addComponent(new KeyControls()); editor.addComponent(new GridLines()); editor.addComponent(new EditorCamera(camera)); editor.addComponent(new GizmoSystem(this, editor)); blocks = AssetPool.getSpriteSheet(CONSTANTS.BLOCK_SHEET_PATH.getValue(), 16, 16, 0, 81); addGameObjectToScene(editor); AssetPool.getSound(CONSTANTS.SOUNDS_PATH.getValue() + "main-theme-overworld.ogg").stop(); } public boolean gizmoActive() { GizmoSystem gizmoSystem = editor.getComponent(GizmoSystem.class); return gizmoSystem.gizmoActive(); } private List<Sound> loadSounds() { String sound_dir = CONSTANTS.SOUNDS_PATH.getValue(); File[] files = new File(sound_dir).listFiles(); if (files != null) { for (File file : files) { if (file.isFile() && file.getName().endsWith(".ogg")) { String path = file.getAbsolutePath(); AssetPool.getSound(path, false); } } } return new ArrayList<>(AssetPool.getSounds()); } private void addBlock(SpriteSheet sheet, int i, ImVec2 windowSize, ImVec2 itemSpacing, float windowX, boolean decoration) { Sprite sprite = sheet.getSprite(i); float spriteWidth = sprite.getWidth() * 3, spriteHeight = sprite.getHeight() * 3; Vector2f[] texCoords = sprite.getTexCoords(); int id = sprite.getTextureID(); ImGui.pushID(i); if (ImGui.imageButton( id, spriteWidth, spriteHeight, texCoords[2].x, texCoords[0].y, texCoords[0].x, texCoords[2].y)) { GameObject ob = Prefabs.generateSpriteObject(sprite, CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue()); if (!decoration) { RigidBody2D rb = new RigidBody2D(); rb.setBodyType(BodyType.STATIC); ob.addComponent(rb); Box2DCollider collider = new Box2DCollider(); collider.setHalfSize(new Vector2f(CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue())); ob.addComponent(collider); ob.addComponent(new Ground()); if (i == 12 || i == 33) ob.addComponent(new BreakableBrick()); } editor.getComponent(MouseControls.class).setActiveGameObject(ob); } ImGui.popID(); ImVec2 lastButtonPos = ImGui.getItemRectMax(); float lastButtonX = lastButtonPos.x; float nextButtonX = lastButtonX + itemSpacing.x + sprite.getWidth() * 3; if (i + 1 < blocks.getNumSprites() && nextButtonX < windowX + windowSize.x - 30) { ImGui.sameLine(); } } @Override public void imGui() { ImGui.begin("Editor");
Window.getScene().setDefaultScene(JImGui.inputText("Scene Name", Window.getScene().getDefaultScene()));
2
2023-11-04 13:19:21+00:00
24k
RezaGooner/University-food-ordering
Frames/LoginFrame.java
[ { "identifier": "CustomRendererLoginHistory", "path": "Classes/Theme/CustomRendererLoginHistory.java", "snippet": "public class CustomRendererLoginHistory extends DefaultTableCellRenderer {\r\n private static final long serialVersionUID = 1L;\r\n\r\n @Override\r\n public Component getTableCellR...
import Classes.Theme.CustomRendererLoginHistory; import Classes.Theme.CustomRendererOrderCount; import Classes.Theme.StyledButtonUI; import Frames.Order.UniversitySelfRestaurant; import Frames.Profile.ChangePasswordFrame; import Frames.Profile.ForgotPassword; import Frames.Profile.NewUserFrame; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Scanner; import static Classes.Pathes.FilesPath.*; import static Classes.Theme.SoundEffect.*; import static Frames.Admin.AdminWindow.OpenAdminWindow;
20,337
public LoginFrame() { setTitle("ورود"); setIconImage(icon.getImage()); setSize(375, 175); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setBackground(colorBackground); JLabel idLabel = new JLabel(": شماره دانشجویی"); idLabel.setHorizontalAlignment(SwingConstants.CENTER); idField = new JTextField(10); JLabel passwordLabel = new JLabel(": کلمـــه عبــور"); passwordLabel.setHorizontalAlignment(SwingConstants.CENTER); passwordField = new JPasswordField(10); passwordField.setEchoChar('\u25cf'); showPasswordCheckbox = new JCheckBox("نمایش کلمه عبور"); showPasswordCheckbox.setBackground(colorBackground); JButton loginButton = new JButton("ورود"); loginButton.setUI(new StyledButtonUI()); loginButton.setBackground(colorButton); statusLabel = new JLabel(""); JPanel panel = new JPanel(new GridLayout(4, 1)); panel.setBackground(colorBackground); panel.add(idLabel); panel.add(idField); panel.add(passwordLabel); panel.add(passwordField); panel.add(showPasswordCheckbox); panel.add(loginButton); panel.add(statusLabel); JButton helpButton = new JButton("اطلاعیه ها"); panel.add(helpButton); helpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame subWindow = new JFrame(); setIconImage(icon.getImage()); subWindow.setTitle(""); subWindow.setSize(300, 200); subWindow.setVisible(true); try { FileReader fileReader = new FileReader(HelpPath); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); while ((line = bufferedReader.readLine()) != null) { if (line.equals("***")) { panel.add(new JSeparator(JSeparator.HORIZONTAL)); } else { JLabel label = new JLabel(line); label.setFont(new Font("Arial", Font.BOLD, 20)); label.setForeground(Color.RED); panel.add(label); } } JScrollPane scrollPane = new JScrollPane(panel); subWindow.add(scrollPane); bufferedReader.close(); } catch (IOException exception) { } JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(helpButton, BorderLayout.CENTER); panel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { subWindow.setVisible(true); } }); add(panel); FontMetrics fm = helpButton.getFontMetrics(helpButton.getFont()); int textWidth = fm.stringWidth(helpButton.getText()); int textHeight = fm.getHeight(); helpButton.setPreferredSize(new Dimension(textWidth, textHeight)); } }); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(colorButton); setJMenuBar(menuBar); JMenu menu = new JMenu("حساب کاربری"); menu.setBackground(colorButton); menuBar.add(menu); JMenuItem adminItem = new JMenuItem("ورود مدیریت"); adminItem.setBackground(colorButton); menu.add(adminItem); JMenuItem forgotItem = new JMenuItem("فراموشی رمز"); forgotItem.setBackground(colorButton); menu.add(forgotItem); JMenuItem changePassword = new JMenuItem("تغییر رمز"); changePassword.setBackground(colorButton); menu.add(changePassword); JMenuItem historyLoginButton = new JMenuItem("سابقه ورود"); historyLoginButton.setBackground(colorButton); menu.add(historyLoginButton); JMenuItem newUserItem = new JMenuItem("جدید"); newUserItem.setBackground(colorButton); menu.add(newUserItem); JMenuItem exitItem = new JMenuItem("خروج"); exitItem.setBackground(colorButton); menuBar.add(exitItem); adminItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try {
package Frames; /* این کد یک فریم ورود به برنامه است که به کاربران اجازه می‌دهد شماره دانشجویی و رمز عبور خود را وارد کنند و سپس توسط برنامه بررسی شود که این اطلاعات معتبر هستند یا خیر. برای بررسی صحت اطلاعات، برنامه از یک فایل متنی استفاده می‌کند که شماره دانشجویی و رمز عبور کاربران را در خود نگه می‌دارد. در صورتی که اطلاعات وارد شده توسط کاربر با اطلاعات موجود در فایل مطابقت داشته باشد، کاربر به صفحه اصلی برنامه برای سفارش غذا هدایت می‌شود. در غیر این صورت، پیام خطا به کاربر نمایش داده می‌شود و از کاربر خواسته می‌شود تا اطلاعات خود را بررسی کرده و مجدداً وارد کند یا در صورت لزوم، از طریق گزینه هایی که برای او نمایش داده می‌شود، اقدام به بازیابی رمز عبور یا ساخت حساب جدید کند. */ public class LoginFrame extends JFrame { public static boolean isNumeric(String str) { if (str == null || str.length() == 0) { return false; } try { Long.parseLong(str); } catch (NumberFormatException nfe) { return false; } return true; } private static JTextField idField; private final JPasswordField passwordField; private final JLabel statusLabel; private final JCheckBox showPasswordCheckbox; private String name , lastName , gender , organization; public static Color colorButton = new Color(255,255,255); public static Color colorBackground = new Color(241,255,85); private String tempID; public LoginFrame() { setTitle("ورود"); setIconImage(icon.getImage()); setSize(375, 175); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setBackground(colorBackground); JLabel idLabel = new JLabel(": شماره دانشجویی"); idLabel.setHorizontalAlignment(SwingConstants.CENTER); idField = new JTextField(10); JLabel passwordLabel = new JLabel(": کلمـــه عبــور"); passwordLabel.setHorizontalAlignment(SwingConstants.CENTER); passwordField = new JPasswordField(10); passwordField.setEchoChar('\u25cf'); showPasswordCheckbox = new JCheckBox("نمایش کلمه عبور"); showPasswordCheckbox.setBackground(colorBackground); JButton loginButton = new JButton("ورود"); loginButton.setUI(new StyledButtonUI()); loginButton.setBackground(colorButton); statusLabel = new JLabel(""); JPanel panel = new JPanel(new GridLayout(4, 1)); panel.setBackground(colorBackground); panel.add(idLabel); panel.add(idField); panel.add(passwordLabel); panel.add(passwordField); panel.add(showPasswordCheckbox); panel.add(loginButton); panel.add(statusLabel); JButton helpButton = new JButton("اطلاعیه ها"); panel.add(helpButton); helpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame subWindow = new JFrame(); setIconImage(icon.getImage()); subWindow.setTitle(""); subWindow.setSize(300, 200); subWindow.setVisible(true); try { FileReader fileReader = new FileReader(HelpPath); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); while ((line = bufferedReader.readLine()) != null) { if (line.equals("***")) { panel.add(new JSeparator(JSeparator.HORIZONTAL)); } else { JLabel label = new JLabel(line); label.setFont(new Font("Arial", Font.BOLD, 20)); label.setForeground(Color.RED); panel.add(label); } } JScrollPane scrollPane = new JScrollPane(panel); subWindow.add(scrollPane); bufferedReader.close(); } catch (IOException exception) { } JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(helpButton, BorderLayout.CENTER); panel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { subWindow.setVisible(true); } }); add(panel); FontMetrics fm = helpButton.getFontMetrics(helpButton.getFont()); int textWidth = fm.stringWidth(helpButton.getText()); int textHeight = fm.getHeight(); helpButton.setPreferredSize(new Dimension(textWidth, textHeight)); } }); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(colorButton); setJMenuBar(menuBar); JMenu menu = new JMenu("حساب کاربری"); menu.setBackground(colorButton); menuBar.add(menu); JMenuItem adminItem = new JMenuItem("ورود مدیریت"); adminItem.setBackground(colorButton); menu.add(adminItem); JMenuItem forgotItem = new JMenuItem("فراموشی رمز"); forgotItem.setBackground(colorButton); menu.add(forgotItem); JMenuItem changePassword = new JMenuItem("تغییر رمز"); changePassword.setBackground(colorButton); menu.add(changePassword); JMenuItem historyLoginButton = new JMenuItem("سابقه ورود"); historyLoginButton.setBackground(colorButton); menu.add(historyLoginButton); JMenuItem newUserItem = new JMenuItem("جدید"); newUserItem.setBackground(colorButton); menu.add(newUserItem); JMenuItem exitItem = new JMenuItem("خروج"); exitItem.setBackground(colorButton); menuBar.add(exitItem); adminItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try {
OpenAdminWindow();
9
2023-11-03 08:35:22+00:00
24k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/objects/GameAnalyser.java
[ { "identifier": "AnalysisManager", "path": "src/main/java/com/chadfield/shogiexplorer/main/AnalysisManager.java", "snippet": "public class AnalysisManager {\n\n private AnalysisManager() {\n throw new IllegalStateException(\"Utility class\");\n }\n\n public static void save(Analysis anal...
import com.chadfield.shogiexplorer.main.AnalysisManager; import com.chadfield.shogiexplorer.main.EngineManager; import com.chadfield.shogiexplorer.main.SFENParser; import com.chadfield.shogiexplorer.objects.Board.Turn; import com.chadfield.shogiexplorer.utils.NotationUtils; import com.chadfield.shogiexplorer.utils.ParserUtils; import static com.chadfield.shogiexplorer.utils.StringUtils.getFileExtension; import com.ibm.icu.text.Transliterator; import java.awt.Rectangle; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultIntervalXYDataset;
15,774
stdin.write(("setoption USI_OwnBook value false\n").getBytes()); getReady(); stdin.write(("position sfen " + position.getGameSFEN() + "\n").getBytes()); stdin.write(("go infinite\n").getBytes()); stdin.flush(); String line; while (!bestMove && (line = bufferedReader.readLine()) != null) { if (Thread.interrupted()) { stdin.write(("stop\n").getBytes()); stdin.flush(); } updateTableModel(line, tableModel, positionTurn, sfen); } stdin.flush(); analysisParam.setPositionAnalysisList(positionAnalysisList); analysing.set(false); } private Turn getTurn(Position position) { if (position.getGameSFEN().split(" ")[1].contentEquals("b")) { return Turn.SENTE; } else { return Turn.GOTE; } } private void updateTableModel(String line, DefaultTableModel tableModel, Turn positionTurn, String sfen) { if (!line.contains("bestmove")) { ArrayList<Position> pvPositionList = getPVPositionList(sfen, line, null); Object[] tableInsert = getTableInsert(line, positionTurn, pvPositionList, tableModel); positionAnalysisList.add(rowNum, pvPositionList); tableModel.insertRow(rowNum, tableInsert); } else { bestMove = true; } } private Object[] getTableInsert(String line, Turn positionTurn, ArrayList<Position> pvPositionList, DefaultTableModel tableModel) { turn = positionTurn; boolean lower = false; boolean upper = false; boolean foundPV = false; String depth = null; String seldepth = null; String nodes = null; int score; String[] splitLine = line.split(" "); for (int i = 0; i < splitLine.length; i++) { if (!foundPV) { switch (splitLine[i]) { case "multipv" -> { int thisMultiPv = Integer.parseInt(splitLine[i + 1]); if (thisMultiPv < multiPV) { positionAnalysisList.add(0, null); tableModel.insertRow(0, new Object[]{}); } multiPV = thisMultiPv; rowNum = multiPV - 1; } case "depth" -> { depth = splitLine[i + 1]; } case "seldepth" -> { seldepth = splitLine[i + 1]; } case "nodes" -> { nodes = splitLine[i + 1]; } case "lowerbound" -> { lower = true; } case "upperbound" -> { upper = true; } case "cp" -> { score = getScore(turn, splitLine[i + 1]); scoreStr = Integer.toString(score); } case "mate" -> { int mateNum = Integer.parseInt(splitLine[i + 1]); if (mateNum > 0) { score = 31111; } else { score = -31111; } if (turn == Turn.GOTE) { score = -score; } if (score > 0) { scoreStr = "+Mate:" + Math.abs(mateNum); } else { scoreStr = "-Mate:" + Math.abs(mateNum); } } case "pv" -> { foundPV = true; } default -> { // Unwanted element. } } } } StringBuilder pvBuilder = new StringBuilder(""); for (Position position : pvPositionList) { pvBuilder.append(position.getNotation().getJapanese()); pvBuilder.append("\u3000"); } String pvStr = pvBuilder.toString().trim(); String lowUp = getLowUpString(lower, upper); return new Object[]{depth + "/" + seldepth, nodes, scoreStr, lowUp, pvStr}; } private void initializeEngine(Engine engine) { try { ProcessBuilder processBuilder;
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.objects; public class GameAnalyser { private Process process; private OutputStream stdin; private BufferedReader bufferedReader; private String lastScore = ""; private String opinion = ""; private int analysisTimePerMove; private static final int ANALYSIS_MISTAKE_THRESHOLD = 250; private static final int ANALYSIS_BLUNDER_THRESHOLD = 500; private static final int ANALYSIS_IGNORE_THRESHOLD = 2000; double[] x1Start; double[] x1; double[] x1End; double[] y1Start; double[] y1; double[] y1End; double[][] data1; double[] x2Start; double[] x2; double[] x2End; double[] y2Start; double[] y2; double[] y2End; double[][] data2; XYPlot plot; int range; String scoreStr; List<Integer> scoreList; JRadioButtonMenuItem graphView1; JRadioButtonMenuItem graphView2; JRadioButtonMenuItem graphView3; JButton stopAnalysisToolbarButton; JMenuItem stopAnalysisMenuItem; JMenuItem analyseGameMenuItem; JButton analyseGameToolbarButton; JMenuItem analysePositionMenuItem; JButton analysePositionToolbarButton; JMenuItem resumeAnalysisMenuItem; JButton resumeAnalysisToolbarButton; Transliterator trans = Transliterator.getInstance("Halfwidth-Fullwidth"); Turn turn; int multiPV; int rowNum; boolean bestMove; boolean interrupted; private List<List<Position>> positionAnalysisList; private static final String OS = System.getProperty("os.name").toLowerCase(); public static final boolean IS_WINDOWS = (OS.contains("win")); public static final boolean IS_MAC = (OS.contains("mac")); public static final boolean IS_LINUX = (OS.contains("nux")); public void analyse(Game game, Engine engine, JList<String> moveList, JTable analysisTable, AnalysisParameter analysisParam, AtomicBoolean analysing, XYPlot plot, boolean saveAnalysis, boolean resume) throws IOException { analysing.set(true); this.plot = plot; DefaultIntervalXYDataset plotDataset = (DefaultIntervalXYDataset) plot.getDataset(); this.analysisTimePerMove = analysisParam.getAnalysisTimePerMove(); this.graphView1 = analysisParam.getGraphView1(); this.graphView2 = analysisParam.getGraphView2(); this.graphView3 = analysisParam.getGraphView3(); this.stopAnalysisToolbarButton = analysisParam.getHaltAnalysisButton(); this.stopAnalysisMenuItem = analysisParam.getStopAnalysisMenuItem(); this.analyseGameMenuItem = analysisParam.getAnalyseGameMenuItem(); this.analyseGameToolbarButton = analysisParam.getAnalyseGameToolbarButton(); this.analysePositionMenuItem = analysisParam.getAnalysePositionMenuItem(); this.analysePositionToolbarButton = analysisParam.getAnalysePositionToolbarButton(); this.resumeAnalysisMenuItem = analysisParam.getResumeAnalysisMenuItem(); this.resumeAnalysisToolbarButton = analysisParam.getResumeAnalysisToolbarButton(); this.x1Start = analysisParam.getX1Start(); this.x1 = analysisParam.getX1(); this.x1End = analysisParam.getX1End(); this.y1Start = analysisParam.getY1Start(); this.y1 = analysisParam.getY1(); this.y1End = analysisParam.getY1End(); this.x2Start = analysisParam.getX2Start(); this.x2 = analysisParam.getX2(); this.x2End = analysisParam.getX2End(); this.y2Start = analysisParam.getY2Start(); this.y2 = analysisParam.getY2(); this.y2End = analysisParam.getY2End(); initializeEngine(engine); initiateUSIProtocol(); setOptions(engine); getReady(); String engineMove = null; String japaneseMove = null; String sfen = null; String lastSFEN = null; int count = 1; int resumeCount = 1; if (resume) { resumeCount = analysisTable.getRowCount(); } Coordinate lastDestination = null; Coordinate previousMoveDestination = null; if (!resume) { game.setAnalysisPositionList(new ArrayList<>()); } scoreList = new ArrayList<>(); game.isHandicap(); if (game.isHandicap()) { turn = Turn.GOTE; } else { turn = Turn.SENTE; } interrupted = false; for (Position position : game.getPositionList()) { if (engineMove != null) { if (!resume || count > resumeCount) { updateMoveList(moveList, count); analysePosition(game, lastSFEN, engineMove, japaneseMove, analysisTable, plotDataset, count, turn, previousMoveDestination); } if (interrupted) { break; } previousMoveDestination = lastDestination; count++; turn = ParserUtils.switchTurn(turn); } lastSFEN = sfen; sfen = position.getGameSFEN(); engineMove = position.getNotation().getEngineMove(); if (turn == Turn.SENTE) { japaneseMove = trans.transliterate(" ☗" + position.getNotation().getJapanese()); } else { japaneseMove = trans.transliterate(" ☖" + position.getNotation().getJapanese()); } lastDestination = position.getDestination(); } if (!interrupted) { updateMoveList(moveList, count); analysePosition(game, lastSFEN, engineMove, japaneseMove, analysisTable, plotDataset, count, turn, previousMoveDestination); count++; } if (analysisTable.getRowCount() > 0) { analysisTable.setRowSelectionInterval(count - 2, count - 2); analysisTable.scrollRectToVisible(new Rectangle(analysisTable.getCellRect(count - 2, 0, true))); } quitEngine(); stopAnalysisMenuItem.setEnabled(false); stopAnalysisToolbarButton.setEnabled(false); analyseGameMenuItem.setEnabled(true); analyseGameToolbarButton.setEnabled(true); analysePositionMenuItem.setEnabled(true); analysePositionToolbarButton.setEnabled(true); resumeAnalysisMenuItem.setEnabled(count < game.getPositionList().size() - 1); resumeAnalysisToolbarButton.setEnabled(resumeAnalysisMenuItem.isEnabled()); analysisParam.setX1Start(x1Start); analysisParam.setX1(x1); analysisParam.setX1End(x1End); analysisParam.setY1Start(y1Start); analysisParam.setY1(y1); analysisParam.setY1End(y1End); analysisParam.setX2Start(x2Start); analysisParam.setX2(x2); analysisParam.setX2End(x2End); analysisParam.setY2Start(y2Start); analysisParam.setY2(y2); analysisParam.setY2End(y2End); if (saveAnalysis) { Analysis analysis = new Analysis(); analysis.setAnalysisPositionList(game.getAnalysisPositionList()); List<Object[]> tableRows = new ArrayList<>(); DefaultTableModel analysisTableModel = (DefaultTableModel) analysisTable.getModel(); for (int i = 0; i < analysisTableModel.getRowCount(); i++) { tableRows.add(new Object[]{ analysisTableModel.getValueAt(i, 0), analysisTableModel.getValueAt(i, 1), analysisTableModel.getValueAt(i, 2), analysisTableModel.getValueAt(i, 3), analysisTableModel.getValueAt(i, 4) }); } analysis.setTableRows(tableRows); analysis.setScoreList(scoreList); AnalysisManager.save(analysis, analysisParam.getKifFile()); } analysing.set(false); } private void updateMoveList(JList<String> moveList, final int index) { try { java.awt.EventQueue.invokeAndWait(() -> moveList.setSelectedIndex(index)); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } catch (InvocationTargetException ex) { Logger.getLogger(GameAnalyser.class.getName()).log(Level.SEVERE, null, ex); } } public void analysePosition(Engine engine, AnalysisParameter analysisParam, AtomicBoolean analysing, Position position, JTable positionAnalysisTable) throws IOException { analysing.set(true); bestMove = false; positionAnalysisList = new ArrayList<>(); multiPV = 0; rowNum = 0; DefaultTableModel tableModel = (DefaultTableModel) positionAnalysisTable.getModel(); Turn positionTurn = getTurn(position); String sfen = position.getGameSFEN(); initializeEngine(engine); initiateUSIProtocol(); setOptions(engine); // Infinite analysis does not play well with opening books. stdin.write(("setoption USI_OwnBook value false\n").getBytes()); getReady(); stdin.write(("position sfen " + position.getGameSFEN() + "\n").getBytes()); stdin.write(("go infinite\n").getBytes()); stdin.flush(); String line; while (!bestMove && (line = bufferedReader.readLine()) != null) { if (Thread.interrupted()) { stdin.write(("stop\n").getBytes()); stdin.flush(); } updateTableModel(line, tableModel, positionTurn, sfen); } stdin.flush(); analysisParam.setPositionAnalysisList(positionAnalysisList); analysing.set(false); } private Turn getTurn(Position position) { if (position.getGameSFEN().split(" ")[1].contentEquals("b")) { return Turn.SENTE; } else { return Turn.GOTE; } } private void updateTableModel(String line, DefaultTableModel tableModel, Turn positionTurn, String sfen) { if (!line.contains("bestmove")) { ArrayList<Position> pvPositionList = getPVPositionList(sfen, line, null); Object[] tableInsert = getTableInsert(line, positionTurn, pvPositionList, tableModel); positionAnalysisList.add(rowNum, pvPositionList); tableModel.insertRow(rowNum, tableInsert); } else { bestMove = true; } } private Object[] getTableInsert(String line, Turn positionTurn, ArrayList<Position> pvPositionList, DefaultTableModel tableModel) { turn = positionTurn; boolean lower = false; boolean upper = false; boolean foundPV = false; String depth = null; String seldepth = null; String nodes = null; int score; String[] splitLine = line.split(" "); for (int i = 0; i < splitLine.length; i++) { if (!foundPV) { switch (splitLine[i]) { case "multipv" -> { int thisMultiPv = Integer.parseInt(splitLine[i + 1]); if (thisMultiPv < multiPV) { positionAnalysisList.add(0, null); tableModel.insertRow(0, new Object[]{}); } multiPV = thisMultiPv; rowNum = multiPV - 1; } case "depth" -> { depth = splitLine[i + 1]; } case "seldepth" -> { seldepth = splitLine[i + 1]; } case "nodes" -> { nodes = splitLine[i + 1]; } case "lowerbound" -> { lower = true; } case "upperbound" -> { upper = true; } case "cp" -> { score = getScore(turn, splitLine[i + 1]); scoreStr = Integer.toString(score); } case "mate" -> { int mateNum = Integer.parseInt(splitLine[i + 1]); if (mateNum > 0) { score = 31111; } else { score = -31111; } if (turn == Turn.GOTE) { score = -score; } if (score > 0) { scoreStr = "+Mate:" + Math.abs(mateNum); } else { scoreStr = "-Mate:" + Math.abs(mateNum); } } case "pv" -> { foundPV = true; } default -> { // Unwanted element. } } } } StringBuilder pvBuilder = new StringBuilder(""); for (Position position : pvPositionList) { pvBuilder.append(position.getNotation().getJapanese()); pvBuilder.append("\u3000"); } String pvStr = pvBuilder.toString().trim(); String lowUp = getLowUpString(lower, upper); return new Object[]{depth + "/" + seldepth, nodes, scoreStr, lowUp, pvStr}; } private void initializeEngine(Engine engine) { try { ProcessBuilder processBuilder;
if (!IS_WINDOWS && getFileExtension(engine.getPath()).contentEquals("exe")) {
6
2023-11-08 09:24:57+00:00
24k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/SysUserServiceImpl.java
[ { "identifier": "LoginAboutAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/LoginAboutAdapt.java", "snippet": "public class LoginAboutAdapt {\n\n public static final int USE_NAME_LENGTH = 8;\n\n /**\n * 构造token信息类\n *\n * @param saTokenInfo s...
import cn.dev33.satoken.secure.SaSecureUtil; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.codec.Base64; import cn.hutool.core.util.RandomUtil; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.provider.StaticCredentialProvider; import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient; import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest; import com.google.code.kaptcha.Producer; import com.qingmeng.config.adapt.LoginAboutAdapt; import com.qingmeng.config.adapt.UserInfoAdapt; import com.qingmeng.config.adapt.UserSettingAdapt; import com.qingmeng.config.cache.UserCache; import com.qingmeng.config.cache.UserFriendSettingCache; import com.qingmeng.config.cache.UserSettingCache; import com.qingmeng.constant.RedisConstant; import com.qingmeng.constant.SystemConstant; import com.qingmeng.dao.*; import com.qingmeng.dto.login.CheckFriendDTO; import com.qingmeng.dto.login.LoginParamDTO; import com.qingmeng.dto.login.RegisterDTO; import com.qingmeng.dto.user.AlterAccountDTO; import com.qingmeng.dto.user.AlterPersonalInfoDTO; import com.qingmeng.dto.user.PersonalPrivacySettingDTO; import com.qingmeng.entity.ChatFriendRoom; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserFriendSetting; import com.qingmeng.entity.SysUserPrivacySetting; import com.qingmeng.enums.user.LoginMethodEnum; import com.qingmeng.config.event.SysUserRegisterEvent; import com.qingmeng.exception.TalkTimeException; import com.qingmeng.service.SysUserFriendService; import com.qingmeng.service.SysUserService; import com.qingmeng.config.strategy.login.LoginFactory; import com.qingmeng.config.strategy.login.LoginStrategy; import com.qingmeng.utils.*; import com.qingmeng.vo.login.CaptchaVO; import com.qingmeng.vo.login.TokenInfoVO; import com.qingmeng.vo.user.*; import darabonba.core.client.ClientOverrideConfiguration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.FastByteArrayOutputStream; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit;
14,675
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:19:00 */ @Service public class SysUserServiceImpl implements SysUserService { public static final String MATH = "math"; public static final String CHAR = "char"; @Value("${alibaba.sms.accessKeyId}") private String aliAccessKeyId; @Value("${alibaba.sms.accessKeySecret}") private String aliAccessKeySecret; @Resource @Lazy
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:19:00 */ @Service public class SysUserServiceImpl implements SysUserService { public static final String MATH = "math"; public static final String CHAR = "char"; @Value("${alibaba.sms.accessKeyId}") private String aliAccessKeyId; @Value("${alibaba.sms.accessKeySecret}") private String aliAccessKeySecret; @Resource @Lazy
private LoginFactory loginFactory;
23
2023-11-07 16:04:55+00:00
24k
Griefed/AddEmAll
common/src/main/java/de/griefed/addemall/CommonClass.java
[ { "identifier": "GeneratedModBlocks", "path": "common/src/main/java/de/griefed/addemall/block/GeneratedModBlocks.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class GeneratedModBlocks {\n public static final RegistrationProvider<Block> BLOCKS = RegistrationProvider.get(Registry.BLOCK_REGIS...
import de.griefed.addemall.block.GeneratedModBlocks; import de.griefed.addemall.item.GeneratedModItems; import de.griefed.addemall.platform.Services; import net.minecraft.network.chat.Component; import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import java.util.List;
19,858
package de.griefed.addemall; // This class is part of the common project meaning it is shared between all supported loaders. Code written here can only // import and access the vanilla codebase, libraries used by vanilla, and optionally third party libraries that provide // common compatible binaries. This means common code can not directly use loader specific concepts such as Forge events // however it will be compatible with all supported mod loaders. public class CommonClass { // The loader specific projects are able to import and use any code from the common project. This allows you to // write the majority of your code here and load it from your loader specific projects. This example has some // code that gets invoked by the entry point of the loader specific projects. public static void init() { Constants.LOG.info("Hello from Common init on {}! we are currently in a {} environment!", Services.PLATFORM.getPlatformName(), Services.PLATFORM.getEnvironmentName()); // It is common for all supported loaders to provide a similar feature that can not be used directly in the // common code. A popular way to get around this is using Java's built-in service loader feature to create // your own abstraction layer. You can learn more about this in our provided services class. In this example // we have an interface in the common code and use a loader specific implementation to delegate our call to // the platform specific approach. if (Services.PLATFORM.isModLoaded("addemall")) { Constants.LOG.info("Hello to addemall"); } /*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###*/
package de.griefed.addemall; // This class is part of the common project meaning it is shared between all supported loaders. Code written here can only // import and access the vanilla codebase, libraries used by vanilla, and optionally third party libraries that provide // common compatible binaries. This means common code can not directly use loader specific concepts such as Forge events // however it will be compatible with all supported mod loaders. public class CommonClass { // The loader specific projects are able to import and use any code from the common project. This allows you to // write the majority of your code here and load it from your loader specific projects. This example has some // code that gets invoked by the entry point of the loader specific projects. public static void init() { Constants.LOG.info("Hello from Common init on {}! we are currently in a {} environment!", Services.PLATFORM.getPlatformName(), Services.PLATFORM.getEnvironmentName()); // It is common for all supported loaders to provide a similar feature that can not be used directly in the // common code. A popular way to get around this is using Java's built-in service loader feature to create // your own abstraction layer. You can learn more about this in our provided services class. In this example // we have an interface in the common code and use a loader specific implementation to delegate our call to // the platform specific approach. if (Services.PLATFORM.isModLoaded("addemall")) { Constants.LOG.info("Hello to addemall"); } /*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###*/
GeneratedModBlocks.loadClass();
0
2023-11-06 12:50:10+00:00
24k
dingodb/dingo-expr
test/src/test/java/io/dingodb/expr/test/cases/EvalConstProvider.java
[ { "identifier": "Types", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/Types.java", "snippet": "public final class Types {\n public static final NullType NULL = new NullType();\n public static final IntType INT = new IntType();\n public static final LongType LONG = new LongType();...
import com.google.common.collect.ImmutableMap; import io.dingodb.expr.runtime.type.Types; import io.dingodb.expr.runtime.utils.DateTimeUtils; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static io.dingodb.expr.runtime.expr.Exprs.ABS; import static io.dingodb.expr.runtime.expr.Exprs.ABS_C; import static io.dingodb.expr.runtime.expr.Exprs.ACOS; import static io.dingodb.expr.runtime.expr.Exprs.ADD; import static io.dingodb.expr.runtime.expr.Exprs.AND; import static io.dingodb.expr.runtime.expr.Exprs.AND_FUN; import static io.dingodb.expr.runtime.expr.Exprs.ARRAY; import static io.dingodb.expr.runtime.expr.Exprs.ASIN; import static io.dingodb.expr.runtime.expr.Exprs.ATAN; import static io.dingodb.expr.runtime.expr.Exprs.CASE; import static io.dingodb.expr.runtime.expr.Exprs.CEIL; import static io.dingodb.expr.runtime.expr.Exprs.CHAR_LENGTH; import static io.dingodb.expr.runtime.expr.Exprs.CONCAT; import static io.dingodb.expr.runtime.expr.Exprs.COS; import static io.dingodb.expr.runtime.expr.Exprs.COSH; import static io.dingodb.expr.runtime.expr.Exprs.DATEDIFF; import static io.dingodb.expr.runtime.expr.Exprs.DATE_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.DATE_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.DIV; import static io.dingodb.expr.runtime.expr.Exprs.EQ; import static io.dingodb.expr.runtime.expr.Exprs.EXP; import static io.dingodb.expr.runtime.expr.Exprs.FLOOR; import static io.dingodb.expr.runtime.expr.Exprs.FORMAT; import static io.dingodb.expr.runtime.expr.Exprs.FROM_UNIXTIME; import static io.dingodb.expr.runtime.expr.Exprs.GE; import static io.dingodb.expr.runtime.expr.Exprs.GT; import static io.dingodb.expr.runtime.expr.Exprs.HEX; import static io.dingodb.expr.runtime.expr.Exprs.INDEX; import static io.dingodb.expr.runtime.expr.Exprs.IS_FALSE; import static io.dingodb.expr.runtime.expr.Exprs.IS_NULL; import static io.dingodb.expr.runtime.expr.Exprs.IS_TRUE; import static io.dingodb.expr.runtime.expr.Exprs.LE; import static io.dingodb.expr.runtime.expr.Exprs.LEFT; import static io.dingodb.expr.runtime.expr.Exprs.LIST; import static io.dingodb.expr.runtime.expr.Exprs.LOCATE2; import static io.dingodb.expr.runtime.expr.Exprs.LOCATE3; import static io.dingodb.expr.runtime.expr.Exprs.LOG; import static io.dingodb.expr.runtime.expr.Exprs.LOWER; import static io.dingodb.expr.runtime.expr.Exprs.LT; import static io.dingodb.expr.runtime.expr.Exprs.LTRIM1; import static io.dingodb.expr.runtime.expr.Exprs.LTRIM2; import static io.dingodb.expr.runtime.expr.Exprs.MAP; import static io.dingodb.expr.runtime.expr.Exprs.MATCHES; import static io.dingodb.expr.runtime.expr.Exprs.MATCHES_NC; import static io.dingodb.expr.runtime.expr.Exprs.MAX; import static io.dingodb.expr.runtime.expr.Exprs.MID2; import static io.dingodb.expr.runtime.expr.Exprs.MID3; import static io.dingodb.expr.runtime.expr.Exprs.MIN; import static io.dingodb.expr.runtime.expr.Exprs.MOD; import static io.dingodb.expr.runtime.expr.Exprs.MUL; import static io.dingodb.expr.runtime.expr.Exprs.NE; import static io.dingodb.expr.runtime.expr.Exprs.NEG; import static io.dingodb.expr.runtime.expr.Exprs.NOT; import static io.dingodb.expr.runtime.expr.Exprs.OR; import static io.dingodb.expr.runtime.expr.Exprs.OR_FUN; import static io.dingodb.expr.runtime.expr.Exprs.POS; import static io.dingodb.expr.runtime.expr.Exprs.POW; import static io.dingodb.expr.runtime.expr.Exprs.REPEAT; import static io.dingodb.expr.runtime.expr.Exprs.REPLACE; import static io.dingodb.expr.runtime.expr.Exprs.REVERSE; import static io.dingodb.expr.runtime.expr.Exprs.RIGHT; import static io.dingodb.expr.runtime.expr.Exprs.ROUND1; import static io.dingodb.expr.runtime.expr.Exprs.ROUND2; import static io.dingodb.expr.runtime.expr.Exprs.RTRIM1; import static io.dingodb.expr.runtime.expr.Exprs.RTRIM2; import static io.dingodb.expr.runtime.expr.Exprs.SIN; import static io.dingodb.expr.runtime.expr.Exprs.SINH; import static io.dingodb.expr.runtime.expr.Exprs.SLICE; import static io.dingodb.expr.runtime.expr.Exprs.SUB; import static io.dingodb.expr.runtime.expr.Exprs.SUBSTR2; import static io.dingodb.expr.runtime.expr.Exprs.SUBSTR3; import static io.dingodb.expr.runtime.expr.Exprs.TAN; import static io.dingodb.expr.runtime.expr.Exprs.TANH; import static io.dingodb.expr.runtime.expr.Exprs.TIMESTAMP_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.TIMESTAMP_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.TIME_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.TIME_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TO_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TO_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TRIM1; import static io.dingodb.expr.runtime.expr.Exprs.TRIM2; import static io.dingodb.expr.runtime.expr.Exprs.UNIX_TIMESTAMP1; import static io.dingodb.expr.runtime.expr.Exprs.UPPER; import static io.dingodb.expr.runtime.expr.Exprs._CP1; import static io.dingodb.expr.runtime.expr.Exprs._CP2; import static io.dingodb.expr.runtime.expr.Exprs._CTF; import static io.dingodb.expr.runtime.expr.Exprs.op; import static io.dingodb.expr.runtime.expr.Exprs.val; import static io.dingodb.expr.runtime.expr.Val.NULL; import static io.dingodb.expr.runtime.expr.Val.NULL_BOOL; import static io.dingodb.expr.runtime.expr.Val.NULL_BYTES; import static io.dingodb.expr.runtime.expr.Val.NULL_DATE; import static io.dingodb.expr.runtime.expr.Val.NULL_DECIMAL; import static io.dingodb.expr.runtime.expr.Val.NULL_DOUBLE; import static io.dingodb.expr.runtime.expr.Val.NULL_FLOAT; import static io.dingodb.expr.runtime.expr.Val.NULL_INT; import static io.dingodb.expr.runtime.expr.Val.NULL_LONG; import static io.dingodb.expr.runtime.expr.Val.NULL_STRING; import static io.dingodb.expr.runtime.expr.Val.NULL_TIME; import static io.dingodb.expr.runtime.expr.Val.NULL_TIMESTAMP; import static io.dingodb.expr.test.ExprsHelper.bytes; import static io.dingodb.expr.test.ExprsHelper.date; import static io.dingodb.expr.test.ExprsHelper.dec; import static io.dingodb.expr.test.ExprsHelper.sec; import static io.dingodb.expr.test.ExprsHelper.time; import static io.dingodb.expr.test.ExprsHelper.ts; import static org.junit.jupiter.params.provider.Arguments.arguments;
19,191
arguments(op(CONCAT, "Alice", NULL_STRING), null), arguments(op(CONCAT, "Alice", "Betty"), "AliceBetty"), arguments(op(LOWER, "HeLLo"), "hello"), arguments(op(UPPER, "HeLLo"), "HELLO"), arguments(op(LEFT, NULL_STRING, 1), null), arguments(op(LEFT, "Alice", NULL_INT), null), arguments(op(LEFT, "Alice", 0), ""), arguments(op(LEFT, "Alice", -1), ""), arguments(op(LEFT, "Alice", 10), "Alice"), arguments(op(LEFT, "Alice", 3), "Ali"), arguments(op(LEFT, "Alice", 3.5), "Alic"), arguments(op(RIGHT, NULL_STRING, 1), null), arguments(op(RIGHT, "Alice", NULL_INT), null), arguments(op(RIGHT, "Alice", 0), ""), arguments(op(RIGHT, "Alice", -1), ""), arguments(op(RIGHT, "Alice", 10), "Alice"), arguments(op(RIGHT, "Alice", 3), "ice"), arguments(op(RIGHT, "Alice", 3.5), "lice"), arguments(op(TRIM1, " HeLLo "), "HeLLo"), arguments(op(TRIM2, "aBcHeLLoaBcaBc", "aBc"), "HeLLo"), arguments(op(LTRIM1, NULL_STRING), null), arguments(op(LTRIM1, " HeLLo "), "HeLLo "), arguments(op(LTRIM2, "aBcaBcHeLLoaBc", "aBc"), "HeLLoaBc"), arguments(op(RTRIM1, NULL_STRING), null), arguments(op(RTRIM1, " HeLLo "), " HeLLo"), arguments(op(RTRIM2, "aBcHeLLoaBc", "aBc"), "aBcHeLLo"), arguments(op(SUBSTR2, "HeLLo", 2), "LLo"), arguments(op(SUBSTR2, "HeLLo", 2.5), "Lo"), arguments(op(SUBSTR3, "HeLLo", 1, 3), "eL"), arguments(op(MID2, "Alice", 2), "lice"), arguments(op(MID2, "Alice", 0), ""), arguments(op(MID2, "Alice", NULL_INT), null), arguments(op(MID2, "Alice", -2), "ce"), arguments(op(MID3, NULL_STRING, 0, 0), null), arguments(op(MID3, "Alice", NULL_INT, 0), null), arguments(op(MID3, "Alice", 1, NULL_INT), null), arguments(op(MID3, "Alice", 0, 0), ""), arguments(op(MID3, "Alice", 1, 0), ""), arguments(op(MID3, "Alice", 1, 3), "Ali"), arguments(op(MID3, "Alice", -1, 1), "e"), arguments(op(MID3, "Alice", -3, 2), "ic"), arguments(op(MID3, "Alice", -3, 1.5), "ic"), arguments(op(REPEAT, NULL_STRING, 3), null), arguments(op(REPEAT, "Abc", -1), ""), arguments(op(REPEAT, "Abc", 3), "AbcAbcAbc"), arguments(op(REPEAT, "Abc", 1.7), "AbcAbc"), arguments(op(REVERSE, NULL_STRING), null), arguments(op(REVERSE, "AbCdE"), "EdCbA"), arguments(op(REPLACE, "HeLLo", "eL", "El"), "HElLo"), arguments(op(REPLACE, NULL, "a", "b"), null), arguments(op(LOCATE2, NULL_STRING, "a"), null), arguments(op(LOCATE2, "at", "Water"), 2), arguments(op(LOCATE2, "am", "Water"), 0), arguments(op(LOCATE2, NULL_STRING, "Water"), null), arguments(op(LOCATE2, "", "Water"), 1), arguments(op(LOCATE3, "", "Water", 3), 3), arguments(op(LOCATE3, "a", "Banana", 3), 4), arguments(op(LOCATE3, "a", "Banana", 7), 0), arguments(op(LOCATE3, "a", "Banana", 3.5), 4), arguments(op(HEX, "414243"), "ABC".getBytes(StandardCharsets.UTF_8)), arguments(op(FORMAT, 100.21, 1), "100.2"), arguments(op(FORMAT, 99.00000, 2), "99.00"), arguments(op(FORMAT, 1220.532, 0), "1221"), arguments(op(FORMAT, 18, 2), "18.00"), arguments(op(FORMAT, 15354.6651, 1.6), "15354.67"), arguments(op(MATCHES, "abc123", ".*c\\d{2}."), true), arguments(op(MATCHES, "abc123", "c\\d{2}"), false), arguments(op(MATCHES, "abc123", "Abc\\d{3}"), false), arguments(op(MATCHES_NC, "abc123", "Abc\\d{3}"), true), arguments(op(_CTF, "%Y"), "uuuu"), arguments(op(_CTF, "%Y-%m-%d"), "uuuu'-'MM'-'dd"), arguments(op(_CTF, "%A%B%C"), "'ABC'"), arguments(op(_CTF, "Year: %Y, Month: %m"), "'Year: 'uuuu', Month: 'MM"), arguments(op(_CP1, "%"), ".*"), arguments(op(_CP1, "_"), "."), arguments(op(_CP1, "a_b%c"), "a.b.*c"), arguments(op(_CP1, "a\\_b\\%c"), "a_b%c"), arguments(op(_CP1, "a\\nb\\%c"), "a\\nb%c"), arguments(op(_CP2, "a\\_b\\%c", "|"), "a\\.b\\.*c"), arguments(op(_CP2, "a|_b|%c", "|"), "a_b%c"), // Date & times arguments(op(DATE_FORMAT1, 0), "1970-01-01"), arguments(op(DATE_FORMAT2, 0, "uuuu:MM:dd"), "1970:01:01"), arguments(op(DATE_FORMAT2, 0, op(_CTF, "%Y:%m:%d")), "1970:01:01"), arguments(op(TIME_FORMAT1, 0), "00:00:00"), arguments(op(TIME_FORMAT2, 0, "HH-mm-ss"), "00-00-00"), arguments(op(TIME_FORMAT2, 0, op(_CTF, "%H-%i-%s")), "00-00-00"), arguments( op(TIMESTAMP_FORMAT1, 0), DateTimeUtils.timestampFormat(new Timestamp(0), DateTimeUtils.DEFAULT_OUTPUT_TIMESTAMP_FORMATTER) ), arguments( op(TIMESTAMP_FORMAT2, 0, "uuuuMMddHHmmss"), DateTimeUtils.timestampFormat(new Timestamp(0), "uuuuMMddHHmmss") ), arguments( op(TIMESTAMP_FORMAT2, 0, op(_CTF, "%Y%m%d%H%i%s")), DateTimeUtils.timestampFormat(new Timestamp(0), "uuuuMMddHHmmss") ), arguments(op(FROM_UNIXTIME, 1), new Timestamp(sec(1L))), arguments(op(FROM_UNIXTIME, 1L), new Timestamp(sec(1L))), arguments(op(FROM_UNIXTIME, dec(1.23)), new Timestamp(sec(BigDecimal.valueOf(1.23)))), arguments(op(UNIX_TIMESTAMP1, ts(1L)), 1L), arguments(op(UNIX_TIMESTAMP1, 2L), 2L), arguments(op(UNIX_TIMESTAMP1, 3.5), 4L), arguments(op(DATEDIFF, 24L * 60L * 60L, 0L), 1L), // Collections arguments(op(ARRAY, 1, 2, 3), new int[]{1, 2, 3}), arguments(op(ARRAY, 1L, 2, 3), new long[]{1L, 2L, 3L}), arguments(op(ARRAY, 1L, 2.0, 3), new double[]{1.0, 2.0, 3.0}), arguments(op(LIST, 1, 2, 3), Arrays.asList(1, 2, 3)), arguments(op(LIST, 1L, 2, 3), Arrays.asList(1L, 2L, 3L)), arguments(op(LIST, 1L, 2.0, 3), Arrays.asList(1.0, 2.0, 3.0)), arguments(op(MAP, 'a', 1, 'b', 2), ImmutableMap.of('a', 1, 'b', 2)), arguments(op(MAP, 1, 1, 2, 2), ImmutableMap.of(1, 1, 2, 2)), arguments(op(MAP, '1', 1, 2, '2'), ImmutableMap.of('1', 1, 2, '2')), arguments(op(TO_ARRAY_INT, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}), arguments(op(TO_ARRAY_INT_C, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}),
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.test.cases; public class EvalConstProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Stream.of( // Values arguments(val(1), 1), arguments(val(2L), 2L), arguments(val(3.3f), 3.3f), arguments(val(4.4), 4.4), arguments(val(true), true), arguments(val(false), false), arguments(dec(5.5), BigDecimal.valueOf(5.5)), arguments(val("abc"), "abc"), arguments(bytes("123"), "123".getBytes(StandardCharsets.UTF_8)), arguments(date(1L), new Date(sec(1L))), arguments(time(2L), new Time(sec(2L))), arguments(ts(3L), new Timestamp(sec(3L))), arguments(val(null), null), // Castings arguments(op(TO_INT, 1), 1), arguments(op(TO_INT, 1L), 1), arguments(op(TO_INT_C, 1L), 1), arguments(op(TO_INT, 1.4f), 1), arguments(op(TO_INT_C, 1.4f), 1), arguments(op(TO_INT, 1.5f), 2), arguments(op(TO_INT_C, 1.5f), 2), arguments(op(TO_INT, 1.4), 1), arguments(op(TO_INT, 1.5), 2), arguments(op(TO_INT, true), 1), arguments(op(TO_INT, false), 0), arguments(op(TO_INT, dec(1.4)), 1), arguments(op(TO_INT_C, dec(1.4)), 1), arguments(op(TO_INT, dec(1.5)), 2), arguments(op(TO_INT_C, dec(1.5)), 2), arguments(op(TO_INT, "10"), 10), arguments(op(TO_LONG, 1), 1L), arguments(op(TO_LONG, 1L), 1L), arguments(op(TO_LONG, 1.4f), 1L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.5f), 2L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.4), 1L), arguments(op(TO_LONG, 1.5), 2L), arguments(op(TO_LONG, true), 1L), arguments(op(TO_LONG, false), 0L), arguments(op(TO_LONG, dec(1.4)), 1L), arguments(op(TO_LONG, dec(1.5)), 2L), arguments(op(TO_LONG, "10"), 10L), arguments(op(TO_FLOAT, 1), 1.0f), arguments(op(TO_FLOAT, 1L), 1.0f), arguments(op(TO_FLOAT, 1.4f), 1.4f), arguments(op(TO_FLOAT, 1.4), 1.4f), arguments(op(TO_FLOAT, true), 1.0f), arguments(op(TO_FLOAT, false), 0.0f), arguments(op(TO_FLOAT, dec(1.4)), 1.4f), arguments(op(TO_FLOAT, "12.3"), 12.3f), arguments(op(TO_DOUBLE, 1), 1.0), arguments(op(TO_DOUBLE, 1L), 1.0), arguments(op(TO_DOUBLE, 1.4f), 1.4), arguments(op(TO_DOUBLE, 1.4), 1.4), arguments(op(TO_DOUBLE, true), 1.0), arguments(op(TO_DOUBLE, false), 0.0), arguments(op(TO_DOUBLE, dec(1.4)), 1.4), arguments(op(TO_DOUBLE, "12.3"), 12.3), arguments(op(TO_BOOL, 1), true), arguments(op(TO_BOOL, 0), false), arguments(op(TO_BOOL, 1L), true), arguments(op(TO_BOOL, 0L), false), arguments(op(TO_BOOL, 1.4f), true), arguments(op(TO_BOOL, 0.0f), false), arguments(op(TO_BOOL, 1.4), true), arguments(op(TO_BOOL, 0.0), false), arguments(op(TO_BOOL, true), true), arguments(op(TO_BOOL, false), false), arguments(op(TO_BOOL, val(BigDecimal.ONE)), true), arguments(op(TO_BOOL, val(BigDecimal.ZERO)), false), arguments(op(TO_DECIMAL, 1), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1L), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1.4f), BigDecimal.valueOf(1.4f)), arguments(op(TO_DECIMAL, 1.4), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, true), BigDecimal.ONE), arguments(op(TO_DECIMAL, false), BigDecimal.ZERO), arguments(op(TO_DECIMAL, dec(1.4)), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, "12.3"), BigDecimal.valueOf(12.3)), arguments(op(TO_STRING, 1), "1"), arguments(op(TO_STRING, 1L), "1"), arguments(op(TO_STRING, 1.4f), "1.4"), arguments(op(TO_STRING, 1.4), "1.4"), arguments(op(TO_STRING, true), "true"), arguments(op(TO_STRING, false), "false"), arguments(op(TO_STRING, dec(12.3)), "12.3"), arguments(op(TO_STRING, "abc"), "abc"), arguments(op(TO_BYTES, bytes("abc")), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_BYTES, "abc"), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_DATE, 1), new Date(sec(1L))), arguments(op(TO_DATE, 1L), new Date(sec(1L))), arguments(op(TO_DATE, "1970-01-01"), new Date(sec(0L))), arguments(op(TO_DATE, date(1L)), new Date(sec(1L))), arguments(op(TO_TIME, 1), new Time(sec(1L))), arguments(op(TO_TIME, 1L), new Time(sec(1L))), arguments(op(TO_TIME, "00:00:00"), new Time(sec(0L))), arguments(op(TO_TIME, time(1L)), new Time(sec(1L))), arguments(op(TO_TIMESTAMP, 1), new Timestamp(sec(1L))), arguments(op(TO_TIMESTAMP, 1L), new Timestamp(sec(1L))), arguments( op(TO_TIMESTAMP, "1970-01-01 00:00:00"), DateTimeUtils.parseTimestamp("1970-01-01 00:00:00") ), arguments(op(TO_TIMESTAMP, ts(1L)), new Timestamp(sec(1L))), // Arithmetics arguments(op(POS, 1), 1), arguments(op(POS, 1L), 1L), arguments(op(POS, 1.1f), 1.1f), arguments(op(POS, 1.1), 1.1), arguments(op(POS, dec(1.1)), BigDecimal.valueOf(1.1)), arguments(op(NEG, 1), -1), arguments(op(NEG, 1L), -1L), arguments(op(NEG, 1.1f), -1.1f), arguments(op(NEG, 1.1), -1.1), arguments(op(NEG, dec(1.1)), BigDecimal.valueOf(-1.1)), arguments(op(ADD, 1, 2), 3), arguments(op(ADD, 1L, 2L), 3L), arguments(op(ADD, 1.1f, 2.2f), 3.3f), arguments(op(ADD, 1.1, 2.2), 3.3), arguments(op(ADD, dec(1.1), dec(2.2)), BigDecimal.valueOf(3.3)), arguments(op(ADD, 1, 2L), 3L), arguments(op(ADD, 1L, 2.2f), 3.2f), arguments(op(ADD, 1.1f, 2.2), 3.3), arguments(op(ADD, 1.1, dec(2.2)), BigDecimal.valueOf(3.3)), arguments(op(ADD, "a", "bc"), "abc"), arguments(op(SUB, 1, 2), -1), arguments(op(SUB, 1L, 2L), -1L), arguments(op(SUB, 1.1f, 2.2f), -1.1f), arguments(op(SUB, 1.1, 2.2), -1.1), arguments(op(SUB, dec(1.1), dec(2.2)), BigDecimal.valueOf(-1.1)), arguments(op(SUB, 1, 2L), -1L), arguments(op(SUB, 1L, 2.2f), -1.2f), arguments(op(SUB, 1.1f, 2.2), -1.1), arguments(op(SUB, 1.1, dec(2.2)), BigDecimal.valueOf(-1.1)), arguments(op(MUL, 1, 2), 2), arguments(op(MUL, 1L, 2L), 2L), arguments(op(MUL, 1.1f, 2.2f), 2.42f), arguments(op(MUL, 1.1, 2.2), 2.42), arguments(op(MUL, dec(1.1), dec(2.2)), BigDecimal.valueOf(2.42)), arguments(op(MUL, 1, 2L), 2L), arguments(op(MUL, 1L, 2.2f), 2.2f), arguments(op(MUL, 1.1f, 2.2), 2.42), arguments(op(MUL, 1.1, dec(2.2)), BigDecimal.valueOf(2.42)), arguments(op(DIV, 1, 2), 0), arguments(op(DIV, 1L, 2L), 0L), arguments(op(DIV, 1.1f, 2.2f), 0.5f), arguments(op(DIV, 1.1, 2.2), 0.5), arguments(op(DIV, dec(1.1), dec(2.2)), BigDecimal.valueOf(0.5)), arguments(op(DIV, 1, 2L), 0L), arguments(op(DIV, 1L, 2.0f), 0.5f), arguments(op(DIV, 1.1f, 2.2), 0.5), arguments(op(DIV, 1.1, dec(2.2)), BigDecimal.valueOf(0.5)), arguments(op(DIV, 1, 0), null), arguments(op(DIV, 1.1f, 0.0f), null), arguments(op(DIV, 1.2, 0.0), null), arguments(op(DIV, dec(1.3), dec(0)), null), // Relations arguments(op(EQ, 1, 1), true), arguments(op(EQ, 1L, 2L), false), arguments(op(EQ, 1.1f, 1.1f), true), arguments(op(EQ, 1.1, 2.2), false), arguments(op(EQ, true, true), true), arguments(op(EQ, dec(1.1), dec(2.2)), false), arguments(op(EQ, "abc", "abc"), true), arguments(op(EQ, date(1L), date(2L)), false), arguments(op(EQ, time(1L), time(1L)), true), arguments(op(EQ, ts(2L), ts(1L)), false), arguments(op(NE, 1, 1), false), arguments(op(NE, 1L, 2L), true), arguments(op(NE, 1.1f, 1.1f), false), arguments(op(NE, 1.1, 2.2), true), arguments(op(NE, true, true), false), arguments(op(NE, dec(1.1), dec(2.2)), true), arguments(op(NE, "abc", "abc"), false), arguments(op(NE, date(1L), date(2L)), true), arguments(op(NE, time(1L), time(1L)), false), arguments(op(NE, ts(2L), ts(1L)), true), arguments(op(GT, 1, 1), false), arguments(op(GT, 1L, 2L), false), arguments(op(GT, 1.1f, 1.1f), false), arguments(op(GT, 1.1, 2.2), false), arguments(op(GT, true, true), false), arguments(op(GT, dec(1.1), dec(2.2)), false), arguments(op(GT, "abc", "abc"), false), arguments(op(GT, date(1L), date(2L)), false), arguments(op(GT, time(1L), time(1L)), false), arguments(op(GT, ts(2L), ts(1L)), true), arguments(op(GE, 1, 1), true), arguments(op(GE, 1L, 2L), false), arguments(op(GE, 1.1f, 1.1f), true), arguments(op(GE, 1.1, 2.2), false), arguments(op(GE, true, true), true), arguments(op(GE, dec(1.1), dec(2.2)), false), arguments(op(GE, "abc", "abc"), true), arguments(op(GE, date(1L), date(2L)), false), arguments(op(GE, time(1L), time(1L)), true), arguments(op(GE, ts(2L), ts(1L)), true), arguments(op(LT, 1, 1), false), arguments(op(LT, 1L, 2L), true), arguments(op(LT, 1.1f, 1.1f), false), arguments(op(LT, 1.1, 2.2), true), arguments(op(LT, true, true), false), arguments(op(LT, dec(1.1), dec(2.2)), true), arguments(op(LT, "abc", "abc"), false), arguments(op(LT, date(1L), date(2L)), true), arguments(op(LT, time(1L), time(1L)), false), arguments(op(LT, ts(2L), ts(1L)), false), arguments(op(LE, 1, 1), true), arguments(op(LE, 1L, 2L), true), arguments(op(LE, 1.1f, 1.1f), true), arguments(op(LE, 1.1, 2.2), true), arguments(op(LE, true, true), true), arguments(op(LE, dec(1.1), dec(2.2)), true), arguments(op(LE, "abc", "abc"), true), arguments(op(LE, date(1L), date(2L)), true), arguments(op(LE, time(1L), time(1L)), true), arguments(op(LE, ts(2L), ts(1L)), false), // Logics arguments(op(AND, false, false), false), arguments(op(AND, false, true), false), arguments(op(AND, false, NULL_BOOL), false), arguments(op(AND, true, false), false), arguments(op(AND, true, true), true), arguments(op(AND, true, NULL_BOOL), null), arguments(op(AND, NULL_BOOL, false), false), arguments(op(AND, NULL_BOOL, true), null), arguments(op(AND, NULL_BOOL, NULL_BOOL), null), arguments(op(OR, false, false), false), arguments(op(OR, false, true), true), arguments(op(OR, false, NULL_BOOL), null), arguments(op(OR, true, false), true), arguments(op(OR, true, true), true), arguments(op(OR, true, NULL_BOOL), true), arguments(op(OR, NULL_BOOL, false), null), arguments(op(OR, NULL_BOOL, true), true), arguments(op(OR, NULL_BOOL, NULL_BOOL), null), arguments(op(NOT, false), true), arguments(op(NOT, true), false), arguments(op(NOT, NULL_BOOL), null), arguments(op(AND_FUN, true, false, true), false), arguments(op(AND_FUN, true, NULL_BOOL, true), null), arguments(op(AND_FUN, true, true, true), true), arguments(op(OR_FUN, true, false, true), true), arguments(op(OR_FUN, false, NULL_BOOL, false), null), arguments(op(OR_FUN, false, false, false), false), // Specials arguments(op(IS_NULL, 1), false), arguments(op(IS_NULL, NULL_INT), true), arguments(op(IS_NULL, 1L), false), arguments(op(IS_NULL, NULL_LONG), true), arguments(op(IS_NULL, 1.1f), false), arguments(op(IS_NULL, NULL_FLOAT), true), arguments(op(IS_NULL, 1.1), false), arguments(op(IS_NULL, NULL_DOUBLE), true), arguments(op(IS_NULL, false), false), arguments(op(IS_NULL, NULL_BOOL), true), arguments(op(IS_NULL, dec(1)), false), arguments(op(IS_NULL, NULL_DECIMAL), true), arguments(op(IS_NULL, ""), false), arguments(op(IS_NULL, NULL_STRING), true), arguments(op(IS_NULL, bytes("")), false), arguments(op(IS_NULL, NULL_BYTES), true), arguments(op(IS_NULL, date(0)), false), arguments(op(IS_NULL, NULL_DATE), true), arguments(op(IS_NULL, time(0)), false), arguments(op(IS_NULL, NULL_TIME), true), arguments(op(IS_NULL, ts(0)), false), arguments(op(IS_NULL, NULL_TIMESTAMP), true), arguments(op(IS_TRUE, 1), true), arguments(op(IS_TRUE, 0), false), arguments(op(IS_TRUE, NULL_INT), false), arguments(op(IS_TRUE, 1L), true), arguments(op(IS_TRUE, 0L), false), arguments(op(IS_TRUE, NULL_LONG), false), arguments(op(IS_TRUE, 1.1f), true), arguments(op(IS_TRUE, 0.0f), false), arguments(op(IS_TRUE, NULL_FLOAT), false), arguments(op(IS_TRUE, 1.1), true), arguments(op(IS_TRUE, 0.0), false), arguments(op(IS_TRUE, NULL_DOUBLE), false), arguments(op(IS_TRUE, true), true), arguments(op(IS_TRUE, false), false), arguments(op(IS_TRUE, NULL_BOOL), false), arguments(op(IS_TRUE, dec(1)), true), arguments(op(IS_TRUE, dec(0)), false), arguments(op(IS_TRUE, NULL_DECIMAL), false), arguments(op(IS_TRUE, "abc"), false), arguments(op(IS_TRUE, ""), false), arguments(op(IS_TRUE, NULL_STRING), false), arguments(op(IS_TRUE, bytes("abc")), false), arguments(op(IS_TRUE, bytes("")), false), arguments(op(IS_TRUE, NULL_BYTES), false), arguments(op(IS_TRUE, date(0)), true), arguments(op(IS_TRUE, NULL_DATE), false), arguments(op(IS_TRUE, time(0)), true), arguments(op(IS_TRUE, NULL_TIME), false), arguments(op(IS_TRUE, ts(0)), true), arguments(op(IS_TRUE, NULL_TIMESTAMP), false), arguments(op(IS_FALSE, 1), false), arguments(op(IS_FALSE, 0), true), arguments(op(IS_FALSE, NULL_INT), false), arguments(op(IS_FALSE, 1L), false), arguments(op(IS_FALSE, 0L), true), arguments(op(IS_FALSE, NULL_LONG), false), arguments(op(IS_FALSE, 1.1f), false), arguments(op(IS_FALSE, 0.0f), true), arguments(op(IS_FALSE, NULL_FLOAT), false), arguments(op(IS_FALSE, 1.1), false), arguments(op(IS_FALSE, 0.0), true), arguments(op(IS_FALSE, NULL_DOUBLE), false), arguments(op(IS_FALSE, true), false), arguments(op(IS_FALSE, false), true), arguments(op(IS_FALSE, NULL_BOOL), false), arguments(op(IS_FALSE, dec(1)), false), arguments(op(IS_FALSE, dec(0)), true), arguments(op(IS_FALSE, NULL_DECIMAL), false), arguments(op(IS_FALSE, "abc"), true), arguments(op(IS_FALSE, ""), true), arguments(op(IS_FALSE, NULL_STRING), false), arguments(op(IS_FALSE, bytes("abc")), true), arguments(op(IS_FALSE, bytes("")), true), arguments(op(IS_FALSE, NULL_BYTES), false), arguments(op(IS_FALSE, date(0)), false), arguments(op(IS_FALSE, NULL_DATE), false), arguments(op(IS_FALSE, time(0)), false), arguments(op(IS_FALSE, NULL_TIME), false), arguments(op(IS_FALSE, ts(0)), false), arguments(op(IS_FALSE, NULL_TIMESTAMP), false), arguments(op(CASE, 100), 100), arguments(op(CASE, true, 1, 100), 1), arguments(op(CASE, false, 1, true, 2, 100), 2), // Mathematics arguments(op(ABS, -1), 1), arguments(op(ABS, 1), 1), arguments(op(ABS, -1L), 1L), arguments(op(ABS, 1L), 1L), arguments(op(ABS, -0.5f), 0.5f), arguments(op(ABS, 0.5f), 0.5f), arguments(op(ABS, -0.5), 0.5), arguments(op(ABS, 0.5), 0.5), arguments(op(ABS, dec(-0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS, dec(0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS_C, -1), 1), arguments(op(ABS_C, 1), 1), arguments(op(ABS_C, -1L), 1L), arguments(op(ABS_C, 1L), 1L), arguments(op(ABS_C, -0.5f), 0.5f), arguments(op(ABS_C, 0.5f), 0.5f), arguments(op(ABS_C, -0.5), 0.5), arguments(op(ABS_C, 0.5), 0.5), arguments(op(ABS_C, dec(-0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS_C, dec(0.5)), BigDecimal.valueOf(0.5)), arguments(op(MIN, 1, 2), 1), arguments(op(MIN, 1L, 2L), 1L), arguments(op(MIN, 1.1f, 2.2f), 1.1f), arguments(op(MIN, 1.1, 2.2), 1.1), arguments(op(MIN, dec(1.1), dec(2.2)), BigDecimal.valueOf(1.1)), arguments(op(MIN, "abc", "def"), "abc"), arguments(op(MIN, date(1L), date(2L)), new Date(sec(1L))), arguments(op(MIN, time(1L), time(2L)), new Time(sec(1L))), arguments(op(MIN, ts(1L), ts(2L)), new Timestamp(sec(1L))), arguments(op(MAX, 1, 2), 2), arguments(op(MAX, 1L, 2L), 2L), arguments(op(MAX, 1.1f, 2.2f), 2.2f), arguments(op(MAX, 1.1, 2.2), 2.2), arguments(op(MAX, dec(1.1), dec(2.2)), BigDecimal.valueOf(2.2)), arguments(op(MAX, "abc", "def"), "def"), arguments(op(MAX, date(1L), date(2L)), new Date(sec(2L))), arguments(op(MAX, time(1L), time(2L)), new Time(sec(2L))), arguments(op(MAX, ts(1L), ts(2L)), new Timestamp(sec(2L))), arguments(op(MOD, 4, 3), 1), arguments(op(MOD, -4, 3), -1), arguments(op(MOD, 1, 0), null), arguments(op(MOD, 4L, -3L), 1L), arguments(op(MOD, -4L, -3L), -1L), arguments(op(MOD, 1L, 0L), null), arguments(op(MOD, dec(5.0), dec(2.5)), BigDecimal.valueOf(0.0)), arguments(op(MOD, dec(5.1), dec(2.5)), BigDecimal.valueOf(0.1)), arguments(op(MOD, dec(5.1), dec(0)), null), arguments(op(SIN, 0), 0.0), arguments(op(SIN, Math.PI / 6), 0.5), arguments(op(SIN, Math.PI / 2), 1.0), arguments(op(SIN, 5 * Math.PI / 6), 0.5), arguments(op(SIN, Math.PI), 0.0), arguments(op(SIN, 7 * Math.PI / 6), -0.5), arguments(op(SIN, 3 * Math.PI / 2), -1.0), arguments(op(SIN, 11 * Math.PI / 6), -0.5), arguments(op(SIN, 2 * Math.PI), 0.0), arguments(op(COS, 0), 1.0), arguments(op(COS, Math.PI / 3), 0.5), arguments(op(COS, Math.PI / 2), 0.0), arguments(op(COS, 2 * Math.PI / 3), -0.5), arguments(op(COS, Math.PI), -1.0), arguments(op(COS, 4 * Math.PI / 3), -0.5), arguments(op(COS, 3 * Math.PI / 2), 0.0), arguments(op(COS, 5 * Math.PI / 3), 0.5), arguments(op(COS, 2 * Math.PI), 1.0), arguments(op(TAN, 0), 0.0), arguments(op(TAN, Math.PI / 4), 1.0), arguments(op(TAN, 3 * Math.PI / 4), -1.0), arguments(op(TAN, Math.PI), 0.0), arguments(op(TAN, 5 * Math.PI / 4), 1.0), arguments(op(TAN, 7 * Math.PI / 4), -1.0), arguments(op(TAN, 2 * Math.PI), 0.0), arguments(op(ASIN, -1), -Math.PI / 2), arguments(op(ASIN, -0.5), -Math.PI / 6), arguments(op(ASIN, 0), 0.0), arguments(op(ASIN, 0.5), Math.PI / 6), arguments(op(ASIN, 1), Math.PI / 2), arguments(op(ACOS, -1), Math.PI), arguments(op(ACOS, -0.5), 2 * Math.PI / 3), arguments(op(ACOS, 0), Math.PI / 2), arguments(op(ACOS, 0.5), Math.PI / 3), arguments(op(ACOS, 1), 0.0), arguments(op(ATAN, -1), -Math.PI / 4), arguments(op(ATAN, 0), 0.0), arguments(op(ATAN, 1), Math.PI / 4), arguments(op(SINH, 0), 0.0), arguments(op(COSH, 0), 1.0), arguments(op(TANH, 0), 0.0), arguments(op(EXP, 0), 1.0), arguments(op(EXP, 1), Math.exp(1.0)), arguments(op(LOG, Math.E), 1.0), arguments(op(LOG, 1.0 / Math.E), -1.0), arguments(op(CEIL, 1), 1), arguments(op(CEIL, 1L), 1L), arguments(op(CEIL, 2.3f), 3.0), arguments(op(CEIL, 3.4), 4.0), arguments(op(CEIL, dec(1.23)), BigDecimal.valueOf(2)), arguments(op(FLOOR, 1), 1), arguments(op(FLOOR, 1L), 1L), arguments(op(FLOOR, 2.5f), 2.0), arguments(op(FLOOR, 3.6), 3.0), arguments(op(FLOOR, dec(1.23)), BigDecimal.valueOf(1)), arguments(op(POW, 2, 3), 8.0), arguments(op(POW, 3, 3), 27.0), arguments(op(POW, -3.1, 3), -29.791), arguments(op(POW, "10", -2), 0.01), arguments(op(ROUND2, 123, -2), 100), arguments(op(ROUND2, 12.677, 2), 12.68), arguments(op(ROUND2, 195334.12, -4), 200000.0), arguments(op(ROUND2, -155.586, -2), -200.0), arguments(op(ROUND2, 101, -2), 100), arguments(op(ROUND2, 101.0, -2), 100.0), arguments(op(ROUND2, 105, -2), 100), arguments(op(ROUND2, dec(105), -1), BigDecimal.valueOf(110)), arguments(op(ROUND2, 105, "-2"), 100), arguments(op(ROUND1, 10), 10), arguments(op(ROUND2, 3.6, 0), 4.0), arguments(op(ROUND1, 3.4), 3.0), // Strings arguments(op(CHAR_LENGTH, NULL_STRING), null), arguments(op(CHAR_LENGTH, ""), 0), arguments(op(CHAR_LENGTH, "Alice"), 5), arguments(op(CONCAT, NULL_STRING, "Betty"), null), arguments(op(CONCAT, "Alice", NULL_STRING), null), arguments(op(CONCAT, "Alice", "Betty"), "AliceBetty"), arguments(op(LOWER, "HeLLo"), "hello"), arguments(op(UPPER, "HeLLo"), "HELLO"), arguments(op(LEFT, NULL_STRING, 1), null), arguments(op(LEFT, "Alice", NULL_INT), null), arguments(op(LEFT, "Alice", 0), ""), arguments(op(LEFT, "Alice", -1), ""), arguments(op(LEFT, "Alice", 10), "Alice"), arguments(op(LEFT, "Alice", 3), "Ali"), arguments(op(LEFT, "Alice", 3.5), "Alic"), arguments(op(RIGHT, NULL_STRING, 1), null), arguments(op(RIGHT, "Alice", NULL_INT), null), arguments(op(RIGHT, "Alice", 0), ""), arguments(op(RIGHT, "Alice", -1), ""), arguments(op(RIGHT, "Alice", 10), "Alice"), arguments(op(RIGHT, "Alice", 3), "ice"), arguments(op(RIGHT, "Alice", 3.5), "lice"), arguments(op(TRIM1, " HeLLo "), "HeLLo"), arguments(op(TRIM2, "aBcHeLLoaBcaBc", "aBc"), "HeLLo"), arguments(op(LTRIM1, NULL_STRING), null), arguments(op(LTRIM1, " HeLLo "), "HeLLo "), arguments(op(LTRIM2, "aBcaBcHeLLoaBc", "aBc"), "HeLLoaBc"), arguments(op(RTRIM1, NULL_STRING), null), arguments(op(RTRIM1, " HeLLo "), " HeLLo"), arguments(op(RTRIM2, "aBcHeLLoaBc", "aBc"), "aBcHeLLo"), arguments(op(SUBSTR2, "HeLLo", 2), "LLo"), arguments(op(SUBSTR2, "HeLLo", 2.5), "Lo"), arguments(op(SUBSTR3, "HeLLo", 1, 3), "eL"), arguments(op(MID2, "Alice", 2), "lice"), arguments(op(MID2, "Alice", 0), ""), arguments(op(MID2, "Alice", NULL_INT), null), arguments(op(MID2, "Alice", -2), "ce"), arguments(op(MID3, NULL_STRING, 0, 0), null), arguments(op(MID3, "Alice", NULL_INT, 0), null), arguments(op(MID3, "Alice", 1, NULL_INT), null), arguments(op(MID3, "Alice", 0, 0), ""), arguments(op(MID3, "Alice", 1, 0), ""), arguments(op(MID3, "Alice", 1, 3), "Ali"), arguments(op(MID3, "Alice", -1, 1), "e"), arguments(op(MID3, "Alice", -3, 2), "ic"), arguments(op(MID3, "Alice", -3, 1.5), "ic"), arguments(op(REPEAT, NULL_STRING, 3), null), arguments(op(REPEAT, "Abc", -1), ""), arguments(op(REPEAT, "Abc", 3), "AbcAbcAbc"), arguments(op(REPEAT, "Abc", 1.7), "AbcAbc"), arguments(op(REVERSE, NULL_STRING), null), arguments(op(REVERSE, "AbCdE"), "EdCbA"), arguments(op(REPLACE, "HeLLo", "eL", "El"), "HElLo"), arguments(op(REPLACE, NULL, "a", "b"), null), arguments(op(LOCATE2, NULL_STRING, "a"), null), arguments(op(LOCATE2, "at", "Water"), 2), arguments(op(LOCATE2, "am", "Water"), 0), arguments(op(LOCATE2, NULL_STRING, "Water"), null), arguments(op(LOCATE2, "", "Water"), 1), arguments(op(LOCATE3, "", "Water", 3), 3), arguments(op(LOCATE3, "a", "Banana", 3), 4), arguments(op(LOCATE3, "a", "Banana", 7), 0), arguments(op(LOCATE3, "a", "Banana", 3.5), 4), arguments(op(HEX, "414243"), "ABC".getBytes(StandardCharsets.UTF_8)), arguments(op(FORMAT, 100.21, 1), "100.2"), arguments(op(FORMAT, 99.00000, 2), "99.00"), arguments(op(FORMAT, 1220.532, 0), "1221"), arguments(op(FORMAT, 18, 2), "18.00"), arguments(op(FORMAT, 15354.6651, 1.6), "15354.67"), arguments(op(MATCHES, "abc123", ".*c\\d{2}."), true), arguments(op(MATCHES, "abc123", "c\\d{2}"), false), arguments(op(MATCHES, "abc123", "Abc\\d{3}"), false), arguments(op(MATCHES_NC, "abc123", "Abc\\d{3}"), true), arguments(op(_CTF, "%Y"), "uuuu"), arguments(op(_CTF, "%Y-%m-%d"), "uuuu'-'MM'-'dd"), arguments(op(_CTF, "%A%B%C"), "'ABC'"), arguments(op(_CTF, "Year: %Y, Month: %m"), "'Year: 'uuuu', Month: 'MM"), arguments(op(_CP1, "%"), ".*"), arguments(op(_CP1, "_"), "."), arguments(op(_CP1, "a_b%c"), "a.b.*c"), arguments(op(_CP1, "a\\_b\\%c"), "a_b%c"), arguments(op(_CP1, "a\\nb\\%c"), "a\\nb%c"), arguments(op(_CP2, "a\\_b\\%c", "|"), "a\\.b\\.*c"), arguments(op(_CP2, "a|_b|%c", "|"), "a_b%c"), // Date & times arguments(op(DATE_FORMAT1, 0), "1970-01-01"), arguments(op(DATE_FORMAT2, 0, "uuuu:MM:dd"), "1970:01:01"), arguments(op(DATE_FORMAT2, 0, op(_CTF, "%Y:%m:%d")), "1970:01:01"), arguments(op(TIME_FORMAT1, 0), "00:00:00"), arguments(op(TIME_FORMAT2, 0, "HH-mm-ss"), "00-00-00"), arguments(op(TIME_FORMAT2, 0, op(_CTF, "%H-%i-%s")), "00-00-00"), arguments( op(TIMESTAMP_FORMAT1, 0), DateTimeUtils.timestampFormat(new Timestamp(0), DateTimeUtils.DEFAULT_OUTPUT_TIMESTAMP_FORMATTER) ), arguments( op(TIMESTAMP_FORMAT2, 0, "uuuuMMddHHmmss"), DateTimeUtils.timestampFormat(new Timestamp(0), "uuuuMMddHHmmss") ), arguments( op(TIMESTAMP_FORMAT2, 0, op(_CTF, "%Y%m%d%H%i%s")), DateTimeUtils.timestampFormat(new Timestamp(0), "uuuuMMddHHmmss") ), arguments(op(FROM_UNIXTIME, 1), new Timestamp(sec(1L))), arguments(op(FROM_UNIXTIME, 1L), new Timestamp(sec(1L))), arguments(op(FROM_UNIXTIME, dec(1.23)), new Timestamp(sec(BigDecimal.valueOf(1.23)))), arguments(op(UNIX_TIMESTAMP1, ts(1L)), 1L), arguments(op(UNIX_TIMESTAMP1, 2L), 2L), arguments(op(UNIX_TIMESTAMP1, 3.5), 4L), arguments(op(DATEDIFF, 24L * 60L * 60L, 0L), 1L), // Collections arguments(op(ARRAY, 1, 2, 3), new int[]{1, 2, 3}), arguments(op(ARRAY, 1L, 2, 3), new long[]{1L, 2L, 3L}), arguments(op(ARRAY, 1L, 2.0, 3), new double[]{1.0, 2.0, 3.0}), arguments(op(LIST, 1, 2, 3), Arrays.asList(1, 2, 3)), arguments(op(LIST, 1L, 2, 3), Arrays.asList(1L, 2L, 3L)), arguments(op(LIST, 1L, 2.0, 3), Arrays.asList(1.0, 2.0, 3.0)), arguments(op(MAP, 'a', 1, 'b', 2), ImmutableMap.of('a', 1, 'b', 2)), arguments(op(MAP, 1, 1, 2, 2), ImmutableMap.of(1, 1, 2, 2)), arguments(op(MAP, '1', 1, 2, '2'), ImmutableMap.of('1', 1, 2, '2')), arguments(op(TO_ARRAY_INT, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}), arguments(op(TO_ARRAY_INT_C, op(ARRAY, 1.1, 2.2, 3.3, 4.4, 5.5)), new int[]{1, 2, 3, 4, 6}),
arguments(op(TO_ARRAY_LONG, op(ARRAY, "1", "2", "3")), new long[]{1L, 2L, 3L}),
87
2023-11-04 08:43:49+00:00
24k
conductor-oss/conductor
core/src/main/java/com/netflix/conductor/core/events/DefaultEventProcessor.java
[ { "identifier": "EventExecution", "path": "common/src/main/java/com/netflix/conductor/common/metadata/events/EventExecution.java", "snippet": "@ProtoMessage\npublic class EventExecution {\n\n @ProtoEnum\n public enum Status {\n IN_PROGRESS,\n COMPLETED,\n FAILED,\n SKIP...
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.retry.support.RetryTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import com.netflix.conductor.common.metadata.events.EventExecution; import com.netflix.conductor.common.metadata.events.EventExecution.Status; import com.netflix.conductor.common.metadata.events.EventHandler; import com.netflix.conductor.common.metadata.events.EventHandler.Action; import com.netflix.conductor.core.config.ConductorProperties; import com.netflix.conductor.core.events.queue.Message; import com.netflix.conductor.core.events.queue.ObservableQueue; import com.netflix.conductor.core.exception.TransientException; import com.netflix.conductor.core.execution.evaluators.Evaluator; import com.netflix.conductor.core.utils.JsonUtils; import com.netflix.conductor.metrics.Monitors; import com.netflix.conductor.service.ExecutionService; import com.netflix.conductor.service.MetadataService; import com.fasterxml.jackson.databind.ObjectMapper; import com.spotify.futures.CompletableFutures; import static com.netflix.conductor.core.utils.Utils.isTransientException;
21,590
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.core.events; /** * Event Processor is used to dispatch actions configured in the event handlers, based on incoming * events to the event queues. * * <p><code>Set conductor.default-event-processor.enabled=false</code> to disable event processing. */ @Component @ConditionalOnProperty( name = "conductor.default-event-processor.enabled", havingValue = "true", matchIfMissing = true) public class DefaultEventProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultEventProcessor.class); private final MetadataService metadataService; private final ExecutionService executionService; private final ActionProcessor actionProcessor; private final ExecutorService eventActionExecutorService; private final ObjectMapper objectMapper; private final JsonUtils jsonUtils; private final boolean isEventMessageIndexingEnabled; private final Map<String, Evaluator> evaluators; private final RetryTemplate retryTemplate; public DefaultEventProcessor( ExecutionService executionService, MetadataService metadataService, ActionProcessor actionProcessor, JsonUtils jsonUtils,
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.core.events; /** * Event Processor is used to dispatch actions configured in the event handlers, based on incoming * events to the event queues. * * <p><code>Set conductor.default-event-processor.enabled=false</code> to disable event processing. */ @Component @ConditionalOnProperty( name = "conductor.default-event-processor.enabled", havingValue = "true", matchIfMissing = true) public class DefaultEventProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultEventProcessor.class); private final MetadataService metadataService; private final ExecutionService executionService; private final ActionProcessor actionProcessor; private final ExecutorService eventActionExecutorService; private final ObjectMapper objectMapper; private final JsonUtils jsonUtils; private final boolean isEventMessageIndexingEnabled; private final Map<String, Evaluator> evaluators; private final RetryTemplate retryTemplate; public DefaultEventProcessor( ExecutionService executionService, MetadataService metadataService, ActionProcessor actionProcessor, JsonUtils jsonUtils,
ConductorProperties properties,
4
2023-12-08 06:06:09+00:00
24k
10cks/fofaEX
src/main/java/Main.java
[ { "identifier": "CommonExecute", "path": "src/main/java/plugins/CommonExecute.java", "snippet": "public class CommonExecute {\n\n public static JTable table = new JTable(); // 表格\n\n public static void exportTableToExcel(JTable table) {\n XSSFWorkbook workbook = new XSSFWorkbook();\n\n ...
import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import javax.swing.BorderFactory; import javax.swing.event.*; import java.awt.Color; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import plugins.CommonExecute; import plugins.CommonTemplate; import plugins.FofaHack; import tableInit.HighlightRenderer; import tableInit.RightClickFunctions; import javax.swing.table.*; import javax.swing.text.Document; import javax.swing.undo.UndoManager; import static java.awt.BorderLayout.*; import static java.lang.Thread.sleep; import static plugins.CommonTemplate.saveTableData; import static plugins.CommonTemplate.switchTab; import static tableInit.GetjTableHeader.adjustColumnWidths; import static tableInit.GetjTableHeader.getjTableHeader; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors;
15,515
public class Main { // 创建输入框 private static JTextField fofaUrl = createTextField("https://fofa.info"); private static JTextField fofaEmail = createTextField("当前版本不需要输入邮箱"); private static JTextField fofaKey = createTextField("请输入API key"); private static String rulesPath = "rules.txt"; private static String accountsPath = "accounts.json"; // 设置 field 规则 private static boolean hostMark = true; private static boolean ipMark = true; private static boolean portMark = true; private static boolean protocolMark = true; private static boolean titleMark = true; private static boolean domainMark = true; private static boolean linkMark = true; private static boolean icpMark = false; private static boolean cityMark = false; private static boolean countryMark = false; /* 下面未完成 */ private static boolean country_nameMark = false; private static boolean regionMark = false; private static boolean longitudeMark = false; private static boolean latitudeMark = false; private static boolean asNumberMark = false; private static boolean asOrganizationMark = false; private static boolean osMark = false; private static boolean serverMark = false; private static boolean jarmMark = false; private static boolean headerMark = false; private static boolean bannerMark = false; private static boolean baseProtocolMark = false; private static boolean certsIssuerOrgMark = false; private static boolean certsIssuerCnMark = false; private static boolean certsSubjectOrgMark = false; private static boolean certsSubjectCnMark = false; private static boolean tlsJa3sMark = false; private static boolean tlsVersionMark = false; private static boolean productMark = false; private static boolean productCategoryMark = false; private static boolean versionMark = false; private static boolean lastupdatetimeMark = false; private static boolean cnameMark = false; private static boolean iconHashMark = false; private static boolean certsValidMark = false; private static boolean cnameDomainMark = false; private static boolean bodyMark = false; private static boolean iconMark = false; private static boolean fidMark = false; private static boolean structinfoMark = false; private static boolean scrollPaneMark = true; // 标记 private static boolean exportButtonAdded = false; private static boolean timeAdded = false; private static JLabel timeLabel; private static int queryTotalNumber; private static int numberOfItems; private static int currentPage = 1; private static boolean setFull = true; private static int sizeSetting = 10000; private static boolean openFileMark = false; // 创建全局数据表 private static JTable table; // 在类的成员变量中创建弹出菜单 private static JPopupMenu popupMenu = new JPopupMenu(); private static JMenuItem itemSelectColumn = new JMenuItem("选择当前整列"); private static JMenuItem itemDeselectColumn = new JMenuItem("取消选择整列"); private static JMenuItem itemOpenLink = new JMenuItem("打开链接"); static JMenuItem itemCopy = new JMenuItem("复制"); private static JMenuItem itemSearch = new JMenuItem("表格搜索"); private static File lastOpenedPath; // 添加一个成员变量来保存上次打开的文件路径 static TableCellRenderer highlightRenderer = new HighlightRenderer(); private static TableCellRenderer defaultRenderer; private static JTabbedPane tabbedPane0; public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, FileNotFoundException { JFrame jFrame = new JFrame("fofaEX"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try { URL resource = Main.class.getResource("icon.png"); jFrame.setIconImage((new ImageIcon(resource).getImage())); //给Frame设置图标 } catch (Exception e) { System.out.println(e); } // 设置外观风格 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // 创建 CardLayout 布局管理器 CardLayout cardLayout = new CardLayout(); jFrame.setLayout(cardLayout); // 创建 tab 面板 tabbedPane0 = new JTabbedPane(); // 创建菜单栏 JMenuBar menuBar = new JMenuBar(); // 在JFrame中添加菜单栏 jFrame.setJMenuBar(menuBar); // 创建"账户设置"菜单项 JMenu settingsMenu = new JMenu("账户设置"); JMenuItem changePasswordMenuItem = new JMenuItem("FOFA API"); settingsMenu.add(changePasswordMenuItem); menuBar.add(settingsMenu); // 创建"搜索设置"菜单项 JMenu configureMenu = new JMenu("查询设置"); JMenuItem configureMenuItem = new JMenuItem("默认查询数量"); JMenuItem configureFullItem = new JMenuItem("默认查询区间"); JCheckBox defaultCheckFullBox = new JCheckBox("是否默认仅查询近一年数据?", false); defaultCheckFullBox.setFocusPainted(false); configureMenu.add(configureMenuItem); configureMenu.add(configureFullItem); menuBar.add(configureMenu); // 创建 “实验功能” 菜单项 JMenu labMenu = new JMenu("实验功能"); JMenuItem openFileMenuItem = new JMenuItem("打开文件"); JMenuItem iconHashLabMenuItem = new JMenuItem("iconHash 计算"); JMenu pluginMenu = new JMenu("插件模式"); JMenu fofaHackMenu = new JMenu("Fofa-Hack"); JMenuItem fofaHackMenuItemRun = new JMenuItem("运行"); JMenuItem fofaHackMenuItemSetting = new JMenuItem("设置"); JMenuItem fofaHackMenuItemAbout = new JMenuItem("关于"); CommonTemplate.addMenuItemsFromFile(pluginMenu, tabbedPane0); JMenu testMenu = new JMenu("测试模式"); JMenuItem focusTestItem = new JMenuItem("焦点测试"); JMenuItem switchToHttpxItem = new JMenuItem("跳转测试"); labMenu.add(openFileMenuItem); labMenu.add(iconHashLabMenuItem); labMenu.add(pluginMenu); // 发布需要注释 pluginMenu.add(fofaHackMenu); fofaHackMenu.add(fofaHackMenuItemRun); fofaHackMenu.add(fofaHackMenuItemSetting); fofaHackMenu.add(fofaHackMenuItemAbout); //labMenu.add(testMenu); // 发布需要注释 testMenu.add(focusTestItem); testMenu.add(switchToHttpxItem); menuBar.add(labMenu); // 创建"关于"菜单项 JMenu aboutMenu = new JMenu("关于"); JMenuItem aboutMenuItem = new JMenuItem("关于项目"); aboutMenu.add(aboutMenuItem); menuBar.add(aboutMenu); // 刷新jf容器及其内部组件的外观 SwingUtilities.updateComponentTreeUI(jFrame); jFrame.setSize(1000, 800); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 确保按下关闭按钮时结束程序 // 创建 fofa 输入框 JTextField textField0 = createTextFieldFofa("fofaEX: FOFA Extension"); // 创建数据表 if (table == null) { table = new JTable(); } // 初始化 table 右键
public class Main { // 创建输入框 private static JTextField fofaUrl = createTextField("https://fofa.info"); private static JTextField fofaEmail = createTextField("当前版本不需要输入邮箱"); private static JTextField fofaKey = createTextField("请输入API key"); private static String rulesPath = "rules.txt"; private static String accountsPath = "accounts.json"; // 设置 field 规则 private static boolean hostMark = true; private static boolean ipMark = true; private static boolean portMark = true; private static boolean protocolMark = true; private static boolean titleMark = true; private static boolean domainMark = true; private static boolean linkMark = true; private static boolean icpMark = false; private static boolean cityMark = false; private static boolean countryMark = false; /* 下面未完成 */ private static boolean country_nameMark = false; private static boolean regionMark = false; private static boolean longitudeMark = false; private static boolean latitudeMark = false; private static boolean asNumberMark = false; private static boolean asOrganizationMark = false; private static boolean osMark = false; private static boolean serverMark = false; private static boolean jarmMark = false; private static boolean headerMark = false; private static boolean bannerMark = false; private static boolean baseProtocolMark = false; private static boolean certsIssuerOrgMark = false; private static boolean certsIssuerCnMark = false; private static boolean certsSubjectOrgMark = false; private static boolean certsSubjectCnMark = false; private static boolean tlsJa3sMark = false; private static boolean tlsVersionMark = false; private static boolean productMark = false; private static boolean productCategoryMark = false; private static boolean versionMark = false; private static boolean lastupdatetimeMark = false; private static boolean cnameMark = false; private static boolean iconHashMark = false; private static boolean certsValidMark = false; private static boolean cnameDomainMark = false; private static boolean bodyMark = false; private static boolean iconMark = false; private static boolean fidMark = false; private static boolean structinfoMark = false; private static boolean scrollPaneMark = true; // 标记 private static boolean exportButtonAdded = false; private static boolean timeAdded = false; private static JLabel timeLabel; private static int queryTotalNumber; private static int numberOfItems; private static int currentPage = 1; private static boolean setFull = true; private static int sizeSetting = 10000; private static boolean openFileMark = false; // 创建全局数据表 private static JTable table; // 在类的成员变量中创建弹出菜单 private static JPopupMenu popupMenu = new JPopupMenu(); private static JMenuItem itemSelectColumn = new JMenuItem("选择当前整列"); private static JMenuItem itemDeselectColumn = new JMenuItem("取消选择整列"); private static JMenuItem itemOpenLink = new JMenuItem("打开链接"); static JMenuItem itemCopy = new JMenuItem("复制"); private static JMenuItem itemSearch = new JMenuItem("表格搜索"); private static File lastOpenedPath; // 添加一个成员变量来保存上次打开的文件路径 static TableCellRenderer highlightRenderer = new HighlightRenderer(); private static TableCellRenderer defaultRenderer; private static JTabbedPane tabbedPane0; public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, FileNotFoundException { JFrame jFrame = new JFrame("fofaEX"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try { URL resource = Main.class.getResource("icon.png"); jFrame.setIconImage((new ImageIcon(resource).getImage())); //给Frame设置图标 } catch (Exception e) { System.out.println(e); } // 设置外观风格 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // 创建 CardLayout 布局管理器 CardLayout cardLayout = new CardLayout(); jFrame.setLayout(cardLayout); // 创建 tab 面板 tabbedPane0 = new JTabbedPane(); // 创建菜单栏 JMenuBar menuBar = new JMenuBar(); // 在JFrame中添加菜单栏 jFrame.setJMenuBar(menuBar); // 创建"账户设置"菜单项 JMenu settingsMenu = new JMenu("账户设置"); JMenuItem changePasswordMenuItem = new JMenuItem("FOFA API"); settingsMenu.add(changePasswordMenuItem); menuBar.add(settingsMenu); // 创建"搜索设置"菜单项 JMenu configureMenu = new JMenu("查询设置"); JMenuItem configureMenuItem = new JMenuItem("默认查询数量"); JMenuItem configureFullItem = new JMenuItem("默认查询区间"); JCheckBox defaultCheckFullBox = new JCheckBox("是否默认仅查询近一年数据?", false); defaultCheckFullBox.setFocusPainted(false); configureMenu.add(configureMenuItem); configureMenu.add(configureFullItem); menuBar.add(configureMenu); // 创建 “实验功能” 菜单项 JMenu labMenu = new JMenu("实验功能"); JMenuItem openFileMenuItem = new JMenuItem("打开文件"); JMenuItem iconHashLabMenuItem = new JMenuItem("iconHash 计算"); JMenu pluginMenu = new JMenu("插件模式"); JMenu fofaHackMenu = new JMenu("Fofa-Hack"); JMenuItem fofaHackMenuItemRun = new JMenuItem("运行"); JMenuItem fofaHackMenuItemSetting = new JMenuItem("设置"); JMenuItem fofaHackMenuItemAbout = new JMenuItem("关于"); CommonTemplate.addMenuItemsFromFile(pluginMenu, tabbedPane0); JMenu testMenu = new JMenu("测试模式"); JMenuItem focusTestItem = new JMenuItem("焦点测试"); JMenuItem switchToHttpxItem = new JMenuItem("跳转测试"); labMenu.add(openFileMenuItem); labMenu.add(iconHashLabMenuItem); labMenu.add(pluginMenu); // 发布需要注释 pluginMenu.add(fofaHackMenu); fofaHackMenu.add(fofaHackMenuItemRun); fofaHackMenu.add(fofaHackMenuItemSetting); fofaHackMenu.add(fofaHackMenuItemAbout); //labMenu.add(testMenu); // 发布需要注释 testMenu.add(focusTestItem); testMenu.add(switchToHttpxItem); menuBar.add(labMenu); // 创建"关于"菜单项 JMenu aboutMenu = new JMenu("关于"); JMenuItem aboutMenuItem = new JMenuItem("关于项目"); aboutMenu.add(aboutMenuItem); menuBar.add(aboutMenu); // 刷新jf容器及其内部组件的外观 SwingUtilities.updateComponentTreeUI(jFrame); jFrame.setSize(1000, 800); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 确保按下关闭按钮时结束程序 // 创建 fofa 输入框 JTextField textField0 = createTextFieldFofa("fofaEX: FOFA Extension"); // 创建数据表 if (table == null) { table = new JTable(); } // 初始化 table 右键
RightClickFunctions.table = table;
4
2023-12-07 13:46:27+00:00
24k
kaifangqian/open-sign
src/main/java/com/resrun/controller/OpenSignController.java
[ { "identifier": "SignTypeEnum", "path": "src/main/java/com/resrun/enums/SignTypeEnum.java", "snippet": "public enum SignTypeEnum {\n\n\n POSITION(1,\"位置签署\"),\n KEYWORD(2,\"关键字签署\"),\n\n ;\n\n private String msg;\n private Integer code;\n\n\n SignTypeEnum(Integer code,String msg){\n ...
import com.resrun.enums.SignTypeEnum; import com.resrun.service.pojo.CertificateProperty; import com.resrun.service.pojo.GenerateCertificateInfo; import com.resrun.service.pojo.RealPositionProperty; import com.resrun.service.pojo.SourcePositionProperty; import com.resrun.service.cert.CertService; import com.resrun.service.image.EntSealClipService; import com.resrun.service.image.EntSealGenerateService; import com.resrun.service.pdf.CalculatePositionService; import com.resrun.service.pdf.SignService; import com.resrun.service.verify.SignVerifyService; import com.resrun.utils.Base64; import com.resrun.controller.vo.base.Result; import com.resrun.controller.vo.request.*; import com.resrun.controller.vo.response.SealResponse; import com.resrun.controller.vo.response.SignResponse; import com.resrun.controller.vo.response.VerifyResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.pdfbox.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.*; import java.io.*; import java.util.ArrayList; import java.util.List;
15,255
signFileBytes = getResourceFiles(fileName); } catch (Exception e) { e.printStackTrace(); } if(signFileBytes == null){ return Result.error("签署失败",null); } //生成企业证书和个人证书 try { if(request.getEntName() != null && request.getEntName().length() > 0){ String subject = "C=CN,ST=北京,L=北京,O=开放签 CA,OU=产品部,CN=开放签@" + request.getEntName(); GenerateCertificateInfo generateCertificateInfo = certService.generateCertificate(null, subject, 10); if(generateCertificateInfo != null){ entCert = new CertificateProperty(); entCert.setCertType("PKCS12"); entCert.setCertFile(generateCertificateInfo.getPfx()); entCert.setPassword(generateCertificateInfo.getPassword()); } if(entCert == null){ return Result.error("签署失败",null); } } if(request.getPersonalName() != null && request.getPersonalName().length() > 0){ String subject = "C=CN,ST=北京,L=北京,O=开放签 CA,OU=产品部,CN=开放签@" + request.getPersonalName(); GenerateCertificateInfo generateCertificateInfo = certService.generateCertificate(null, subject, 10); if(generateCertificateInfo != null){ personalCert = new CertificateProperty(); personalCert.setCertType("PKCS12"); personalCert.setCertFile(generateCertificateInfo.getPfx()); personalCert.setPassword(generateCertificateInfo.getPassword()); } if(personalCert == null){ return Result.error("签署失败",null); } } } catch (Exception e) { e.printStackTrace(); } //生成企业签章和个人签章 if(request.getEntSeal() != null){ entSealBytes = Base64.decode(request.getEntSeal()); } if(request.getPersonalSeal() != null){ personalBytes = Base64.decode(request.getPersonalSeal()); } //计算企业签署位置和个人签署位置 if(SignTypeEnum.POSITION.getCode().equals(request.getSignType())){ if((request.getEntPositionList() == null || request.getEntPositionList().size() == 0 ) && (request.getPersonalPositionList() == null || request.getPersonalPositionList().size() == 0)){ return Result.error("签署失败",null); } //计算企业签署位置 if(request.getEntPositionList() != null && request.getEntPositionList().size() > 0){ List<SourcePositionProperty> convert = convert(request.getEntPositionList()); entPositionList = calculatePositionService.calculatePositions(convert, signFileBytes); } //计算个人签署位置 if(request.getPersonalPositionList() != null && request.getPersonalPositionList().size() > 0){ List<SourcePositionProperty> convert = convert(request.getPersonalPositionList()); personalPositionList = calculatePositionService.calculatePositions(convert, signFileBytes); } }else if(SignTypeEnum.KEYWORD.getCode().equals(request.getSignType())){ if((request.getEntKeyword() == null || request.getEntKeyword().length() == 0 ) && (request.getPersonalKeyword() == null || request.getPersonalKeyword().length() == 0)){ return Result.error("签署失败",null); } //根据关键字计算所有企业签署位置 if(request.getEntKeyword() != null && request.getEntKeyword().length() > 0){ entPositionList = calculatePositionService.getAllPositionByKeyWords(signFileBytes, request.getEntKeyword(), entSealWidth, entSealHeight); } //根据关键字计算所有个人签署位置 if(request.getPersonalKeyword() != null && request.getPersonalKeyword().length() > 0){ personalPositionList = calculatePositionService.getAllPositionByKeyWords(signFileBytes,request.getPersonalKeyword(),personalSealWidth,personalSealHeight); } if((personalPositionList == null || personalPositionList.size() == 0 ) && (entPositionList == null || entPositionList.size() == 0)){ return Result.error("签署失败!签署关键字在文件中不存在,请准确设置关键字后再签署",null); } } //进行签署操作 byte[] operationByte = signFileBytes ; try { //所有企业位置签署 if(entPositionList != null && entPositionList.size() > 0){ for(RealPositionProperty realPositionProperty : entPositionList){ operationByte = signService.signingContract(operationByte, entSealBytes, entCert, realPositionProperty); } } //所有个人位置签署 if(personalPositionList != null && personalPositionList.size() > 0){ for(RealPositionProperty realPositionProperty : personalPositionList){ operationByte = signService.signingContract(operationByte, personalBytes, personalCert, realPositionProperty); } } }catch (Exception e){ } if(operationByte == null){ return Result.error("签署失败",null); } // try { // org.apache.commons.io.IOUtils.write(operationByte,new FileOutputStream(new File("/Users/gongfenglai/Desktop/test/pdf/" + System.currentTimeMillis() + ".pdf"))); // } catch (Exception e) { // e.printStackTrace(); // } String encode = Base64.encode(operationByte); SignResponse response = new SignResponse(); response.setSignFile(encode); return Result.OK(response); } @ApiOperation("文件验签") @RequestMapping(value = "/verify",method = RequestMethod.POST)
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired private CalculatePositionService calculatePositionService ; @Autowired private SignService signService ; @Autowired private EntSealGenerateService entSealGenerateService ; @Autowired private EntSealClipService entSealClipService ; @Autowired private CertService certService ; @ApiOperation("生成企业签章-上传生成") @RequestMapping(value = "/clip/seal",method = RequestMethod.POST) public Result<SealResponse> generateUpload(@RequestBody ClipSealRequest request){ if(request.getImage() == null || request.getImage().length() == 0){ return Result.error("图片数据为空",null); } byte[] decode = Base64.decode(request.getImage()); if(decode == null || decode.length == 0){ return Result.error("签章制作失败",null); } byte[] entSealByte = entSealClipService.clip(decode, request.getColorRange()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("生成企业签章-参数生成") @RequestMapping(value = "/generate/seal",method = RequestMethod.POST) public Result<SealResponse> seal(@RequestBody GenerateSealRequest request){ if(request == null || request.getMiddleText() == null || request.getTopText() == null){ return Result.error("参数缺失",null) ; } byte[] entSealByte = entSealGenerateService.generateEntSeal(request.getTopText(), request.getMiddleText()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("签署") @RequestMapping(value = "/sign",method = RequestMethod.POST) public Result<SignResponse> sign(@RequestBody SignRequest request){ String fileName = "开源工具版说明.pdf" ; byte[] signFileBytes = null ; byte[] entSealBytes = null ; byte[] personalBytes = null ; CertificateProperty entCert = null ; CertificateProperty personalCert = null ; List<RealPositionProperty> entPositionList = null; List<RealPositionProperty> personalPositionList = null; int entSealWidth = 200 ; int entSealHeight = 200 ; int personalSealWidth = 150 ; int personalSealHeight = 70 ; //获取本地签署文件 try { signFileBytes = getResourceFiles(fileName); } catch (Exception e) { e.printStackTrace(); } if(signFileBytes == null){ return Result.error("签署失败",null); } //生成企业证书和个人证书 try { if(request.getEntName() != null && request.getEntName().length() > 0){ String subject = "C=CN,ST=北京,L=北京,O=开放签 CA,OU=产品部,CN=开放签@" + request.getEntName(); GenerateCertificateInfo generateCertificateInfo = certService.generateCertificate(null, subject, 10); if(generateCertificateInfo != null){ entCert = new CertificateProperty(); entCert.setCertType("PKCS12"); entCert.setCertFile(generateCertificateInfo.getPfx()); entCert.setPassword(generateCertificateInfo.getPassword()); } if(entCert == null){ return Result.error("签署失败",null); } } if(request.getPersonalName() != null && request.getPersonalName().length() > 0){ String subject = "C=CN,ST=北京,L=北京,O=开放签 CA,OU=产品部,CN=开放签@" + request.getPersonalName(); GenerateCertificateInfo generateCertificateInfo = certService.generateCertificate(null, subject, 10); if(generateCertificateInfo != null){ personalCert = new CertificateProperty(); personalCert.setCertType("PKCS12"); personalCert.setCertFile(generateCertificateInfo.getPfx()); personalCert.setPassword(generateCertificateInfo.getPassword()); } if(personalCert == null){ return Result.error("签署失败",null); } } } catch (Exception e) { e.printStackTrace(); } //生成企业签章和个人签章 if(request.getEntSeal() != null){ entSealBytes = Base64.decode(request.getEntSeal()); } if(request.getPersonalSeal() != null){ personalBytes = Base64.decode(request.getPersonalSeal()); } //计算企业签署位置和个人签署位置 if(SignTypeEnum.POSITION.getCode().equals(request.getSignType())){ if((request.getEntPositionList() == null || request.getEntPositionList().size() == 0 ) && (request.getPersonalPositionList() == null || request.getPersonalPositionList().size() == 0)){ return Result.error("签署失败",null); } //计算企业签署位置 if(request.getEntPositionList() != null && request.getEntPositionList().size() > 0){ List<SourcePositionProperty> convert = convert(request.getEntPositionList()); entPositionList = calculatePositionService.calculatePositions(convert, signFileBytes); } //计算个人签署位置 if(request.getPersonalPositionList() != null && request.getPersonalPositionList().size() > 0){ List<SourcePositionProperty> convert = convert(request.getPersonalPositionList()); personalPositionList = calculatePositionService.calculatePositions(convert, signFileBytes); } }else if(SignTypeEnum.KEYWORD.getCode().equals(request.getSignType())){ if((request.getEntKeyword() == null || request.getEntKeyword().length() == 0 ) && (request.getPersonalKeyword() == null || request.getPersonalKeyword().length() == 0)){ return Result.error("签署失败",null); } //根据关键字计算所有企业签署位置 if(request.getEntKeyword() != null && request.getEntKeyword().length() > 0){ entPositionList = calculatePositionService.getAllPositionByKeyWords(signFileBytes, request.getEntKeyword(), entSealWidth, entSealHeight); } //根据关键字计算所有个人签署位置 if(request.getPersonalKeyword() != null && request.getPersonalKeyword().length() > 0){ personalPositionList = calculatePositionService.getAllPositionByKeyWords(signFileBytes,request.getPersonalKeyword(),personalSealWidth,personalSealHeight); } if((personalPositionList == null || personalPositionList.size() == 0 ) && (entPositionList == null || entPositionList.size() == 0)){ return Result.error("签署失败!签署关键字在文件中不存在,请准确设置关键字后再签署",null); } } //进行签署操作 byte[] operationByte = signFileBytes ; try { //所有企业位置签署 if(entPositionList != null && entPositionList.size() > 0){ for(RealPositionProperty realPositionProperty : entPositionList){ operationByte = signService.signingContract(operationByte, entSealBytes, entCert, realPositionProperty); } } //所有个人位置签署 if(personalPositionList != null && personalPositionList.size() > 0){ for(RealPositionProperty realPositionProperty : personalPositionList){ operationByte = signService.signingContract(operationByte, personalBytes, personalCert, realPositionProperty); } } }catch (Exception e){ } if(operationByte == null){ return Result.error("签署失败",null); } // try { // org.apache.commons.io.IOUtils.write(operationByte,new FileOutputStream(new File("/Users/gongfenglai/Desktop/test/pdf/" + System.currentTimeMillis() + ".pdf"))); // } catch (Exception e) { // e.printStackTrace(); // } String encode = Base64.encode(operationByte); SignResponse response = new SignResponse(); response.setSignFile(encode); return Result.OK(response); } @ApiOperation("文件验签") @RequestMapping(value = "/verify",method = RequestMethod.POST)
public Result<VerifyResponse> verify(@RequestBody VerifyRequest request){
15
2023-12-14 06:53:32+00:00
24k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/ui/fragments/ColorsFragment.java
[ { "identifier": "MANUAL_OVERRIDE_COLORS", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MANUAL_OVERRIDE_COLORS = \"manualOverrideColors\";" }, { "identifier": "MONET_ACCENT_SATURATION", "path": "app/src/main/java/com/drdisagr...
import static com.drdisagree.colorblendr.common.Const.MANUAL_OVERRIDE_COLORS; import static com.drdisagree.colorblendr.common.Const.MONET_ACCENT_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_ACCURATE_SHADES; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_LIGHTNESS; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_LAST_UPDATED; import static com.drdisagree.colorblendr.common.Const.MONET_PITCH_BLACK_THEME; import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR; import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR_ENABLED; import static com.drdisagree.colorblendr.common.Const.MONET_STYLE; import static com.drdisagree.colorblendr.common.Const.WALLPAPER_COLOR_LIST; import android.content.BroadcastReceiver; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.drdisagree.colorblendr.R; import com.drdisagree.colorblendr.common.Const; import com.drdisagree.colorblendr.config.RPrefs; import com.drdisagree.colorblendr.databinding.FragmentColorsBinding; import com.drdisagree.colorblendr.ui.viewmodels.SharedViewModel; import com.drdisagree.colorblendr.ui.views.WallColorPreview; import com.drdisagree.colorblendr.utils.ColorSchemeUtil; import com.drdisagree.colorblendr.utils.ColorUtil; import com.drdisagree.colorblendr.utils.MiscUtil; import com.drdisagree.colorblendr.utils.OverlayManager; import com.drdisagree.colorblendr.utils.WallpaperUtil; import com.google.android.material.snackbar.Snackbar; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import me.jfenn.colorpickerdialog.dialogs.ColorPickerDialog; import me.jfenn.colorpickerdialog.views.picker.ImagePickerView;
19,364
package com.drdisagree.colorblendr.ui.fragments; @SuppressWarnings("deprecation") public class ColorsFragment extends Fragment { private static final String TAG = ColorsFragment.class.getSimpleName(); private FragmentColorsBinding binding; private int[] monetSeedColor; private LinearLayout[] colorTableRows; private SharedViewModel sharedViewModel; private final String[][] colorNames = ColorUtil.getColorNames(); private static final int[] colorCodes = { 0, 10, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; private final BroadcastReceiver wallpaperChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, android.content.Intent intent) { if (binding.colorsToggleGroup.getCheckedButtonId() == R.id.wallpaper_colors_button) { addWallpaperColorItems(); } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentColorsBinding.inflate(inflater, container, false); MiscUtil.setToolbarTitle(requireContext(), R.string.app_name, false, binding.header.toolbar); monetSeedColor = new int[]{RPrefs.getInt( MONET_SEED_COLOR, WallpaperUtil.getWallpaperColor(requireContext()) )}; colorTableRows = new LinearLayout[]{ binding.colorPreview.systemAccent1, binding.colorPreview.systemAccent2, binding.colorPreview.systemAccent3, binding.colorPreview.systemNeutral1, binding.colorPreview.systemNeutral2 }; return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); sharedViewModel.getBooleanStates().observe(getViewLifecycleOwner(), this::updateBooleanStates); sharedViewModel.getVisibilityStates().observe(getViewLifecycleOwner(), this::updateViewVisibility); // Color codes binding.colorsToggleGroup.check( RPrefs.getBoolean(MONET_SEED_COLOR_ENABLED, false) ? R.id.basic_colors_button : R.id.wallpaper_colors_button ); binding.colorsToggleGroup.addOnButtonCheckedListener((group, checkedId, isChecked) -> { if (isChecked) { if (checkedId == R.id.wallpaper_colors_button) { addWallpaperColorItems(); } else { addBasicColorItems(); } } }); if (RPrefs.getBoolean(MONET_SEED_COLOR_ENABLED, false)) { addBasicColorItems(); } else { addWallpaperColorItems(); } // Color table preview initColorTablePreview(colorTableRows); // Primary color binding.seedColorPicker.setPreviewColor(RPrefs.getInt( MONET_SEED_COLOR, monetSeedColor[0] )); binding.seedColorPicker.setOnClickListener(v -> new ColorPickerDialog() .withCornerRadius(10) .withColor(monetSeedColor[0]) .withAlphaEnabled(false) .withPicker(ImagePickerView.class) .withListener((pickerView, color) -> { if (monetSeedColor[0] != color) { monetSeedColor[0] = color; binding.seedColorPicker.setPreviewColor(color); RPrefs.putInt(MONET_SEED_COLOR, monetSeedColor[0]); updatePreviewColors( colorTableRows, generateModifiedColors() ); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 300); } }) .show(getChildFragmentManager(), "seedColorPicker") ); binding.seedColorPicker.setVisibility( RPrefs.getBoolean(MONET_SEED_COLOR_ENABLED, false) ? View.VISIBLE : View.GONE ); // Force per app theme binding.perAppTheme.setOnClickListener(v -> HomeFragment.replaceFragment(new PerAppThemeFragment())); } private void updateBooleanStates(Map<String, Boolean> stringBooleanMap) {
package com.drdisagree.colorblendr.ui.fragments; @SuppressWarnings("deprecation") public class ColorsFragment extends Fragment { private static final String TAG = ColorsFragment.class.getSimpleName(); private FragmentColorsBinding binding; private int[] monetSeedColor; private LinearLayout[] colorTableRows; private SharedViewModel sharedViewModel; private final String[][] colorNames = ColorUtil.getColorNames(); private static final int[] colorCodes = { 0, 10, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; private final BroadcastReceiver wallpaperChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, android.content.Intent intent) { if (binding.colorsToggleGroup.getCheckedButtonId() == R.id.wallpaper_colors_button) { addWallpaperColorItems(); } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentColorsBinding.inflate(inflater, container, false); MiscUtil.setToolbarTitle(requireContext(), R.string.app_name, false, binding.header.toolbar); monetSeedColor = new int[]{RPrefs.getInt( MONET_SEED_COLOR, WallpaperUtil.getWallpaperColor(requireContext()) )}; colorTableRows = new LinearLayout[]{ binding.colorPreview.systemAccent1, binding.colorPreview.systemAccent2, binding.colorPreview.systemAccent3, binding.colorPreview.systemNeutral1, binding.colorPreview.systemNeutral2 }; return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); sharedViewModel.getBooleanStates().observe(getViewLifecycleOwner(), this::updateBooleanStates); sharedViewModel.getVisibilityStates().observe(getViewLifecycleOwner(), this::updateViewVisibility); // Color codes binding.colorsToggleGroup.check( RPrefs.getBoolean(MONET_SEED_COLOR_ENABLED, false) ? R.id.basic_colors_button : R.id.wallpaper_colors_button ); binding.colorsToggleGroup.addOnButtonCheckedListener((group, checkedId, isChecked) -> { if (isChecked) { if (checkedId == R.id.wallpaper_colors_button) { addWallpaperColorItems(); } else { addBasicColorItems(); } } }); if (RPrefs.getBoolean(MONET_SEED_COLOR_ENABLED, false)) { addBasicColorItems(); } else { addWallpaperColorItems(); } // Color table preview initColorTablePreview(colorTableRows); // Primary color binding.seedColorPicker.setPreviewColor(RPrefs.getInt( MONET_SEED_COLOR, monetSeedColor[0] )); binding.seedColorPicker.setOnClickListener(v -> new ColorPickerDialog() .withCornerRadius(10) .withColor(monetSeedColor[0]) .withAlphaEnabled(false) .withPicker(ImagePickerView.class) .withListener((pickerView, color) -> { if (monetSeedColor[0] != color) { monetSeedColor[0] = color; binding.seedColorPicker.setPreviewColor(color); RPrefs.putInt(MONET_SEED_COLOR, monetSeedColor[0]); updatePreviewColors( colorTableRows, generateModifiedColors() ); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 300); } }) .show(getChildFragmentManager(), "seedColorPicker") ); binding.seedColorPicker.setVisibility( RPrefs.getBoolean(MONET_SEED_COLOR_ENABLED, false) ? View.VISIBLE : View.GONE ); // Force per app theme binding.perAppTheme.setOnClickListener(v -> HomeFragment.replaceFragment(new PerAppThemeFragment())); } private void updateBooleanStates(Map<String, Boolean> stringBooleanMap) {
Boolean accurateShades = stringBooleanMap.get(MONET_ACCURATE_SHADES);
2
2023-12-06 13:20:16+00:00
24k
lxs2601055687/contextAdminRuoYi
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java
[ { "identifier": "UserConstants", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java", "snippet": "public interface UserConstants {\n\n /**\n * 平台内系统用户的唯一标志\n */\n String SYS_USER = \"SYS_USER\";\n\n /**\n * 正常状态\n */\n String NORMAL = \"0\";\n\n ...
import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.secure.BCrypt; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ObjectUtil; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.PageQuery; import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.core.domain.entity.SysRole; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.excel.ExcelResult; import com.ruoyi.common.helper.LoginHelper; import com.ruoyi.common.utils.StreamUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.system.domain.vo.SysUserExportVo; import com.ruoyi.system.domain.vo.SysUserImportVo; import com.ruoyi.system.listener.SysUserImportListener; import com.ruoyi.system.service.ISysDeptService; import com.ruoyi.system.service.ISysPostService; import com.ruoyi.system.service.ISysRoleService; import com.ruoyi.system.service.ISysUserService; import lombok.RequiredArgsConstructor; import org.springframework.http.MediaType; 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.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
20,769
package com.ruoyi.web.controller.system; /** * 用户信息 * * @author Lion Li */ @Validated @RequiredArgsConstructor @RestController @RequestMapping("/system/user") public class SysUserController extends BaseController { private final ISysUserService userService; private final ISysRoleService roleService; private final ISysPostService postService;
package com.ruoyi.web.controller.system; /** * 用户信息 * * @author Lion Li */ @Validated @RequiredArgsConstructor @RestController @RequestMapping("/system/user") public class SysUserController extends BaseController { private final ISysUserService userService; private final ISysRoleService roleService; private final ISysPostService postService;
private final ISysDeptService deptService;
17
2023-12-07 12:06:21+00:00
24k
DantSu/studio
web-ui/src/main/java/studio/webui/service/StoryTellerService.java
[ { "identifier": "PackFormat", "path": "core/src/main/java/studio/core/v1/utils/PackFormat.java", "snippet": "public enum PackFormat {\n\n ARCHIVE(new ArchiveStoryPackReader(), new ArchiveStoryPackWriter()),\n\n RAW(new BinaryStoryPackReader(), new BinaryStoryPackWriter()),\n\n FS(new FsStoryPac...
import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.usb4java.Device; import io.vertx.core.eventbus.EventBus; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import studio.core.v1.utils.PackFormat; import studio.core.v1.utils.SecurityUtils; import studio.core.v1.utils.exception.StoryTellerException; import studio.driver.StoryTellerAsyncDriver; import studio.driver.fs.FsStoryTellerAsyncDriver; import studio.driver.model.StoryPackInfos; import studio.driver.model.fs.FsDeviceInfos; import studio.driver.model.fs.FsStoryPackInfos; import studio.driver.model.raw.RawDeviceInfos; import studio.driver.model.raw.RawStoryPackInfos; import studio.driver.raw.LibUsbMassStorageHelper; import studio.driver.raw.RawStoryTellerAsyncDriver; import studio.metadata.DatabaseMetadataService;
20,781
return rawDriver.dump(outputPath); } // unavailable for fsDevice return CompletableFuture.completedFuture(null); } private void sendDevicePlugged(JsonObject infos) { eventBus.send("storyteller.plugged", infos); } private void sendDeviceUnplugged() { eventBus.send("storyteller.unplugged", null); } private void sendFailure() { eventBus.send("storyteller.failure", null); } private void sendProgress(String id, double p) { eventBus.send("storyteller.transfer." + id + ".progress", new JsonObject().put("progress", p)); } private void sendDone(String id, boolean success) { eventBus.send("storyteller.transfer." + id + ".done", new JsonObject().put("success", success)); } private <T,U,V extends StoryPackInfos> Optional<String> upload(List<V> packs, StoryTellerAsyncDriver<T, U> driver, String uuid, Path packFile) { // Check that the pack is not already on the device : Look for UUID in packs index boolean matched = packs.stream().anyMatch(p -> p.getUuid().equals(UUID.fromString(uuid))); if (matched) { LOGGER.error("Cannot add pack to device because the pack already exists on the device"); return Optional.empty(); } String transferId = UUID.randomUUID().toString(); try { driver.uploadPack(uuid, packFile, status -> { // Send event on eventbus to monitor progress double p = status.getPercent(); LOGGER.debug("Pack add progress... {}% ({} / {})", p, status.getTransferred(), status.getTotal()); sendProgress(transferId, p); }).whenComplete((status, t) -> { // Handle failure if (t != null) { throw new StoryTellerException(t); } // Handle success sendDone(transferId, true); }); } catch (Exception e) { LOGGER.error("Failed to add pack to device", e); // Send event on eventbus to signal transfer failure sendDone(transferId, false); } return Optional.of(transferId); } private <T, U> Optional<String> download(StoryTellerAsyncDriver<T, U> driver, String uuid, Path destFile) { // Check that the destination is available if (Files.exists(destFile.resolve(uuid))) { LOGGER.error("Cannot extract pack from device because the destination file already exists"); return Optional.empty(); } String transferId = UUID.randomUUID().toString(); try { driver.downloadPack(uuid, destFile, status -> { // Send event on eventbus to monitor progress double p = status.getPercent(); LOGGER.debug("Pack extraction progress... {}% ({} / {})", p, status.getTransferred(), status.getTotal()); sendProgress(transferId, p); }).whenComplete((status, t) -> { // Handle failure if (t != null) { throw new StoryTellerException(t); } // Handle success sendDone(transferId, true); }); } catch (Exception e) { LOGGER.error("Failed to extract pack from device", e); // Send event on eventbus to signal transfer failure sendDone(transferId, false); } return Optional.of(transferId); } private JsonObject getRawPackMetadata(RawStoryPackInfos pack) { JsonObject json = new JsonObject() .put("uuid", pack.getUuid().toString()) .put("format", PackFormat.RAW.getLabel()) .put("version", pack.getVersion()) .put("sectorSize", pack.getSizeInSectors()); return databaseMetadataService.getPackMetadata(pack.getUuid().toString()) .map(meta -> json .put("title", meta.getTitle()) .put("description", meta.getDescription()) .put("image", meta.getThumbnail()) .put("official", meta.isOfficial())) .orElse(json); } private JsonObject getFsPackMetadata(FsStoryPackInfos pack) { JsonObject json = new JsonObject() .put("uuid", pack.getUuid().toString()) .put("format", PackFormat.FS.getLabel()) .put("version", pack.getVersion()) .put("folderName", pack.getFolderName()) .put("sizeInBytes", pack.getSizeInBytes()) .put("nightModeAvailable", pack.isNightModeAvailable()); return databaseMetadataService.getPackMetadata(pack.getUuid().toString()) .map(meta -> json .put("title", meta.getTitle()) .put("description", meta.getDescription()) .put("image", meta.getThumbnail()) .put("official", meta.isOfficial())) .orElse(json); }
/* * 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 studio.webui.service; public class StoryTellerService implements IStoryTellerService { private static final Logger LOGGER = LogManager.getLogger(StoryTellerService.class); private final EventBus eventBus; private final DatabaseMetadataService databaseMetadataService; private RawStoryTellerAsyncDriver rawDriver; private FsStoryTellerAsyncDriver fsDriver; private Device rawDevice; private Device fsDevice; public StoryTellerService(EventBus eventBus, DatabaseMetadataService databaseMetadataService) { this.eventBus = eventBus; this.databaseMetadataService = databaseMetadataService; LOGGER.info("Setting up story teller driver"); rawDriver = new RawStoryTellerAsyncDriver(); fsDriver = new FsStoryTellerAsyncDriver(); // React when a device with firmware 1.x is plugged or unplugged rawDriver.registerDeviceListener( device -> { if (device == null) { LOGGER.error("Device 1.x plugged but got null device"); // Send 'failure' event on bus sendFailure(); } else { LOGGER.info("Device 1.x plugged"); StoryTellerService.this.rawDevice = device; CompletableFuture.runAsync(() -> rawDriver.getDeviceInfos().handle((infos, e) -> { if (e != null) { LOGGER.error("Failed to plug device 1.x", e); // Send 'failure' event on bus sendFailure(); } else { // Send 'plugged' event on bus sendDevicePlugged(toJson(infos)); } return null; })); } }, device -> { LOGGER.info("Device 1.x unplugged"); StoryTellerService.this.rawDevice = null; sendDeviceUnplugged(); }); // React when a device with firmware 2.x is plugged or unplugged fsDriver.registerDeviceListener( device -> { if (device == null) { LOGGER.error("Device 2.x plugged but got null device"); // Send 'failure' event on bus sendFailure(); } else { LOGGER.info("Device 2.x plugged"); StoryTellerService.this.fsDevice = device; CompletableFuture.runAsync(() -> fsDriver.getDeviceInfos().handle((infos, e) -> { if (e != null) { LOGGER.error("Failed to plug device 2.x", e); // Send 'failure' event on bus sendFailure(); } else { // Send 'plugged' event on bus sendDevicePlugged(toJson(infos)); } return null; })); } }, device -> { LOGGER.info("Device 2.x unplugged"); StoryTellerService.this.fsDevice = null; sendDeviceUnplugged(); }); } public CompletionStage<JsonObject> deviceInfos() { if (rawDevice != null) { return rawDriver.getDeviceInfos().thenApply(this::toJson); } if (fsDevice != null) { return fsDriver.getDeviceInfos().thenApply(this::toJson); } return CompletableFuture.completedFuture(new JsonObject().put("plugged", false)); } public CompletionStage<JsonArray> packs() { if (rawDevice != null) { return rawDriver.getPacksList().thenApply( packs -> new JsonArray(packs.stream().map(this::getRawPackMetadata).collect(Collectors.toList()))); } if (fsDevice != null) { return fsDriver.getPacksList().thenApply( packs -> new JsonArray(packs.stream().map(this::getFsPackMetadata).collect(Collectors.toList()))); } return CompletableFuture.completedFuture(new JsonArray()); } public CompletionStage<Optional<String>> addPack(String uuid, Path packFile) { if (rawDevice != null) { return rawDriver.getPacksList().thenApply(packs -> upload(packs, rawDriver, uuid, packFile)); } if (fsDevice != null) { return fsDriver.getPacksList().thenApply(packs -> upload(packs, fsDriver, uuid, packFile)); } return CompletableFuture.completedFuture(Optional.empty()); } public CompletionStage<Boolean> deletePack(String uuid) { if (rawDevice != null) { return rawDriver.deletePack(uuid); } if (fsDevice != null) { return fsDriver.deletePack(uuid); } return CompletableFuture.completedFuture(false); } public CompletionStage<Boolean> reorderPacks(List<String> uuids) { if (rawDevice != null) { return rawDriver.reorderPacks(uuids); } if (fsDevice != null) { return fsDriver.reorderPacks(uuids); } return CompletableFuture.completedFuture(false); } public CompletionStage<Optional<String>> extractPack(String uuid, Path packFile) { if (rawDevice != null) { return CompletableFuture.completedFuture(download(rawDriver, uuid, packFile)); } if (fsDevice != null) { return CompletableFuture.completedFuture(download(fsDriver, uuid, packFile)); } return CompletableFuture.completedFuture(Optional.empty()); } public CompletionStage<Void> dump(Path outputPath) { if (rawDevice != null) { return rawDriver.dump(outputPath); } // unavailable for fsDevice return CompletableFuture.completedFuture(null); } private void sendDevicePlugged(JsonObject infos) { eventBus.send("storyteller.plugged", infos); } private void sendDeviceUnplugged() { eventBus.send("storyteller.unplugged", null); } private void sendFailure() { eventBus.send("storyteller.failure", null); } private void sendProgress(String id, double p) { eventBus.send("storyteller.transfer." + id + ".progress", new JsonObject().put("progress", p)); } private void sendDone(String id, boolean success) { eventBus.send("storyteller.transfer." + id + ".done", new JsonObject().put("success", success)); } private <T,U,V extends StoryPackInfos> Optional<String> upload(List<V> packs, StoryTellerAsyncDriver<T, U> driver, String uuid, Path packFile) { // Check that the pack is not already on the device : Look for UUID in packs index boolean matched = packs.stream().anyMatch(p -> p.getUuid().equals(UUID.fromString(uuid))); if (matched) { LOGGER.error("Cannot add pack to device because the pack already exists on the device"); return Optional.empty(); } String transferId = UUID.randomUUID().toString(); try { driver.uploadPack(uuid, packFile, status -> { // Send event on eventbus to monitor progress double p = status.getPercent(); LOGGER.debug("Pack add progress... {}% ({} / {})", p, status.getTransferred(), status.getTotal()); sendProgress(transferId, p); }).whenComplete((status, t) -> { // Handle failure if (t != null) { throw new StoryTellerException(t); } // Handle success sendDone(transferId, true); }); } catch (Exception e) { LOGGER.error("Failed to add pack to device", e); // Send event on eventbus to signal transfer failure sendDone(transferId, false); } return Optional.of(transferId); } private <T, U> Optional<String> download(StoryTellerAsyncDriver<T, U> driver, String uuid, Path destFile) { // Check that the destination is available if (Files.exists(destFile.resolve(uuid))) { LOGGER.error("Cannot extract pack from device because the destination file already exists"); return Optional.empty(); } String transferId = UUID.randomUUID().toString(); try { driver.downloadPack(uuid, destFile, status -> { // Send event on eventbus to monitor progress double p = status.getPercent(); LOGGER.debug("Pack extraction progress... {}% ({} / {})", p, status.getTransferred(), status.getTotal()); sendProgress(transferId, p); }).whenComplete((status, t) -> { // Handle failure if (t != null) { throw new StoryTellerException(t); } // Handle success sendDone(transferId, true); }); } catch (Exception e) { LOGGER.error("Failed to extract pack from device", e); // Send event on eventbus to signal transfer failure sendDone(transferId, false); } return Optional.of(transferId); } private JsonObject getRawPackMetadata(RawStoryPackInfos pack) { JsonObject json = new JsonObject() .put("uuid", pack.getUuid().toString()) .put("format", PackFormat.RAW.getLabel()) .put("version", pack.getVersion()) .put("sectorSize", pack.getSizeInSectors()); return databaseMetadataService.getPackMetadata(pack.getUuid().toString()) .map(meta -> json .put("title", meta.getTitle()) .put("description", meta.getDescription()) .put("image", meta.getThumbnail()) .put("official", meta.isOfficial())) .orElse(json); } private JsonObject getFsPackMetadata(FsStoryPackInfos pack) { JsonObject json = new JsonObject() .put("uuid", pack.getUuid().toString()) .put("format", PackFormat.FS.getLabel()) .put("version", pack.getVersion()) .put("folderName", pack.getFolderName()) .put("sizeInBytes", pack.getSizeInBytes()) .put("nightModeAvailable", pack.isNightModeAvailable()); return databaseMetadataService.getPackMetadata(pack.getUuid().toString()) .map(meta -> json .put("title", meta.getTitle()) .put("description", meta.getDescription()) .put("image", meta.getThumbnail()) .put("official", meta.isOfficial())) .orElse(json); }
private JsonObject toJson(RawDeviceInfos infos) {
8
2023-12-14 15:08:35+00:00
24k
conductor-oss/conductor-community
persistence/mysql-persistence/src/main/java/com/netflix/conductor/mysql/config/MySQLConfiguration.java
[ { "identifier": "MySQLExecutionDAO", "path": "persistence/mysql-persistence/src/main/java/com/netflix/conductor/mysql/dao/MySQLExecutionDAO.java", "snippet": "public class MySQLExecutionDAO extends MySQLBaseDAO\n implements ExecutionDAO, RateLimitingDAO, PollDataDAO, ConcurrentExecutionLimitDAO {...
import java.sql.SQLException; import java.util.Optional; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Import; import org.springframework.retry.RetryContext; import org.springframework.retry.backoff.NoBackOffPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import com.netflix.conductor.mysql.dao.MySQLExecutionDAO; import com.netflix.conductor.mysql.dao.MySQLMetadataDAO; import com.netflix.conductor.mysql.dao.MySQLQueueDAO; import com.fasterxml.jackson.databind.ObjectMapper; import static com.mysql.cj.exceptions.MysqlErrorNumbers.ER_LOCK_DEADLOCK;
16,093
/* * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.mysql.config; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(MySQLProperties.class) @ConditionalOnProperty(name = "conductor.db.type", havingValue = "mysql") // Import the DataSourceAutoConfiguration when mysql database is selected. // By default the datasource configuration is excluded in the main module. @Import(DataSourceAutoConfiguration.class) public class MySQLConfiguration { @Bean @DependsOn({"flyway", "flywayInitializer"}) public MySQLMetadataDAO mySqlMetadataDAO( @Qualifier("mysqlRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper, DataSource dataSource, MySQLProperties properties) { return new MySQLMetadataDAO(retryTemplate, objectMapper, dataSource, properties); } @Bean @DependsOn({"flyway", "flywayInitializer"}) public MySQLExecutionDAO mySqlExecutionDAO( @Qualifier("mysqlRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper, DataSource dataSource) { return new MySQLExecutionDAO(retryTemplate, objectMapper, dataSource); } @Bean @DependsOn({"flyway", "flywayInitializer"})
/* * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.mysql.config; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(MySQLProperties.class) @ConditionalOnProperty(name = "conductor.db.type", havingValue = "mysql") // Import the DataSourceAutoConfiguration when mysql database is selected. // By default the datasource configuration is excluded in the main module. @Import(DataSourceAutoConfiguration.class) public class MySQLConfiguration { @Bean @DependsOn({"flyway", "flywayInitializer"}) public MySQLMetadataDAO mySqlMetadataDAO( @Qualifier("mysqlRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper, DataSource dataSource, MySQLProperties properties) { return new MySQLMetadataDAO(retryTemplate, objectMapper, dataSource, properties); } @Bean @DependsOn({"flyway", "flywayInitializer"}) public MySQLExecutionDAO mySqlExecutionDAO( @Qualifier("mysqlRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper, DataSource dataSource) { return new MySQLExecutionDAO(retryTemplate, objectMapper, dataSource); } @Bean @DependsOn({"flyway", "flywayInitializer"})
public MySQLQueueDAO mySqlQueueDAO(
2
2023-12-08 06:06:20+00:00
24k
Ispirer/COBOL-to-Java-Conversion-Samples
Java/programs/Crtab.java
[ { "identifier": "TransactionManager", "path": "IspirerFramework/com/ispirer/sw/db/TransactionManager.java", "snippet": "public class TransactionManager extends SqlCA {\r\n\tprivate static TransactionManager instance;\r\n\r\n\tprivate boolean useSqlca = false;\r\n\tprivate boolean useOraca = false;\r\n\r...
import java.sql.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ispirer.sw.db.TransactionManager; import com.ispirer.sw.exception.ExitProgram; import com.ispirer.sw.strings.AlphanumericFormat; import com.ispirer.sw.strings.DecimalFormat; import com.ispirer.sw.types.PictureType; import com.ispirer.sw.exception.StopRun;
18,022
package programs; public class Crtab { private static final Logger LOGGER = LoggerFactory.getLogger(Crtab.class); private static Crtab instance; public boolean isCalled = false; private Drptab drptab = Drptab.getInstance(); public void crtabProcedureDivision() { System.out.println(" "); System.out.println("CREATING PROD_PRICE_HIST TABLE AND INSERTING DATA..."); TransactionManager.getInstance().executeUpdate("CREATE TABLE PROD_PRICE_HIST " + " ( " + " PROD_SYMB VARCHAR2(13), " + " PREV_DAY_PRICE NUMBER(8,3), " + " LATEST_PRICE NUMBER(8,3), END_OF_MNTH_PRICE NUMBER(8,3) )"); if (TransactionManager.sqlcode == 0) { System.out.println("Table was created."); insertData(false); if (isCalled) {
package programs; public class Crtab { private static final Logger LOGGER = LoggerFactory.getLogger(Crtab.class); private static Crtab instance; public boolean isCalled = false; private Drptab drptab = Drptab.getInstance(); public void crtabProcedureDivision() { System.out.println(" "); System.out.println("CREATING PROD_PRICE_HIST TABLE AND INSERTING DATA..."); TransactionManager.getInstance().executeUpdate("CREATE TABLE PROD_PRICE_HIST " + " ( " + " PROD_SYMB VARCHAR2(13), " + " PREV_DAY_PRICE NUMBER(8,3), " + " LATEST_PRICE NUMBER(8,3), END_OF_MNTH_PRICE NUMBER(8,3) )"); if (TransactionManager.sqlcode == 0) { System.out.println("Table was created."); insertData(false); if (isCalled) {
throw new ExitProgram();
1
2023-12-13 14:56:32+00:00
24k
i-moonlight/Suricate
src/test/java/com/michelin/suricate/controllers/ProjectControllerTest.java
[ { "identifier": "ProjectRequestDto", "path": "src/main/java/com/michelin/suricate/model/dto/api/project/ProjectRequestDto.java", "snippet": "@Data\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = false)\n@Schema(description = \"Create or update a project\")\npublic class ProjectRequestDto extends Abs...
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.michelin.suricate.model.dto.api.project.ProjectRequestDto; import com.michelin.suricate.model.dto.api.project.ProjectResponseDto; import com.michelin.suricate.model.dto.api.projectwidget.ProjectWidgetPositionRequestDto; import com.michelin.suricate.model.dto.api.user.UserResponseDto; import com.michelin.suricate.model.dto.websocket.WebsocketClient; import com.michelin.suricate.model.entities.Project; import com.michelin.suricate.model.entities.ProjectGrid; import com.michelin.suricate.model.entities.Role; import com.michelin.suricate.model.entities.User; import com.michelin.suricate.security.LocalUser; import com.michelin.suricate.services.api.ProjectGridService; import com.michelin.suricate.services.api.ProjectService; import com.michelin.suricate.services.api.ProjectWidgetService; import com.michelin.suricate.services.api.UserService; import com.michelin.suricate.services.mapper.ProjectGridMapper; import com.michelin.suricate.services.mapper.ProjectMapper; import com.michelin.suricate.services.mapper.UserMapper; import com.michelin.suricate.services.websocket.DashboardWebSocketService; import com.michelin.suricate.utils.exceptions.ApiException; import com.michelin.suricate.utils.exceptions.InvalidFileException; import com.michelin.suricate.utils.exceptions.ObjectNotFoundException; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; 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.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes;
18,157
when(file.getOriginalFilename()) .thenReturn("originalName"); assertThatThrownBy(() -> projectController.updateProjectScreenshot(localUser, "token", file)) .isInstanceOf(InvalidFileException.class) .hasMessage("The file originalName cannot be read for entity Project '1'"); } @Test void shouldUpdateProjectScreenshot() { Project project = new Project(); project.setId(1L); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); MockMultipartFile file = new MockMultipartFile("name", "originalName", "image/png", new byte[10]); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectService.isConnectedUserCanAccessToProject(any(), any())) .thenReturn(true); ResponseEntity<Void> actual = projectController.updateProjectScreenshot(localUser, "token", file); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); assertThat(actual.getBody()).isNull(); } @Test void shouldDeleteProjectByIdNotFound() { Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); when(projectService.getOneByToken(any())) .thenReturn(Optional.empty()); assertThatThrownBy(() -> projectController.deleteProjectById(localUser, "token")) .isInstanceOf(ObjectNotFoundException.class) .hasMessage("Project 'token' not found"); } @Test void shouldDeleteProjectByIdNotAuthorized() { Project project = new Project(); project.setId(1L); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectService.isConnectedUserCanAccessToProject(any(), any())) .thenReturn(false); assertThatThrownBy(() -> projectController.deleteProjectById(localUser, "token")) .isInstanceOf(ApiException.class) .hasMessage("The user is not allowed to modify this project"); } @Test void shouldDeleteProjectById() { Project project = new Project(); project.setId(1L); ProjectRequestDto projectRequestDto = new ProjectRequestDto(); projectRequestDto.setName("name"); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectService.isConnectedUserCanAccessToProject(any(), any())) .thenReturn(true); ResponseEntity<Void> actual = projectController.deleteProjectById(localUser, "token"); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); assertThat(actual.getBody()).isNull(); } @Test void shouldUpdateProjectWidgetsPositionForProjectNotFound() {
package com.michelin.suricate.controllers; @ExtendWith(MockitoExtension.class) class ProjectControllerTest { @Mock private ProjectService projectService; @Mock private ProjectGridService projectGridService; @Mock private ProjectWidgetService projectWidgetService; @Mock private UserService userService; @Mock private ProjectMapper projectMapper; @Mock private ProjectGridMapper projectGridMapper; @Mock private UserMapper userMapper; @Mock private DashboardWebSocketService dashboardWebSocketService; @InjectMocks private ProjectController projectController; @Test void shouldGetAll() { Project project = new Project(); project.setId(1L); ProjectResponseDto projectResponseDto = new ProjectResponseDto(); projectResponseDto.setName("name"); when(projectService.getAll(any(), any())) .thenReturn(new PageImpl<>(Collections.singletonList(project))); when(projectMapper.toProjectDtoNoAsset(any())) .thenReturn(projectResponseDto); Page<ProjectResponseDto> actual = projectController.getAll("search", Pageable.unpaged()); assertThat(actual).isNotEmpty(); assertThat(actual.get()).hasSize(1); assertThat(actual.get().toList().get(0)).isEqualTo(projectResponseDto); } @Test void shouldCreateProjectUserNotFound() { ProjectRequestDto projectRequestDto = new ProjectRequestDto(); projectRequestDto.setName("name"); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); when(userService.getOneByUsername(any())) .thenReturn(Optional.empty()); assertThatThrownBy(() -> projectController.createProject(localUser, projectRequestDto)) .isInstanceOf(ObjectNotFoundException.class) .hasMessage("User 'username' not found"); } @Test void shouldCreateProject() { ProjectRequestDto projectRequestDto = new ProjectRequestDto(); projectRequestDto.setName("name"); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); ProjectResponseDto projectResponseDto = new ProjectResponseDto(); projectResponseDto.setName("name"); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest())); when(userService.getOneByUsername(any())) .thenReturn(Optional.of(user)); when(projectService.createProjectForUser(any(), any())) .thenReturn(new Project()); when(projectGridMapper.toProjectGridEntity(any(Project.class))) .thenReturn(new ProjectGrid()); when(projectGridService.create(any())) .thenReturn(new ProjectGrid()); when(projectMapper.toProjectDto(any())) .thenReturn(projectResponseDto); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); ResponseEntity<ProjectResponseDto> actual = projectController.createProject(localUser, projectRequestDto); assertThat(actual.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.CREATED); assertThat(actual.getBody()).isNotNull(); assertThat(actual.getBody()).isEqualTo(projectResponseDto); } @Test void shouldGetOneByTokenNotFound() { when(projectService.getOneByToken(any())) .thenReturn(Optional.empty()); assertThatThrownBy(() -> projectController.getOneByToken("token")) .isInstanceOf(ObjectNotFoundException.class) .hasMessage("Project 'token' not found"); } @Test void shouldGetOneByToken() { Project project = new Project(); project.setId(1L); ProjectResponseDto projectResponseDto = new ProjectResponseDto(); projectResponseDto.setName("name"); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectMapper.toProjectDto(any())) .thenReturn(projectResponseDto); ResponseEntity<ProjectResponseDto> actual = projectController.getOneByToken("token"); assertThat(actual.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(actual.getBody()).isNotNull(); assertThat(actual.getBody()).isEqualTo(projectResponseDto); } @Test void shouldUpdateProjectNotFound() { ProjectRequestDto projectRequestDto = new ProjectRequestDto(); projectRequestDto.setName("name"); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); when(projectService.getOneByToken(any())) .thenReturn(Optional.empty()); assertThatThrownBy(() -> projectController.updateProject(localUser, "token", projectRequestDto)) .isInstanceOf(ObjectNotFoundException.class) .hasMessage("Project 'token' not found"); } @Test void shouldUpdateProjectNotAuthorized() { Project project = new Project(); project.setId(1L); ProjectRequestDto projectRequestDto = new ProjectRequestDto(); projectRequestDto.setName("name"); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectService.isConnectedUserCanAccessToProject(any(), any())) .thenReturn(false); assertThatThrownBy(() -> projectController.updateProject(localUser, "token", projectRequestDto)) .isInstanceOf(ApiException.class) .hasMessage("The user is not allowed to modify this project"); } @Test void shouldUpdateProject() { Project project = new Project(); project.setId(1L); ProjectRequestDto projectRequestDto = new ProjectRequestDto(); projectRequestDto.setName("name"); projectRequestDto.setWidgetHeight(1); projectRequestDto.setMaxColumn(1); projectRequestDto.setCssStyle("css"); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectService.isConnectedUserCanAccessToProject(any(), any())) .thenReturn(true); ResponseEntity<Void> actual = projectController.updateProject(localUser, "token", projectRequestDto); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); assertThat(actual.getBody()).isNull(); } @Test void shouldUpdateProjectScreenshotNotFound() { Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); MockMultipartFile file = new MockMultipartFile("name", new byte[10]); when(projectService.getOneByToken(any())) .thenReturn(Optional.empty()); assertThatThrownBy(() -> projectController.updateProjectScreenshot(localUser, "token", file)) .isInstanceOf(ObjectNotFoundException.class) .hasMessage("Project 'token' not found"); } @Test void shouldUpdateProjectScreenshotNotAuthorized() { Project project = new Project(); project.setId(1L); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); MockMultipartFile file = new MockMultipartFile("name", new byte[10]); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectService.isConnectedUserCanAccessToProject(any(), any())) .thenReturn(false); assertThatThrownBy(() -> projectController.updateProjectScreenshot(localUser, "token", file)) .isInstanceOf(ApiException.class) .hasMessage("The user is not allowed to modify this project"); } @Test void shouldThrowExceptionWhenUpdatingProjectScreenshot() throws IOException { Project project = new Project(); project.setId(1L); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); MockMultipartFile file = mock(MockMultipartFile.class); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectService.isConnectedUserCanAccessToProject(any(), any())) .thenReturn(true); doThrow(new IOException("error")).when(file) .getBytes(); when(file.getOriginalFilename()) .thenReturn("originalName"); assertThatThrownBy(() -> projectController.updateProjectScreenshot(localUser, "token", file)) .isInstanceOf(InvalidFileException.class) .hasMessage("The file originalName cannot be read for entity Project '1'"); } @Test void shouldUpdateProjectScreenshot() { Project project = new Project(); project.setId(1L); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); MockMultipartFile file = new MockMultipartFile("name", "originalName", "image/png", new byte[10]); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectService.isConnectedUserCanAccessToProject(any(), any())) .thenReturn(true); ResponseEntity<Void> actual = projectController.updateProjectScreenshot(localUser, "token", file); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); assertThat(actual.getBody()).isNull(); } @Test void shouldDeleteProjectByIdNotFound() { Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); when(projectService.getOneByToken(any())) .thenReturn(Optional.empty()); assertThatThrownBy(() -> projectController.deleteProjectById(localUser, "token")) .isInstanceOf(ObjectNotFoundException.class) .hasMessage("Project 'token' not found"); } @Test void shouldDeleteProjectByIdNotAuthorized() { Project project = new Project(); project.setId(1L); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectService.isConnectedUserCanAccessToProject(any(), any())) .thenReturn(false); assertThatThrownBy(() -> projectController.deleteProjectById(localUser, "token")) .isInstanceOf(ApiException.class) .hasMessage("The user is not allowed to modify this project"); } @Test void shouldDeleteProjectById() { Project project = new Project(); project.setId(1L); ProjectRequestDto projectRequestDto = new ProjectRequestDto(); projectRequestDto.setName("name"); Role role = new Role(); role.setId(1L); role.setName("ROLE_ADMIN"); User user = new User(); user.setId(1L); user.setUsername("username"); user.setPassword("password"); user.setRoles(Collections.singleton(role)); LocalUser localUser = new LocalUser(user, Collections.emptyMap()); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectService.isConnectedUserCanAccessToProject(any(), any())) .thenReturn(true); ResponseEntity<Void> actual = projectController.deleteProjectById(localUser, "token"); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); assertThat(actual.getBody()).isNull(); } @Test void shouldUpdateProjectWidgetsPositionForProjectNotFound() {
ProjectWidgetPositionRequestDto projectWidgetPositionRequestDto = new ProjectWidgetPositionRequestDto();
2
2023-12-11 11:28:37+00:00
24k
fiber-net-gateway/fiber-net-gateway
fiber-gateway-proxy/src/main/java/io/fiber/net/proxy/lib/HttpFunc.java
[ { "identifier": "FiberException", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/FiberException.java", "snippet": "public class FiberException extends Exception {\n private int code;\n private final String errorName;\n\n public FiberException(String message, int code, String er...
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.IntNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.fiber.net.common.FiberException; import io.fiber.net.common.HttpExchange; import io.fiber.net.common.HttpMethod; import io.fiber.net.common.async.internal.SerializeJsonObservable; import io.fiber.net.common.utils.ArrayUtils; import io.fiber.net.common.utils.Constant; import io.fiber.net.common.utils.JsonUtil; import io.fiber.net.common.utils.StringUtils; import io.fiber.net.http.ClientExchange; import io.fiber.net.http.HttpClient; import io.fiber.net.http.HttpHost; import io.fiber.net.http.util.UrlEncoded; import io.fiber.net.script.ExecutionContext; import io.fiber.net.script.Library; import io.fiber.net.script.ScriptExecException; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Iterator; import java.util.Map;
15,147
package io.fiber.net.proxy.lib; public class HttpFunc implements Library.DirectiveDef { private final HttpHost httpHost; private final HttpClient httpClient; private final Map<String, HttpDynamicFunc> fc = new HashMap<>(); public HttpFunc(HttpHost httpHost, HttpClient httpClient) { this.httpHost = httpHost; this.httpClient = httpClient; fc.put("request", new SendFunc()); fc.put("proxyPass", new ProxyFunc()); } @Override public Library.Function findFunc(String directive, String function) { return fc.get(function); } private class SendFunc implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) { JsonNode param = ArrayUtils.isNotEmpty(args) ? args[0] : NullNode.getInstance(); ClientExchange exchange = httpClient.refer(httpHost); setMethod(param, HttpMethod.GET, exchange); setUri(param, "/", null, exchange); addHeader(exchange, param); JsonNode node = param.get("body"); if (node != null) { if (node.isBinary()) { exchange.setReqBufFullFunc(ec -> Unpooled.wrappedBuffer(node.binaryValue())); } else { exchange.setHeader(Constant.CONTENT_TYPE_HEADER, Constant.CONTENT_TYPE_JSON_UTF8); exchange.setReqBodyFunc(ec -> new SerializeJsonObservable(node, ByteBufAllocator.DEFAULT), false); } } exchange.sendForResp().subscribe((response, e) -> { if (e != null) { context.throwErr(this, new ScriptExecException("error send http", e)); } else { ObjectNode nodes = JsonUtil.MAPPER.createObjectNode(); nodes.put("status", response.status()); response.readFullRespBody().subscribe((buf, e2) -> { byte[] bytes = ByteBufUtil.getBytes(buf); nodes.put("body", bytes); buf.release(); context.returnVal(this, nodes); }); } }); } } private static void setMethod(JsonNode param, HttpMethod mtd, ClientExchange exchange) { JsonNode node = param.get("method"); if (node != null && node.isTextual()) { try { mtd = HttpMethod.valueOf(node.textValue().toUpperCase()); } catch (RuntimeException ignore) { } } exchange.setMethod(mtd); } private static void addHeader(ClientExchange exchange, JsonNode param) { JsonNode node = param.get("headers"); if (JsonUtil.isNull(node) || !node.isObject() || node.isEmpty()) { return; } Iterator<Map.Entry<String, JsonNode>> fields = node.fields(); do { Map.Entry<String, JsonNode> next = fields.next(); String key = next.getKey(); JsonNode jsonNode = next.getValue(); if (JsonUtil.isNull(jsonNode)) { exchange.removeHeader(key); } else if (jsonNode.isTextual() && StringUtils.isNotEmpty(jsonNode.textValue())) { exchange.setHeader(key, jsonNode.textValue()); } } while (fields.hasNext()); } private static void setUri(JsonNode param, String path, String query, ClientExchange exchange) { JsonNode node; node = param.get("path"); if (node != null && node.isTextual() && StringUtils.isNotEmpty(node.textValue())) { path = node.textValue(); } String uri = path; node = param.get("query"); if (node != null) { if (node.isTextual() && StringUtils.isNotEmpty(node.textValue())) { uri = uri + '?' + node.textValue(); } else if (node.isObject() && !node.isEmpty()) { StringBuilder builder = new StringBuilder(uri.length() + 64); builder.append(uri).append('?'); Iterator<Map.Entry<String, JsonNode>> fields = node.fields(); do { Map.Entry<String, JsonNode> next = fields.next(); JsonNode jsonNode = next.getValue(); String key = next.getKey(); if (jsonNode.isArray()) { for (JsonNode n : jsonNode) {
package io.fiber.net.proxy.lib; public class HttpFunc implements Library.DirectiveDef { private final HttpHost httpHost; private final HttpClient httpClient; private final Map<String, HttpDynamicFunc> fc = new HashMap<>(); public HttpFunc(HttpHost httpHost, HttpClient httpClient) { this.httpHost = httpHost; this.httpClient = httpClient; fc.put("request", new SendFunc()); fc.put("proxyPass", new ProxyFunc()); } @Override public Library.Function findFunc(String directive, String function) { return fc.get(function); } private class SendFunc implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) { JsonNode param = ArrayUtils.isNotEmpty(args) ? args[0] : NullNode.getInstance(); ClientExchange exchange = httpClient.refer(httpHost); setMethod(param, HttpMethod.GET, exchange); setUri(param, "/", null, exchange); addHeader(exchange, param); JsonNode node = param.get("body"); if (node != null) { if (node.isBinary()) { exchange.setReqBufFullFunc(ec -> Unpooled.wrappedBuffer(node.binaryValue())); } else { exchange.setHeader(Constant.CONTENT_TYPE_HEADER, Constant.CONTENT_TYPE_JSON_UTF8); exchange.setReqBodyFunc(ec -> new SerializeJsonObservable(node, ByteBufAllocator.DEFAULT), false); } } exchange.sendForResp().subscribe((response, e) -> { if (e != null) { context.throwErr(this, new ScriptExecException("error send http", e)); } else { ObjectNode nodes = JsonUtil.MAPPER.createObjectNode(); nodes.put("status", response.status()); response.readFullRespBody().subscribe((buf, e2) -> { byte[] bytes = ByteBufUtil.getBytes(buf); nodes.put("body", bytes); buf.release(); context.returnVal(this, nodes); }); } }); } } private static void setMethod(JsonNode param, HttpMethod mtd, ClientExchange exchange) { JsonNode node = param.get("method"); if (node != null && node.isTextual()) { try { mtd = HttpMethod.valueOf(node.textValue().toUpperCase()); } catch (RuntimeException ignore) { } } exchange.setMethod(mtd); } private static void addHeader(ClientExchange exchange, JsonNode param) { JsonNode node = param.get("headers"); if (JsonUtil.isNull(node) || !node.isObject() || node.isEmpty()) { return; } Iterator<Map.Entry<String, JsonNode>> fields = node.fields(); do { Map.Entry<String, JsonNode> next = fields.next(); String key = next.getKey(); JsonNode jsonNode = next.getValue(); if (JsonUtil.isNull(jsonNode)) { exchange.removeHeader(key); } else if (jsonNode.isTextual() && StringUtils.isNotEmpty(jsonNode.textValue())) { exchange.setHeader(key, jsonNode.textValue()); } } while (fields.hasNext()); } private static void setUri(JsonNode param, String path, String query, ClientExchange exchange) { JsonNode node; node = param.get("path"); if (node != null && node.isTextual() && StringUtils.isNotEmpty(node.textValue())) { path = node.textValue(); } String uri = path; node = param.get("query"); if (node != null) { if (node.isTextual() && StringUtils.isNotEmpty(node.textValue())) { uri = uri + '?' + node.textValue(); } else if (node.isObject() && !node.isEmpty()) { StringBuilder builder = new StringBuilder(uri.length() + 64); builder.append(uri).append('?'); Iterator<Map.Entry<String, JsonNode>> fields = node.fields(); do { Map.Entry<String, JsonNode> next = fields.next(); JsonNode jsonNode = next.getValue(); String key = next.getKey(); if (jsonNode.isArray()) { for (JsonNode n : jsonNode) {
UrlEncoded.encodeInto(key, StandardCharsets.UTF_8, builder);
11
2023-12-08 15:18:05+00:00
24k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/tag/id3/ID3v24Frame.java
[ { "identifier": "FileConstants", "path": "android/src/main/java/org/jaudiotagger/FileConstants.java", "snippet": "public interface FileConstants\n{\n /**\n * defined for convenience\n */\n int BIT7 = 0x80;\n /**\n * defined for convenience\n */\n int BIT6 = 0x40;\n /**\n ...
import java.nio.charset.Charset; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jaudiotagger.FileConstants; import org.jaudiotagger.StandardCharsets; import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.logging.ErrorMessage; import org.jaudiotagger.logging.Hex; import org.jaudiotagger.tag.*; import org.jaudiotagger.tag.datatype.Lyrics3Line; import org.jaudiotagger.tag.id3.framebody.*; import org.jaudiotagger.tag.id3.valuepair.TextEncoding; import org.jaudiotagger.tag.lyrics3.*; import org.jaudiotagger.utils.EqualsUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer;
17,412
{ this.frameBody = new FrameBodyTMOO((FrameBodyTXXX) frame.getBody()); this.frameBody.setHeader(this); identifier = frameBody.getIdentifier(); } else { logger.finer("V3:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier); this.frameBody = (AbstractTagFrameBody) ID3Tags.copyObject(frame.getBody()); this.frameBody.setHeader(this); } } // Is it a known v3 frame which needs forcing to v4 frame e.g. TYER - TDRC else if (ID3Tags.isID3v23FrameIdentifier(frame.getIdentifier())) { identifier = ID3Tags.forceFrameID23To24(frame.getIdentifier()); if (identifier != null) { logger.config("V3:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier); this.frameBody = this.readBody(identifier, (AbstractID3v2FrameBody) frame.getBody()); this.frameBody.setHeader(this); } // No mechanism exists to convert it to a v24 frame, e.g deprecated frame e.g TSIZ, so hold // as a deprecated frame consisting of an array of bytes*/ else { this.frameBody = new FrameBodyDeprecated((AbstractID3v2FrameBody) frame.getBody()); this.frameBody.setHeader(this); identifier = frame.getIdentifier(); logger.finer("V3:Deprecated:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier); } } // Unknown Frame e.g NCON or TDRL (because TDRL unknown to V23) else { this.frameBody = new FrameBodyUnsupported((FrameBodyUnsupported) frame.getBody()); this.frameBody.setHeader(this); identifier = frame.getIdentifier(); logger.finer("V3:Unknown:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier); } } /** * Partially construct ID3v24 Frame form an IS3v23Frame * * Used for Special Cases * * @param frame * @param identifier * @throws InvalidFrameException */ protected ID3v24Frame(ID3v23Frame frame, String identifier) throws InvalidFrameException { this.identifier=identifier; statusFlags = new StatusFlags((ID3v23Frame.StatusFlags) frame.getStatusFlags()); encodingFlags = new EncodingFlags(frame.getEncodingFlags().getFlags()); } /** * Creates a new ID3v24 frame datatype based on another frame of different version * Converts the framebody to the equivalent v24 framebody or to UnsupportedFrameBody if identifier * is unknown. * * @param frame to construct a new frame from * @throws org.jaudiotagger.tag.InvalidFrameException * */ public ID3v24Frame(AbstractID3v2Frame frame) throws InvalidFrameException { //Should not be called if ((frame instanceof ID3v24Frame)) { throw new UnsupportedOperationException("Copy Constructor not called. Please type cast the argument"); } else if (frame instanceof ID3v23Frame) { statusFlags = new StatusFlags((ID3v23Frame.StatusFlags) frame.getStatusFlags()); encodingFlags = new EncodingFlags(frame.getEncodingFlags().getFlags()); } else if (frame instanceof ID3v22Frame) { statusFlags = new StatusFlags(); encodingFlags = new EncodingFlags(); } // Convert Identifier. If the id was a known id for the original // version we should be able to convert it to an v24 frame, although it may mean minor // modification to the data. If it was not recognised originally it should remain // unknown. if (frame instanceof ID3v23Frame) { createV24FrameFromV23Frame((ID3v23Frame) frame); } else if (frame instanceof ID3v22Frame) { ID3v23Frame v23Frame = new ID3v23Frame(frame); createV24FrameFromV23Frame(v23Frame); } this.frameBody.setHeader(this); } /** * Creates a new ID3v2_4Frame datatype based on Lyrics3. * * @param field * @throws InvalidTagException */ public ID3v24Frame(Lyrics3v2Field field) throws InvalidTagException { String id = field.getIdentifier(); String value; if (id.equals("IND")) { throw new InvalidTagException("Cannot create ID3v2.40 frame from Lyrics3 indications field."); } else if (id.equals("LYR")) { FieldFrameBodyLYR lyric = (FieldFrameBodyLYR) field.getBody();
/* * MusicTag Copyright (C)2003,2004 * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jaudiotagger.tag.id3; /** * Represents an ID3v2.4 frame. * * @author : Paul Taylor * @author : Eric Farng * @version $Id$ */ public class ID3v24Frame extends AbstractID3v2Frame { private static Pattern validFrameIdentifier = Pattern.compile("[A-Z][0-9A-Z]{3}"); protected static final int FRAME_DATA_LENGTH_SIZE = 4; protected static final int FRAME_ID_SIZE = 4; protected static final int FRAME_FLAGS_SIZE = 2; protected static final int FRAME_SIZE_SIZE = 4; protected static final int FRAME_ENCRYPTION_INDICATOR_SIZE = 1; protected static final int FRAME_GROUPING_INDICATOR_SIZE = 1; protected static final int FRAME_HEADER_SIZE = FRAME_ID_SIZE + FRAME_SIZE_SIZE + FRAME_FLAGS_SIZE; /** * If the frame is encrypted then the encryption method is stored in this byte */ private int encryptionMethod; /** * If the frame belongs in a group with other frames then the group identifier byte is stored */ private int groupIdentifier; protected int getFrameIdSize() { return FRAME_ID_SIZE; } protected int getFrameSizeSize() { return FRAME_SIZE_SIZE; } protected int getFrameFlagsSize() { return FRAME_FLAGS_SIZE; } protected int getFrameHeaderSize() { return FRAME_HEADER_SIZE; } public ID3v24Frame() { } /** * Creates a new ID3v2_4Frame of type identifier. An empty * body of the correct type will be automatically created. * This constructor should be used when wish to create a new * frame from scratch using user input * * @param identifier defines the type of body to be created */ public ID3v24Frame(String identifier) { //Super Constructor creates a frame with empty body of type specified super(identifier); statusFlags = new StatusFlags(); encodingFlags = new EncodingFlags(); } /** * Copy Constructor:Creates a new ID3v24 frame datatype based on another frame. * * @param frame */ public ID3v24Frame(ID3v24Frame frame) { super(frame); statusFlags = new StatusFlags(frame.getStatusFlags().getOriginalFlags()); encodingFlags = new EncodingFlags(frame.getEncodingFlags().getFlags()); } private void createV24FrameFromV23Frame(ID3v23Frame frame) throws InvalidFrameException { // Is it a straight conversion e.g TALB - TALB identifier = ID3Tags.convertFrameID23To24(frame.getIdentifier()); logger.finer("Creating V24frame from v23:" + frame.getIdentifier() + ":" + identifier); //We cant convert unsupported bodies properly if (frame.getBody() instanceof FrameBodyUnsupported) { this.frameBody = new FrameBodyUnsupported((FrameBodyUnsupported) frame.getBody()); this.frameBody.setHeader(this); identifier = frame.getIdentifier(); logger.finer("V3:UnsupportedBody:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier); }//Simple Copy else if (identifier != null) { //Special Case if ((frame.getIdentifier().equals(ID3v23Frames.FRAME_ID_V3_USER_DEFINED_INFO)) && (((FrameBodyTXXX) frame.getBody()).getDescription().equals(FrameBodyTXXX.MOOD))) { this.frameBody = new FrameBodyTMOO((FrameBodyTXXX) frame.getBody()); this.frameBody.setHeader(this); identifier = frameBody.getIdentifier(); } else { logger.finer("V3:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier); this.frameBody = (AbstractTagFrameBody) ID3Tags.copyObject(frame.getBody()); this.frameBody.setHeader(this); } } // Is it a known v3 frame which needs forcing to v4 frame e.g. TYER - TDRC else if (ID3Tags.isID3v23FrameIdentifier(frame.getIdentifier())) { identifier = ID3Tags.forceFrameID23To24(frame.getIdentifier()); if (identifier != null) { logger.config("V3:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier); this.frameBody = this.readBody(identifier, (AbstractID3v2FrameBody) frame.getBody()); this.frameBody.setHeader(this); } // No mechanism exists to convert it to a v24 frame, e.g deprecated frame e.g TSIZ, so hold // as a deprecated frame consisting of an array of bytes*/ else { this.frameBody = new FrameBodyDeprecated((AbstractID3v2FrameBody) frame.getBody()); this.frameBody.setHeader(this); identifier = frame.getIdentifier(); logger.finer("V3:Deprecated:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier); } } // Unknown Frame e.g NCON or TDRL (because TDRL unknown to V23) else { this.frameBody = new FrameBodyUnsupported((FrameBodyUnsupported) frame.getBody()); this.frameBody.setHeader(this); identifier = frame.getIdentifier(); logger.finer("V3:Unknown:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier); } } /** * Partially construct ID3v24 Frame form an IS3v23Frame * * Used for Special Cases * * @param frame * @param identifier * @throws InvalidFrameException */ protected ID3v24Frame(ID3v23Frame frame, String identifier) throws InvalidFrameException { this.identifier=identifier; statusFlags = new StatusFlags((ID3v23Frame.StatusFlags) frame.getStatusFlags()); encodingFlags = new EncodingFlags(frame.getEncodingFlags().getFlags()); } /** * Creates a new ID3v24 frame datatype based on another frame of different version * Converts the framebody to the equivalent v24 framebody or to UnsupportedFrameBody if identifier * is unknown. * * @param frame to construct a new frame from * @throws org.jaudiotagger.tag.InvalidFrameException * */ public ID3v24Frame(AbstractID3v2Frame frame) throws InvalidFrameException { //Should not be called if ((frame instanceof ID3v24Frame)) { throw new UnsupportedOperationException("Copy Constructor not called. Please type cast the argument"); } else if (frame instanceof ID3v23Frame) { statusFlags = new StatusFlags((ID3v23Frame.StatusFlags) frame.getStatusFlags()); encodingFlags = new EncodingFlags(frame.getEncodingFlags().getFlags()); } else if (frame instanceof ID3v22Frame) { statusFlags = new StatusFlags(); encodingFlags = new EncodingFlags(); } // Convert Identifier. If the id was a known id for the original // version we should be able to convert it to an v24 frame, although it may mean minor // modification to the data. If it was not recognised originally it should remain // unknown. if (frame instanceof ID3v23Frame) { createV24FrameFromV23Frame((ID3v23Frame) frame); } else if (frame instanceof ID3v22Frame) { ID3v23Frame v23Frame = new ID3v23Frame(frame); createV24FrameFromV23Frame(v23Frame); } this.frameBody.setHeader(this); } /** * Creates a new ID3v2_4Frame datatype based on Lyrics3. * * @param field * @throws InvalidTagException */ public ID3v24Frame(Lyrics3v2Field field) throws InvalidTagException { String id = field.getIdentifier(); String value; if (id.equals("IND")) { throw new InvalidTagException("Cannot create ID3v2.40 frame from Lyrics3 indications field."); } else if (id.equals("LYR")) { FieldFrameBodyLYR lyric = (FieldFrameBodyLYR) field.getBody();
Lyrics3Line line;
5
2023-12-11 05:58:19+00:00
24k
xhtcode/xht-cloud-parent
xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/service/impl/SysUserServiceImpl.java
[ { "identifier": "PageResponse", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java", "snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @...
import cn.hutool.captcha.generator.RandomGenerator; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.RandomUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.xht.cloud.framework.core.api.response.PageResponse; import com.xht.cloud.framework.core.constant.CommonConstants; import com.xht.cloud.framework.core.support.StringUtils; import com.xht.cloud.framework.exception.Assert; import com.xht.cloud.framework.exception.business.UserNameNotFountException; import com.xht.cloud.framework.mybatis.core.DataScopeFieldBuilder; import com.xht.cloud.framework.mybatis.core.enums.DataScopeTypeEnums; import com.xht.cloud.framework.mybatis.handler.DataScopeFactory; import com.xht.cloud.framework.mybatis.tool.PageTool; import com.xht.cloud.framework.redis.key.RedisKeyTool; import com.xht.cloud.framework.redis.service.RedisService; import com.xht.cloud.framework.security.constant.UserTypeEnums; import com.xht.cloud.framework.security.support.SecurityContextUtil; import com.xht.cloud.system.enums.MenuTypeEnums; import com.xht.cloud.system.manager.MinioManager; import com.xht.cloud.system.module.dept.controller.response.SysDeptResponse; import com.xht.cloud.system.module.dept.convert.SysDeptConvert; import com.xht.cloud.system.module.dept.dao.dataobject.SysDeptDO; import com.xht.cloud.system.module.dept.dao.mapper.SysDeptMapper; import com.xht.cloud.system.module.permissions.dao.dataobject.SysMenuDO; import com.xht.cloud.system.module.permissions.dao.dataobject.SysRoleDO; import com.xht.cloud.system.module.permissions.dao.mapper.SysMenuMapper; import com.xht.cloud.system.module.permissions.dao.mapper.SysRoleMapper; import com.xht.cloud.system.module.user.controller.request.SysUserBaseAddUpdate; import com.xht.cloud.system.module.user.controller.request.SysUserProfileRequest; import com.xht.cloud.system.module.user.controller.request.SysUserQueryRequest; import com.xht.cloud.system.module.user.controller.request.UpdatePassWordRequest; import com.xht.cloud.system.module.user.controller.response.SysUserProfileResponse; import com.xht.cloud.system.module.user.controller.response.SysUserResponse; import com.xht.cloud.system.module.user.controller.response.SysUserVo; import com.xht.cloud.system.module.user.convert.SysUserConvert; import com.xht.cloud.system.module.user.convert.SysUserProfileConvert; import com.xht.cloud.system.module.user.dao.dataobject.SysUserDO; import com.xht.cloud.system.module.user.dao.dataobject.SysUserProfileDO; import com.xht.cloud.system.module.user.dao.mapper.SysUserMapper; import com.xht.cloud.system.module.user.dao.mapper.SysUserProfileMapper; import com.xht.cloud.system.module.user.dao.wrapper.SysUserWrapper; import com.xht.cloud.system.module.user.service.ISysUserService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.io.InputStream; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
17,804
package com.xht.cloud.system.module.user.service.impl; /** * 描述 :用户 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysUserServiceImpl implements ISysUserService { private final SysUserMapper sysUserMapper; private final SysUserProfileMapper sysUserProfileMapper; private final SysUserConvert sysUserConvert; private final SysUserProfileConvert sysUserProfileConvert; private final SysRoleMapper sysRoleMapper; private final SysMenuMapper sysMenuMapper; private final DataScopeFactory dataScopeFactory; private final PasswordEncoder passwordEncoder; private final RedisService redisService; private final SysDeptConvert sysDeptConvert; private final SysDeptMapper sysDeptMapper;
package com.xht.cloud.system.module.user.service.impl; /** * 描述 :用户 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysUserServiceImpl implements ISysUserService { private final SysUserMapper sysUserMapper; private final SysUserProfileMapper sysUserProfileMapper; private final SysUserConvert sysUserConvert; private final SysUserProfileConvert sysUserProfileConvert; private final SysRoleMapper sysRoleMapper; private final SysMenuMapper sysMenuMapper; private final DataScopeFactory dataScopeFactory; private final PasswordEncoder passwordEncoder; private final RedisService redisService; private final SysDeptConvert sysDeptConvert; private final SysDeptMapper sysDeptMapper;
private final MinioManager minioManager;
14
2023-12-12 08:16:30+00:00
24k
serendipitk/LunarCore
src/main/java/emu/lunarcore/server/packet/recv/HandlerGetFriendRecommendListInfoCsReq.java
[ { "identifier": "GameSession", "path": "src/main/java/emu/lunarcore/server/game/GameSession.java", "snippet": "@Getter\npublic class GameSession {\n private final GameServer server;\n private final Int2LongMap packetCooldown;\n private InetSocketAddress address;\n\n private Account account;\...
import emu.lunarcore.server.game.GameSession; import emu.lunarcore.server.packet.CmdId; import emu.lunarcore.server.packet.Opcodes; import emu.lunarcore.server.packet.PacketHandler; import emu.lunarcore.server.packet.send.PacketGetFriendRecommendListInfoScRsp;
20,074
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetFriendRecommendListInfoCsReq) public class HandlerGetFriendRecommendListInfoCsReq extends PacketHandler { @Override
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetFriendRecommendListInfoCsReq) public class HandlerGetFriendRecommendListInfoCsReq extends PacketHandler { @Override
public void handle(GameSession session, byte[] data) throws Exception {
0
2023-12-08 14:13:04+00:00
24k
quentin452/Garden-Stuff-Continuation
src/main/resources/com/jaquadro/minecraft/gardenstuff/renderer/LanternRenderer.java
[ { "identifier": "GardenAPI", "path": "src/main/java/com/jaquadro/minecraft/gardenapi/api/GardenAPI.java", "snippet": "public class GardenAPI {\n\n private static IGardenAPI instance;\n\n public static IGardenAPI instance() {\n if (instance == null) {\n try {\n Clas...
import com.jaquadro.minecraft.gardenapi.api.GardenAPI; import com.jaquadro.minecraft.gardenapi.api.component.ILanternSource; import com.jaquadro.minecraft.gardenapi.api.connect.IAttachable; import com.jaquadro.minecraft.gardenapi.api.connect.IChainSingleAttachable; import com.jaquadro.minecraft.gardenapi.internal.Api; import com.jaquadro.minecraft.gardencore.util.BindingStack; import com.jaquadro.minecraft.gardencore.util.RenderHelper; import com.jaquadro.minecraft.gardenstuff.GardenStuff; import com.jaquadro.minecraft.gardenstuff.block.BlockLantern; import com.jaquadro.minecraft.gardenstuff.block.tile.TileEntityLantern; import com.jaquadro.minecraft.gardenstuff.core.ClientProxy; import com.jaquadro.minecraft.gardenstuff.core.ModBlocks; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection;
14,492
package com.jaquadro.minecraft.gardenstuff.renderer; public class LanternRenderer implements ISimpleBlockRenderingHandler { public int renderPass = 0; private float[] colorScratch = new float[3]; private static final Vec3 defaultAttachPoint = Vec3.createVectorHelper(0.5D, 0.0D, 0.5D); public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { } public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { return !(block instanceof BlockLantern) ? false : this.renderWorldBlock(world, x, y, z, (BlockLantern)block, modelId, renderer); } private boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, BlockLantern block, int modelId, RenderBlocks renderer) { TileEntityLantern tile; if (this.renderPass == 0) { renderer.setRenderBoundsFromBlock(block); renderer.renderStandardBlock(block, x, y, z); renderer.renderFromInside = true; renderer.renderMinY = 0.004999999888241291D; renderer.renderStandardBlock(block, x, y, z); renderer.renderFromInside = false; renderer.overrideBlockTexture = block.getIconTopCross(); renderer.renderCrossedSquares(block, x, y, z); renderer.overrideBlockTexture = null; tile = block.getTileEntity(world, x, y, z); if (tile != null) { BindingStack binding = GardenStuff.proxy.getClientBindingStack(block); binding.setDefaultMeta(world.getBlockMetadata(x, y, z)); binding.bind(tile.getWorldObj(), x, y, z, 0, tile.getLightSourceMeta()); Tessellator.instance.addTranslation(0.0F, 0.001F, 0.0F); if (tile.getLightSource() != null) {
package com.jaquadro.minecraft.gardenstuff.renderer; public class LanternRenderer implements ISimpleBlockRenderingHandler { public int renderPass = 0; private float[] colorScratch = new float[3]; private static final Vec3 defaultAttachPoint = Vec3.createVectorHelper(0.5D, 0.0D, 0.5D); public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { } public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { return !(block instanceof BlockLantern) ? false : this.renderWorldBlock(world, x, y, z, (BlockLantern)block, modelId, renderer); } private boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, BlockLantern block, int modelId, RenderBlocks renderer) { TileEntityLantern tile; if (this.renderPass == 0) { renderer.setRenderBoundsFromBlock(block); renderer.renderStandardBlock(block, x, y, z); renderer.renderFromInside = true; renderer.renderMinY = 0.004999999888241291D; renderer.renderStandardBlock(block, x, y, z); renderer.renderFromInside = false; renderer.overrideBlockTexture = block.getIconTopCross(); renderer.renderCrossedSquares(block, x, y, z); renderer.overrideBlockTexture = null; tile = block.getTileEntity(world, x, y, z); if (tile != null) { BindingStack binding = GardenStuff.proxy.getClientBindingStack(block); binding.setDefaultMeta(world.getBlockMetadata(x, y, z)); binding.bind(tile.getWorldObj(), x, y, z, 0, tile.getLightSourceMeta()); Tessellator.instance.addTranslation(0.0F, 0.001F, 0.0F); if (tile.getLightSource() != null) {
ILanternSource lanternSource = Api.instance.registries().lanternSources().getLanternSource(tile.getLightSource());
1
2023-12-12 08:13:16+00:00
24k
muchfish/ruoyi-vue-pro-sample
yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java
[ { "identifier": "CommonStatusEnum", "path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/enums/CommonStatusEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum CommonStatusEnum implements IntArrayValuable {\n\n ENABLE(0, \"开启\"),\n DISABLE(1, \"关闭\");\...
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.tenant.config.TenantProperties; import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantPageReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantUpdateReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO; import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO; import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantPackageDO; import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantMapper; import cn.iocoder.yudao.module.system.enums.permission.RoleCodeEnum; import cn.iocoder.yudao.module.system.enums.permission.RoleTypeEnum; import cn.iocoder.yudao.module.system.service.permission.MenuService; import cn.iocoder.yudao.module.system.service.permission.PermissionService; import cn.iocoder.yudao.module.system.service.permission.RoleService; import cn.iocoder.yudao.module.system.service.tenant.handler.TenantInfoHandler; import cn.iocoder.yudao.module.system.service.tenant.handler.TenantMenuHandler; import cn.iocoder.yudao.module.system.service.user.AdminUserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO.PACKAGE_ID_SYSTEM; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*;
16,530
package cn.iocoder.yudao.module.system.service.tenant; /** * {@link TenantServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(TenantServiceImpl.class) public class TenantServiceImplTest extends BaseDbUnitTest { @Resource private TenantServiceImpl tenantService; @Resource private TenantMapper tenantMapper; @MockBean private TenantProperties tenantProperties; @MockBean private TenantPackageService tenantPackageService; @MockBean private AdminUserService userService; @MockBean private RoleService roleService; @MockBean private MenuService menuService; @MockBean private PermissionService permissionService; @BeforeEach public void setUp() { // 清理租户上下文 TenantContextHolder.clear(); } @Test public void testGetTenantIdList() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L)); tenantMapper.insert(tenant); // 调用,并断言业务异常 List<Long> result = tenantService.getTenantIdList(); assertEquals(Collections.singletonList(1L), result); } @Test public void testValidTenant_notExists() { assertServiceException(() -> tenantService.validTenant(randomLongId()), TENANT_NOT_EXISTS); } @Test public void testValidTenant_disable() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.DISABLE.getStatus())); tenantMapper.insert(tenant); // 调用,并断言业务异常 assertServiceException(() -> tenantService.validTenant(1L), TENANT_DISABLE, tenant.getName()); } @Test public void testValidTenant_expired() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus()) .setExpireTime(buildTime(2020, 2, 2))); tenantMapper.insert(tenant); // 调用,并断言业务异常 assertServiceException(() -> tenantService.validTenant(1L), TENANT_EXPIRE, tenant.getName()); } @Test public void testValidTenant_success() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus()) .setExpireTime(LocalDateTime.now().plusDays(1))); tenantMapper.insert(tenant); // 调用,并断言业务异常 tenantService.validTenant(1L); } @Test public void testCreateTenant() { // mock 套餐 100L TenantPackageDO tenantPackage = randomPojo(TenantPackageDO.class, o -> o.setId(100L)); when(tenantPackageService.validTenantPackage(eq(100L))).thenReturn(tenantPackage); // mock 角色 200L when(roleService.createRole(argThat(role -> {
package cn.iocoder.yudao.module.system.service.tenant; /** * {@link TenantServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(TenantServiceImpl.class) public class TenantServiceImplTest extends BaseDbUnitTest { @Resource private TenantServiceImpl tenantService; @Resource private TenantMapper tenantMapper; @MockBean private TenantProperties tenantProperties; @MockBean private TenantPackageService tenantPackageService; @MockBean private AdminUserService userService; @MockBean private RoleService roleService; @MockBean private MenuService menuService; @MockBean private PermissionService permissionService; @BeforeEach public void setUp() { // 清理租户上下文 TenantContextHolder.clear(); } @Test public void testGetTenantIdList() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L)); tenantMapper.insert(tenant); // 调用,并断言业务异常 List<Long> result = tenantService.getTenantIdList(); assertEquals(Collections.singletonList(1L), result); } @Test public void testValidTenant_notExists() { assertServiceException(() -> tenantService.validTenant(randomLongId()), TENANT_NOT_EXISTS); } @Test public void testValidTenant_disable() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.DISABLE.getStatus())); tenantMapper.insert(tenant); // 调用,并断言业务异常 assertServiceException(() -> tenantService.validTenant(1L), TENANT_DISABLE, tenant.getName()); } @Test public void testValidTenant_expired() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus()) .setExpireTime(buildTime(2020, 2, 2))); tenantMapper.insert(tenant); // 调用,并断言业务异常 assertServiceException(() -> tenantService.validTenant(1L), TENANT_EXPIRE, tenant.getName()); } @Test public void testValidTenant_success() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus()) .setExpireTime(LocalDateTime.now().plusDays(1))); tenantMapper.insert(tenant); // 调用,并断言业务异常 tenantService.validTenant(1L); } @Test public void testCreateTenant() { // mock 套餐 100L TenantPackageDO tenantPackage = randomPojo(TenantPackageDO.class, o -> o.setId(100L)); when(tenantPackageService.validTenantPackage(eq(100L))).thenReturn(tenantPackage); // mock 角色 200L when(roleService.createRole(argThat(role -> {
assertEquals(RoleCodeEnum.TENANT_ADMIN.getName(), role.getName());
14
2023-12-08 02:48:42+00:00
24k
mklemmingen/senet-boom
core/src/com/senetboom/game/backend/Stick.java
[ { "identifier": "SenetBoom", "path": "core/src/com/senetboom/game/SenetBoom.java", "snippet": "public class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTextur...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.scenes.scene2d.Actor; import com.senetboom.game.SenetBoom; import static com.senetboom.game.SenetBoom.*;
15,293
package com.senetboom.game.backend; public class Stick { private StickRoll[] stickRolls; private int stickValue; private static float maxTime = 1.5f; private static float elapsedTime = 0; // every time a new Stick is created, we need to create a new RollingSticks actor and add it to the stage // also save the value of the stick in the stickValue variable public Stick() { // rolling Sticks this.stickRolls = new StickRoll[4]; this.stickValue = 0; for (int i = 0; i < 4; i++) { this.stickRolls[i] = new StickRoll(); this.stickValue += this.stickRolls[i].getStickRoll(); } if(stickValue == 0){ // 4 blacks equal value 6 stickValue = 6; } // create RollingsSticks actor and add to stage RollingSticks rollingSticks = new RollingSticks();
package com.senetboom.game.backend; public class Stick { private StickRoll[] stickRolls; private int stickValue; private static float maxTime = 1.5f; private static float elapsedTime = 0; // every time a new Stick is created, we need to create a new RollingSticks actor and add it to the stage // also save the value of the stick in the stickValue variable public Stick() { // rolling Sticks this.stickRolls = new StickRoll[4]; this.stickValue = 0; for (int i = 0; i < 4; i++) { this.stickRolls[i] = new StickRoll(); this.stickValue += this.stickRolls[i].getStickRoll(); } if(stickValue == 0){ // 4 blacks equal value 6 stickValue = 6; } // create RollingsSticks actor and add to stage RollingSticks rollingSticks = new RollingSticks();
SenetBoom.stickStage.addActor(rollingSticks);
1
2023-12-05 22:19:00+00:00
24k
sinbad-navigator/erp-crm
system/src/main/java/com/ec/sys/service/impl/SysMenuServiceImpl.java
[ { "identifier": "Constants", "path": "common/src/main/java/com/ec/common/constant/Constants.java", "snippet": "public class Constants {\n /**\n * UTF-8 字符集\n */\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n public static final String GBK = \"GBK\";...
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ec.common.constant.Constants; import com.ec.common.constant.UserConstants; import com.ec.common.core.domain.TreeSelect; import com.ec.common.core.domain.entity.SysMenu; import com.ec.common.core.domain.entity.SysRole; import com.ec.common.core.domain.entity.SysUser; import com.ec.common.utils.SecurityUtils; import com.ec.common.utils.StringUtils; import com.ec.sys.domain.vo.MetaVo; import com.ec.sys.domain.vo.RouterVo; import com.ec.sys.mapper.SysMenuMapper; import com.ec.sys.mapper.SysRoleMapper; import com.ec.sys.mapper.SysRoleMenuMapper; import com.ec.sys.service.ISysMenuService;
16,273
package com.ec.sys.service.impl; /** * 菜单 业务层处理 * * @author ec */ @Service public class SysMenuServiceImpl implements ISysMenuService { public static final String PREMISSION_STRING = "perms[\"{0}\"]"; @Autowired private SysMenuMapper menuMapper; @Autowired private SysRoleMapper roleMapper; @Autowired private SysRoleMenuMapper roleMenuMapper; /** * 根据用户查询系统菜单列表 * * @param userId 用户ID * @return 菜单列表 */ @Override public List<SysMenu> selectMenuList(Long userId) { return selectMenuList(new SysMenu(), userId); } /** * 查询系统菜单列表 * * @param menu 菜单信息 * @return 菜单列表 */ @Override public List<SysMenu> selectMenuList(SysMenu menu, Long userId) { List<SysMenu> menuList = null; // 管理员显示所有菜单信息 if (SysUser.isAdmin(userId)) { menuList = menuMapper.selectMenuList(menu); } else { menu.getParams().put("userId", userId); menuList = menuMapper.selectMenuListByUserId(menu); } return menuList; } /** * 根据用户ID查询权限 * * @param userId 用户ID * @return 权限列表 */ @Override public Set<String> selectMenuPermsByUserId(Long userId) { List<String> perms = menuMapper.selectMenuPermsByUserId(userId); Set<String> permsSet = new HashSet<>(); for (String perm : perms) { if (StringUtils.isNotEmpty(perm)) { permsSet.addAll(Arrays.asList(perm.trim().split(","))); } } return permsSet; } /** * 根据用户ID查询菜单 * * @param userId 用户名称 * @return 菜单列表 */ @Override public List<SysMenu> selectMenuTreeByUserId(Long userId) { List<SysMenu> menus = null; if (SecurityUtils.isAdmin(userId)) { menus = menuMapper.selectMenuTreeAll(); } else { menus = menuMapper.selectMenuTreeByUserId(userId); } return getChildPerms(menus, 0); } /** * 根据角色ID查询菜单树信息 * * @param roleId 角色ID * @return 选中菜单列表 */ @Override public List<Long> selectMenuListByRoleId(Long roleId) { SysRole role = roleMapper.selectRoleById(roleId); return menuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly()); } /** * 构建前端路由所需要的菜单 * * @param menus 菜单列表 * @return 路由列表 */ @Override
package com.ec.sys.service.impl; /** * 菜单 业务层处理 * * @author ec */ @Service public class SysMenuServiceImpl implements ISysMenuService { public static final String PREMISSION_STRING = "perms[\"{0}\"]"; @Autowired private SysMenuMapper menuMapper; @Autowired private SysRoleMapper roleMapper; @Autowired private SysRoleMenuMapper roleMenuMapper; /** * 根据用户查询系统菜单列表 * * @param userId 用户ID * @return 菜单列表 */ @Override public List<SysMenu> selectMenuList(Long userId) { return selectMenuList(new SysMenu(), userId); } /** * 查询系统菜单列表 * * @param menu 菜单信息 * @return 菜单列表 */ @Override public List<SysMenu> selectMenuList(SysMenu menu, Long userId) { List<SysMenu> menuList = null; // 管理员显示所有菜单信息 if (SysUser.isAdmin(userId)) { menuList = menuMapper.selectMenuList(menu); } else { menu.getParams().put("userId", userId); menuList = menuMapper.selectMenuListByUserId(menu); } return menuList; } /** * 根据用户ID查询权限 * * @param userId 用户ID * @return 权限列表 */ @Override public Set<String> selectMenuPermsByUserId(Long userId) { List<String> perms = menuMapper.selectMenuPermsByUserId(userId); Set<String> permsSet = new HashSet<>(); for (String perm : perms) { if (StringUtils.isNotEmpty(perm)) { permsSet.addAll(Arrays.asList(perm.trim().split(","))); } } return permsSet; } /** * 根据用户ID查询菜单 * * @param userId 用户名称 * @return 菜单列表 */ @Override public List<SysMenu> selectMenuTreeByUserId(Long userId) { List<SysMenu> menus = null; if (SecurityUtils.isAdmin(userId)) { menus = menuMapper.selectMenuTreeAll(); } else { menus = menuMapper.selectMenuTreeByUserId(userId); } return getChildPerms(menus, 0); } /** * 根据角色ID查询菜单树信息 * * @param roleId 角色ID * @return 选中菜单列表 */ @Override public List<Long> selectMenuListByRoleId(Long roleId) { SysRole role = roleMapper.selectRoleById(roleId); return menuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly()); } /** * 构建前端路由所需要的菜单 * * @param menus 菜单列表 * @return 路由列表 */ @Override
public List<RouterVo> buildMenus(List<SysMenu> menus) {
9
2023-12-07 14:23:12+00:00
24k
Crydsch/the-one
src/report/NodeDensityReport.java
[ { "identifier": "Coord", "path": "src/core/Coord.java", "snippet": "public class Coord implements Cloneable, Comparable<Coord> {\n\tprivate double x;\n\tprivate double y;\n\n\t/**\n\t * Constructor.\n\t * @param x Initial X-coordinate\n\t * @param y Initial Y-coordinate\n\t */\n\tpublic Coord(double x, ...
import core.Coord; import core.DTNHost; import core.Settings; import core.SettingsError; import core.SimScenario; import java.util.ArrayList; import java.util.List;
18,070
package report; /** * <p>Sampling report that counts the number of nodes in grid over the * simulation area. Output format is: G_x G_y average count_1, count_2, ... * Where G_x and G_y are the coordinates of the grid square [0, 1, ...] and * count_n is the count during the nth sample. * * <p>The report can be configured to output a gnuplot script file that * produces a heat map graph of the node densities. * * @author teemuk */ public class NodeDensityReport extends SamplingReport { //========================================================================// // Settings //========================================================================// /** Number of divisions along the x-axis ({@value}). */ public static final String X_COUNT_SETTING = "xCount"; /** Number of divisions along the y-axis ({@value}). */ public static final String Y_COUNT_SETTING = "yCount"; /** Boolean setting to output gnuplot file ({@value}). */ public static final String GNUPLOT_SETTING = "outputGnuplot"; /** Setting for gnuplot terminal, i.e., terminal set X ({@value}). */ public static final String GNUPLOT_TERMINAL_SETTING = "gnuplotTerminal"; /** Setting for file extension for files generated by gnuplot ({@value}). */ public static final String GNUPLOT_FILE_EXTENSION_SETTING = "gnuplotFileExtension"; /** Boolean setting to output only the average ({@value}). */ public static final String ONLY_AVERAGE_SETTING = "onlyAverage"; /** Default number of divisions along the x-axis ({@value}). */ public static final int DEFAULT_X_COUNT = 10; /** Default number of divisions along the y-axis ({@value}). */ public static final int DEFAULT_Y_COUNT = 10; /** Default value for outputting gnuplot instead of raw data ({@value}). */ public static final boolean DEFAULT_GNUPLOT = false; /** Default value for gnuplot terminal ({@value}). */ public static final String DEFAULT_GNUPLOT_TERMINAL = "png size 1024,768"; public static final String DEFAULT_GNUPLOT_FILE_EXTENSION = "png"; /** Default value for outputting only the average density ({@value}). */ public static final boolean DEFAULT_ONLY_AVERAGE = false; //========================================================================// //========================================================================// // Instance vars //========================================================================// private final int horizontalCount; private final int verticalCount; private final double divisionWidth; private final double divisionHeight; private final boolean gnuplot; private final String gnuplotTerminal; private final String gnuplotFileExtension; private final boolean onlyAverage; private final String runName; private final List<int[][]> samples; //========================================================================// //========================================================================// // Constructor //========================================================================// public NodeDensityReport() { super(); final Settings settings = super.getSettings(); this.gnuplot = settings.getBoolean(GNUPLOT_SETTING, DEFAULT_GNUPLOT); this.onlyAverage = settings.getBoolean(ONLY_AVERAGE_SETTING, DEFAULT_ONLY_AVERAGE); this.gnuplotTerminal = settings.getSetting(GNUPLOT_TERMINAL_SETTING, DEFAULT_GNUPLOT_TERMINAL); this.gnuplotFileExtension = settings.getSetting( GNUPLOT_FILE_EXTENSION_SETTING, DEFAULT_GNUPLOT_FILE_EXTENSION); // Set up the sampling grid this.horizontalCount = settings.getInt(X_COUNT_SETTING, DEFAULT_X_COUNT); this.verticalCount = settings.getInt(Y_COUNT_SETTING, DEFAULT_Y_COUNT); if (this.horizontalCount <= 0 || this.verticalCount <= 0) { throw new SettingsError("Settings '" + X_COUNT_SETTING + "' and '" + Y_COUNT_SETTING + "' must be positive. Found " + this.horizontalCount + ", " + this.verticalCount + "."); } final SimScenario scenario = SimScenario.getInstance(); final int worldWidth = scenario.getWorldSizeX(); final int worldHeight = scenario.getWorldSizeY(); this.divisionWidth = 1.0 * worldWidth / this.horizontalCount; this.divisionHeight = 1.0 * worldHeight / this.verticalCount; final double duration = scenario.getEndTime(); final int sampleCount = (int) (duration / super.interval + 1); this.samples = new ArrayList<int[][]>(sampleCount); this.runName = scenario.getName(); } //========================================================================// //========================================================================// // SamplingReport //========================================================================// @Override
package report; /** * <p>Sampling report that counts the number of nodes in grid over the * simulation area. Output format is: G_x G_y average count_1, count_2, ... * Where G_x and G_y are the coordinates of the grid square [0, 1, ...] and * count_n is the count during the nth sample. * * <p>The report can be configured to output a gnuplot script file that * produces a heat map graph of the node densities. * * @author teemuk */ public class NodeDensityReport extends SamplingReport { //========================================================================// // Settings //========================================================================// /** Number of divisions along the x-axis ({@value}). */ public static final String X_COUNT_SETTING = "xCount"; /** Number of divisions along the y-axis ({@value}). */ public static final String Y_COUNT_SETTING = "yCount"; /** Boolean setting to output gnuplot file ({@value}). */ public static final String GNUPLOT_SETTING = "outputGnuplot"; /** Setting for gnuplot terminal, i.e., terminal set X ({@value}). */ public static final String GNUPLOT_TERMINAL_SETTING = "gnuplotTerminal"; /** Setting for file extension for files generated by gnuplot ({@value}). */ public static final String GNUPLOT_FILE_EXTENSION_SETTING = "gnuplotFileExtension"; /** Boolean setting to output only the average ({@value}). */ public static final String ONLY_AVERAGE_SETTING = "onlyAverage"; /** Default number of divisions along the x-axis ({@value}). */ public static final int DEFAULT_X_COUNT = 10; /** Default number of divisions along the y-axis ({@value}). */ public static final int DEFAULT_Y_COUNT = 10; /** Default value for outputting gnuplot instead of raw data ({@value}). */ public static final boolean DEFAULT_GNUPLOT = false; /** Default value for gnuplot terminal ({@value}). */ public static final String DEFAULT_GNUPLOT_TERMINAL = "png size 1024,768"; public static final String DEFAULT_GNUPLOT_FILE_EXTENSION = "png"; /** Default value for outputting only the average density ({@value}). */ public static final boolean DEFAULT_ONLY_AVERAGE = false; //========================================================================// //========================================================================// // Instance vars //========================================================================// private final int horizontalCount; private final int verticalCount; private final double divisionWidth; private final double divisionHeight; private final boolean gnuplot; private final String gnuplotTerminal; private final String gnuplotFileExtension; private final boolean onlyAverage; private final String runName; private final List<int[][]> samples; //========================================================================// //========================================================================// // Constructor //========================================================================// public NodeDensityReport() { super(); final Settings settings = super.getSettings(); this.gnuplot = settings.getBoolean(GNUPLOT_SETTING, DEFAULT_GNUPLOT); this.onlyAverage = settings.getBoolean(ONLY_AVERAGE_SETTING, DEFAULT_ONLY_AVERAGE); this.gnuplotTerminal = settings.getSetting(GNUPLOT_TERMINAL_SETTING, DEFAULT_GNUPLOT_TERMINAL); this.gnuplotFileExtension = settings.getSetting( GNUPLOT_FILE_EXTENSION_SETTING, DEFAULT_GNUPLOT_FILE_EXTENSION); // Set up the sampling grid this.horizontalCount = settings.getInt(X_COUNT_SETTING, DEFAULT_X_COUNT); this.verticalCount = settings.getInt(Y_COUNT_SETTING, DEFAULT_Y_COUNT); if (this.horizontalCount <= 0 || this.verticalCount <= 0) { throw new SettingsError("Settings '" + X_COUNT_SETTING + "' and '" + Y_COUNT_SETTING + "' must be positive. Found " + this.horizontalCount + ", " + this.verticalCount + "."); } final SimScenario scenario = SimScenario.getInstance(); final int worldWidth = scenario.getWorldSizeX(); final int worldHeight = scenario.getWorldSizeY(); this.divisionWidth = 1.0 * worldWidth / this.horizontalCount; this.divisionHeight = 1.0 * worldHeight / this.verticalCount; final double duration = scenario.getEndTime(); final int sampleCount = (int) (duration / super.interval + 1); this.samples = new ArrayList<int[][]>(sampleCount); this.runName = scenario.getName(); } //========================================================================// //========================================================================// // SamplingReport //========================================================================// @Override
protected void sample(final List<DTNHost> hosts) {
1
2023-12-10 15:51:41+00:00
24k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.java
[ { "identifier": "DialogHelper", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/DialogHelper.java", "snippet": "public class DialogHelper {\n\n\tpublic static int savedDialog = DialogHelper.DIALOG_NONE;\n\n\tpublic final static int DIALOG_NONE = -1;\n\tpublic final static in...
import android.content.Intent; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Style; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.util.Size; import android.view.View; import android.widget.Toast; import com.seleuco.mame4droid.helpers.DialogHelper; import com.seleuco.mame4droid.helpers.PrefsHelper; import com.seleuco.mame4droid.helpers.SAFHelper; import com.seleuco.mame4droid.input.TouchController; import com.seleuco.mame4droid.views.EmulatorViewGL; import java.io.File; import java.nio.ByteBuffer;
20,697
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * 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 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 * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid; public class Emulator { //gets final static public int IN_MENU = 1; final static public int IN_GAME = 2; final static public int NUMBTNS = 3; final static public int NUMWAYS = 4; final static public int IS_LIGHTGUN = 5; //sets final static public int EXIT_GAME = 1; final static public int EXIT_PAUSE = 2; final static public int SHOW_FPS = 3; final static public int AUTO_FRAMESKIP = 4; final static public int CHEATS = 5; final static public int SKIP_GAMEINFO = 6; final static public int DISABLE_DRC = 7; final static public int DRC_USE_C = 8; final static public int SIMPLE_UI = 9; final static public int PAUSE = 11; final static public int SOUND_VALUE = 13; final static public int AUTOSAVE = 16; final static public int SAVESTATE = 17; final static public int LOADSTATE = 18; final static public int OSD_RESOLUTION = 20; final static public int EMU_RESOLUTION = 21; final static public int ZOOM_TO_WINDOW = 22; final static public int DOUBLE_BUFFER = 23; final static public int PXASP1 = 24; final static public int VBEAM2X = 34; final static public int VFLICKER = 36; final static public int SOUND_OPTIMAL_FRAMES = 48; final static public int SOUND_OPTIMAL_SAMPLERATE = 49; final static public int SOUND_ENGINE = 50; final static public int MOUSE = 60; final static public int REFRESH = 61; final static public int USING_SAF = 62; final static public int SAVESATES_IN_ROM_PATH = 63; final static public int WARN_ON_EXIT = 64; final static public int IS_MOUSE = 65; final static public int KEYBOARD = 66; final static public int ONE_PROCESSOR = 67; final static public int NODEADZONEANDSAT = 68; final static public int MAMEINI = 69; //set str final static public int SAF_PATH = 1; final static public int ROM_NAME = 2; final static public int VERSION = 3; final static public int OVERLAY_EFECT = 4; //get str final static public int MAME_VERSION = 1; //KEYS ACTIONS final static public int KEY_DOWN = 1; final static public int KEY_UP = 2; //MOUSE ACTIONS final static public int MOUSE_MOVE = 1; final static public int MOUSE_BTN_DOWN = 2; final static public int MOUSE_BTN_UP = 3; private static MAME4droid mm = null; private static boolean isEmulating = false; public static boolean isEmulating() { return isEmulating; } private static Object lock1 = new Object(); private static ByteBuffer screenBuff = null; private static boolean emuFiltering = false; public static boolean isEmuFiltering() { return emuFiltering; } public static void setEmuFiltering(boolean value) { emuFiltering = value; } private static Paint debugPaint = new Paint(); private static Matrix mtx = new Matrix(); private static int window_width = 320; public static int getWindow_width() { return window_width; } private static int window_height = 240; public static int getWindow_height() { return window_height; } private static int emu_width = 320; private static int emu_height = 240; private static AudioTrack audioTrack = null; private static boolean isDebug = false;
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * 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 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 * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid; public class Emulator { //gets final static public int IN_MENU = 1; final static public int IN_GAME = 2; final static public int NUMBTNS = 3; final static public int NUMWAYS = 4; final static public int IS_LIGHTGUN = 5; //sets final static public int EXIT_GAME = 1; final static public int EXIT_PAUSE = 2; final static public int SHOW_FPS = 3; final static public int AUTO_FRAMESKIP = 4; final static public int CHEATS = 5; final static public int SKIP_GAMEINFO = 6; final static public int DISABLE_DRC = 7; final static public int DRC_USE_C = 8; final static public int SIMPLE_UI = 9; final static public int PAUSE = 11; final static public int SOUND_VALUE = 13; final static public int AUTOSAVE = 16; final static public int SAVESTATE = 17; final static public int LOADSTATE = 18; final static public int OSD_RESOLUTION = 20; final static public int EMU_RESOLUTION = 21; final static public int ZOOM_TO_WINDOW = 22; final static public int DOUBLE_BUFFER = 23; final static public int PXASP1 = 24; final static public int VBEAM2X = 34; final static public int VFLICKER = 36; final static public int SOUND_OPTIMAL_FRAMES = 48; final static public int SOUND_OPTIMAL_SAMPLERATE = 49; final static public int SOUND_ENGINE = 50; final static public int MOUSE = 60; final static public int REFRESH = 61; final static public int USING_SAF = 62; final static public int SAVESATES_IN_ROM_PATH = 63; final static public int WARN_ON_EXIT = 64; final static public int IS_MOUSE = 65; final static public int KEYBOARD = 66; final static public int ONE_PROCESSOR = 67; final static public int NODEADZONEANDSAT = 68; final static public int MAMEINI = 69; //set str final static public int SAF_PATH = 1; final static public int ROM_NAME = 2; final static public int VERSION = 3; final static public int OVERLAY_EFECT = 4; //get str final static public int MAME_VERSION = 1; //KEYS ACTIONS final static public int KEY_DOWN = 1; final static public int KEY_UP = 2; //MOUSE ACTIONS final static public int MOUSE_MOVE = 1; final static public int MOUSE_BTN_DOWN = 2; final static public int MOUSE_BTN_UP = 3; private static MAME4droid mm = null; private static boolean isEmulating = false; public static boolean isEmulating() { return isEmulating; } private static Object lock1 = new Object(); private static ByteBuffer screenBuff = null; private static boolean emuFiltering = false; public static boolean isEmuFiltering() { return emuFiltering; } public static void setEmuFiltering(boolean value) { emuFiltering = value; } private static Paint debugPaint = new Paint(); private static Matrix mtx = new Matrix(); private static int window_width = 320; public static int getWindow_width() { return window_width; } private static int window_height = 240; public static int getWindow_height() { return window_height; } private static int emu_width = 320; private static int emu_height = 240; private static AudioTrack audioTrack = null; private static boolean isDebug = false;
private static int videoRenderMode = PrefsHelper.PREF_RENDER_GL;
1
2023-12-18 11:16:18+00:00
24k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/gui/inventory/inventories/sbmenu/GUICrafting.java
[ { "identifier": "SkyBlockEvent", "path": "generic/src/main/java/net/swofty/types/generic/event/SkyBlockEvent.java", "snippet": "public abstract class SkyBlockEvent {\n private static final HashMap<EventNode<? extends Event>, ArrayList<SkyBlockEvent>> cachedEvents = new HashMap<>();\n private stati...
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextDecoration; import net.minestom.server.event.inventory.InventoryCloseEvent; import net.minestom.server.event.inventory.InventoryPreClickEvent; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; import net.minestom.server.inventory.click.ClickType; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.swofty.types.generic.event.SkyBlockEvent; import net.swofty.types.generic.event.custom.ItemCraftEvent; import net.swofty.types.generic.gui.inventory.ItemStackCreator; import net.swofty.types.generic.gui.inventory.RefreshingGUI; import net.swofty.types.generic.gui.inventory.SkyBlockInventoryGUI; import net.swofty.types.generic.gui.inventory.item.GUIClickableItem; import net.swofty.types.generic.item.ItemType; import net.swofty.types.generic.item.SkyBlockItem; import net.swofty.types.generic.item.impl.SkyBlockRecipe; import net.swofty.types.generic.item.impl.recipes.ShapedRecipe; import net.swofty.types.generic.item.updater.PlayerItemUpdater; import net.swofty.types.generic.user.SkyBlockPlayer; import net.swofty.types.generic.utility.StringUtility; import org.tinylog.Logger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors;
19,974
package net.swofty.types.generic.gui.inventory.inventories.sbmenu; public class GUICrafting extends SkyBlockInventoryGUI implements RefreshingGUI { private static final ItemStack.Builder RECIPE_REQUIRED = ItemStackCreator.getStack("§cRecipe Required", Material.BARRIER, (short) 0, 1, "§7Add the items for a valid recipe in", "§7the crafting grid to the left!"); private static final int[] CRAFT_SLOTS = new int[]{10, 11, 12, 19, 20, 21, 28, 29, 30}; private static final int RESULT_SLOT = 24; public GUICrafting() { super("Craft Item", InventoryType.CHEST_6_ROW); } @Override public void onOpen(InventoryGUIOpenEvent e) { fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE), 13, 34); border(ItemStackCreator.createNamedItemStack(Material.RED_STAINED_GLASS_PANE)); border(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE), 0, 44); set(GUIClickableItem.getCloseItem(49)); set(RESULT_SLOT, RECIPE_REQUIRED); } @Override public boolean allowHotkeying() { return true; } @Override public void onClose(InventoryCloseEvent e, CloseReason reason) { Arrays.stream(CRAFT_SLOTS).forEach(slot -> { ((SkyBlockPlayer) e.getPlayer()).addAndUpdateItem(new SkyBlockItem(e.getInventory().getItemStack(slot))); }); } @Override public void suddenlyQuit(Inventory inventory, SkyBlockPlayer player) { Arrays.stream(CRAFT_SLOTS).forEach(slot -> { player.addAndUpdateItem(new SkyBlockItem(inventory.getItemStack(slot))); }); } @Override public void onBottomClick(InventoryPreClickEvent e) { } @Override public void refreshItems(SkyBlockPlayer player) { Inventory inventory = getInventory();
package net.swofty.types.generic.gui.inventory.inventories.sbmenu; public class GUICrafting extends SkyBlockInventoryGUI implements RefreshingGUI { private static final ItemStack.Builder RECIPE_REQUIRED = ItemStackCreator.getStack("§cRecipe Required", Material.BARRIER, (short) 0, 1, "§7Add the items for a valid recipe in", "§7the crafting grid to the left!"); private static final int[] CRAFT_SLOTS = new int[]{10, 11, 12, 19, 20, 21, 28, 29, 30}; private static final int RESULT_SLOT = 24; public GUICrafting() { super("Craft Item", InventoryType.CHEST_6_ROW); } @Override public void onOpen(InventoryGUIOpenEvent e) { fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE), 13, 34); border(ItemStackCreator.createNamedItemStack(Material.RED_STAINED_GLASS_PANE)); border(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE), 0, 44); set(GUIClickableItem.getCloseItem(49)); set(RESULT_SLOT, RECIPE_REQUIRED); } @Override public boolean allowHotkeying() { return true; } @Override public void onClose(InventoryCloseEvent e, CloseReason reason) { Arrays.stream(CRAFT_SLOTS).forEach(slot -> { ((SkyBlockPlayer) e.getPlayer()).addAndUpdateItem(new SkyBlockItem(e.getInventory().getItemStack(slot))); }); } @Override public void suddenlyQuit(Inventory inventory, SkyBlockPlayer player) { Arrays.stream(CRAFT_SLOTS).forEach(slot -> { player.addAndUpdateItem(new SkyBlockItem(inventory.getItemStack(slot))); }); } @Override public void onBottomClick(InventoryPreClickEvent e) { } @Override public void refreshItems(SkyBlockPlayer player) { Inventory inventory = getInventory();
SkyBlockRecipe<?> recipe = SkyBlockRecipe.parseRecipe(getCurrentRecipe(inventory));
8
2023-12-14 09:51:15+00:00
24k
Tianscar/uxgl
desktop/src/main/java/unrefined/runtime/DesktopBrush.java
[ { "identifier": "BiRadialGradientPaint", "path": "desktop/src/main/java/unrefined/desktop/BiRadialGradientPaint.java", "snippet": "public class BiRadialGradientPaint implements Paint {\n\n private final int transparency;\n\n /** Gradient keyframe values in the range 0 to 1. */\n private final f...
import unrefined.desktop.BiRadialGradientPaint; import unrefined.desktop.TransformedTexturePaint; import unrefined.media.graphics.Brush; import java.awt.Color; import java.awt.LinearGradientPaint; import java.awt.Paint; import java.util.Objects;
20,188
package unrefined.runtime; public class DesktopBrush extends Brush { private final Paint paint; private final int type; public DesktopBrush(Paint paint) { this.paint = paint == null ? Color.BLACK : paint; if (this.paint instanceof Color) this.type = Type.COLOR; else if (this.paint instanceof LinearGradientPaint) this.type = Type.LINEAR_GRADIENT; else if (this.paint instanceof BiRadialGradientPaint) this.type = Type.RADIAL_GRADIENT;
package unrefined.runtime; public class DesktopBrush extends Brush { private final Paint paint; private final int type; public DesktopBrush(Paint paint) { this.paint = paint == null ? Color.BLACK : paint; if (this.paint instanceof Color) this.type = Type.COLOR; else if (this.paint instanceof LinearGradientPaint) this.type = Type.LINEAR_GRADIENT; else if (this.paint instanceof BiRadialGradientPaint) this.type = Type.RADIAL_GRADIENT;
else if (this.paint instanceof TransformedTexturePaint) this.type = Type.BITMAP_PATTERN;
1
2023-12-15 19:03:31+00:00
24k