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
codingmiao/hppt
ss/src/main/java/org/wowtools/hppt/ss/servlet/TalkServlet.java
[ { "identifier": "ProtoMessage", "path": "common/src/main/java/org/wowtools/hppt/common/protobuf/ProtoMessage.java", "snippet": "public final class ProtoMessage {\n private ProtoMessage() {}\n public static void registerAllExtensions(\n com.google.protobuf.ExtensionRegistryLite registry) {\n }\n\...
import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.wowtools.hppt.common.protobuf.ProtoMessage; import org.wowtools.hppt.common.util.BytesUtil; import org.wowtools.hppt.ss.StartSs; import org.wowtools.hppt.ss.service.ClientService; import org.wowtools.hppt.ss.service.ServerSessionService; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
17,082
package org.wowtools.hppt.ss.servlet; /** * @author liuyu * @date 2023/11/5 */ @Slf4j public class TalkServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String loginCode = req.getParameter("c"); loginCode = loginCode.replace(" ", "+");
package org.wowtools.hppt.ss.servlet; /** * @author liuyu * @date 2023/11/5 */ @Slf4j public class TalkServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String loginCode = req.getParameter("c"); loginCode = loginCode.replace(" ", "+");
ClientService.Client client = ClientService.getClient(loginCode);
3
2023-12-22 14:14:27+00:00
24k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/modules/combat/Bomber.java
[ { "identifier": "Phobot", "path": "src/main/java/me/earth/phobot/Phobot.java", "snippet": "@Getter\n@RequiredArgsConstructor\n@SuppressWarnings(\"ClassCanBeRecord\")\npublic class Phobot {\n public static final String NAME = \"Phobot\";\n\n private final PingBypass pingBypass;\n private final E...
import lombok.Getter; import lombok.extern.slf4j.Slf4j; import me.earth.phobot.Phobot; import me.earth.phobot.damagecalc.CrystalPosition; import me.earth.phobot.ducks.IEntity; import me.earth.phobot.modules.BlockPlacingModule; import me.earth.phobot.modules.combat.autocrystal.AutoCrystal; import me.earth.phobot.modules.combat.autocrystal.CrystalPlacingModule; import me.earth.phobot.modules.misc.Speedmine; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.util.ResetUtil; import me.earth.phobot.util.entity.EntityUtil; import me.earth.phobot.util.math.PositionUtil; import me.earth.phobot.util.mutables.MutPos; import me.earth.phobot.util.time.TimeUtil; import me.earth.phobot.util.world.BlockStateLevel; import me.earth.pingbypass.api.event.listeners.generic.Listener; import me.earth.pingbypass.api.module.impl.Categories; import me.earth.pingbypass.commons.event.SafeListener; import me.earth.pingbypass.commons.event.network.PacketEvent; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.boss.enderdragon.EndCrystal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.phys.AABB; import org.apache.commons.lang3.mutable.MutableObject; import org.jetbrains.annotations.Nullable; import java.util.Objects; import java.util.function.Consumer;
19,660
level.getMap().put(pos, Blocks.AIR.defaultBlockState()); } position.computeValidity(phobot.getAntiCheat(), level, player, EntityUtil.RANGE, pos.getX(), pos.getY() - (position == positions.getCenter() ? 0 : 1), pos.getZ(), 0); if (position.isValid()) { if (position.isObsidian()) { position.computeEntityValidity(level, phobot.getAntiCheat().isCC(), 0); if (!position.isClearOfEntities()) { return; } } if (position == positions.center) { level.getMap().put(position, Blocks.AIR.defaultBlockState()); } else { level.getMap().put(position, Blocks.OBSIDIAN.defaultBlockState()); } calculateDamage(position, result, player, level); level.getMap().remove(position); } }, Direction.NORTH, Direction.WEST, Direction.EAST, Direction.SOUTH, Direction.DOWN/*, no Direction.UP*/); return CrystalPosition.copy(result.getBestPos()); } private void iterateOverBomberPositions(PositionsThatBlowUpDrops positions, BlockPos pos, ClientLevel level, Consumer<CrystalPosition> action, Direction... directions) { positions.center.setWithCrystalPositionOffset(pos); action.accept(positions.center); for (int i = 0; i < positions.directionPositions[0].length; i++) { // go out in "circles", so that we check the ones closest first for (int j = 0; j < directions.length; j++) { Direction direction = directions[j]; if (direction == null) { continue; } CrystalPosition crystalPos = positions.directionPositions[direction.ordinal()][i]; crystalPos.setWithCrystalPositionOffset(pos); if (!level.isEmptyBlock(crystalPos)) { directions[j] = null; continue; // continue in another direction, further crystals will be blocked by this block } action.accept(crystalPos); } } } private void calculateDamage(CrystalPosition position, Result result, LocalPlayer player, BlockStateLevel.Delegating level) { MutableObject<CrystalPosition> reference = result.getPositionToCompareTo(position); float selfDamage = phobot.getAntiCheat().getDamageCalculator().getDamage(player, level, position); position.setSelfDamage(selfDamage); if (selfDamage < EntityUtil.getHealth(player)) { if (reference.getValue() == null) { reference.setValue(position); } for (Player enemy : level.players()) { if (EntityUtil.isEnemyInRange(getPingBypass(), player, enemy, EntityUtil.RANGE + CrystalPlacingModule.CRYSTAL_RADIUS)) { float damage = phobot.getAntiCheat().getDamageCalculator().getDamage(enemy, level, position); if (damage >= EntityUtil.getHealth(enemy)) { position.setKilling(true); } position.setDamageIfHigher(damage); } } evaluate(reference, position); } } public void evaluate(MutableObject<CrystalPosition> reference, CrystalPosition position) { if (reference.getValue() == null || position.getSelfDamage() < reference.getValue().getSelfDamage() && position.getDamage() > reference.getValue().getDamage() || position.isKilling() && !reference.getValue().isKilling() || position.getDamage() >= autoCrystal.minDamage().getValue() && position.getRatio(autoCrystal.balance().getValue()) > reference.getValue().getRatio(autoCrystal.balance().getValue())) { reference.setValue(position); } } public static class Result { private final MutableObject<CrystalPosition> position = new MutableObject<>(); private final MutableObject<CrystalPosition> blockedByCrystalPosition = new MutableObject<>(); private final MutableObject<CrystalPosition> obbyPosition = new MutableObject<>(); private final MutableObject<CrystalPosition> blockedByCrystalObbyPosition = new MutableObject<>(); public MutableObject<CrystalPosition> getPositionToCompareTo(CrystalPosition crystalPosition) { if (crystalPosition.isObsidian()) { if (crystalPosition.isBlockedByCrystal()) { return blockedByCrystalObbyPosition; } return obbyPosition; } else if (crystalPosition.isBlockedByCrystal()) { return blockedByCrystalPosition; } return position; } public @Nullable CrystalPosition getBestPos() { return position.getValue() != null ? position.getValue() : (blockedByCrystalPosition.getValue() != null ? blockedByCrystalPosition.getValue() : (obbyPosition.getValue() != null ? obbyPosition.getValue() : (blockedByCrystalObbyPosition.getValue() != null ? blockedByCrystalObbyPosition.getValue() : null))); } } @Getter public static class PositionsThatBlowUpDrops { private static final BlockPos[] BLOCKING_POSITIONS = new BlockPos[]{new BlockPos(0, -1, 0), new BlockPos(1, -1, 0), new BlockPos(-1, -1, 0), new BlockPos(0, -1, -1), new BlockPos(0, -1, 1)}; private final CrystalPosition[] blockingPositions = new CrystalPosition[BLOCKING_POSITIONS.length]; private final CrystalPosition[][] directionPositions = new CrystalPosition[PositionUtil.DIRECTIONS.length][]; private final CrystalPosition center = new CrystalPosition(BlockPos.ZERO);
package me.earth.phobot.modules.combat; // TODO: stop bombing ourselves! // TODO: Anvil Bomber // TODO: distance to target player!!! // TODO: Spam crystals against surround without AutoCrystal calculation @Slf4j public class Bomber extends BlockPlacingModule { private final PositionsThatBlowUpDrops positions = new PositionsThatBlowUpDrops(); @Getter private final AutoCrystal autoCrystal; private final Speedmine speedmine; private final AutoTrap autoTrap; private volatile BlockPos currentSpeedminePos; private volatile BlockPos currentCrystalPos; private volatile long time; public Bomber(Phobot phobot, Speedmine speedmine, AutoCrystal autoCrystal, AutoTrap autoTrap) { super(phobot, phobot.getBlockPlacer(), "Bomber", Categories.COMBAT, "Place End Crystals when mining blocks.", autoCrystal.getPriority()); this.autoCrystal = autoCrystal; this.speedmine = speedmine; this.autoTrap = autoTrap; listen(new Listener<Speedmine.BreakEvent>() { @Override public void onEvent(Speedmine.BreakEvent event) { if (currentCrystalPos != null) { if (TimeUtil.isTimeStampOlderThan(time, 150L)) { reset(); } else { event.setCancelled(true); } return; } BlockStateLevel.Delegating level = new BlockStateLevel.Delegating(event.getLevel()); CrystalPosition crystal = findCrystalThatBlowsUpDrop(positions, event.getPos(), level, event.getPlayer()); Entity crystalEntity; if (crystal != null && (crystalEntity = crystal.getCrystals()[0]) != null) { phobot.getInventoryService().use(context -> { if (breakBlock(context, event.getPos(), event.getPlayer(), event.getLevel(), event.getGameMode())) { phobot.getAttackService().attack(event.getPlayer(), crystalEntity); CrystalPosition surroundBlockingPos = findPositionToBlockSurround(positions, event.getPos(), level, event.getPlayer()); if (surroundBlockingPos != null) { autoCrystal.placer().place(event.getPlayer(), level, surroundBlockingPos); } } }); event.setCancelled(true); } else { CrystalPosition blowsUpDrop = findBestPositionToBlowUpDrop(positions, event.getPos(), level, event.getPlayer()); CrystalPosition blocksSurround = findPositionToBlockSurround(positions, event.getPos(), level, event.getPlayer()); if (isValid(blowsUpDrop, blocksSurround, null) && blowsUpDrop != null) { currentCrystalPos = blowsUpDrop.immutable(); currentSpeedminePos = event.getPos(); time = TimeUtil.getMillis(); autoCrystal.placer().place(event.getPlayer(), level, blowsUpDrop); autoCrystal.blockBlackList().put(blowsUpDrop.immutable(), TimeUtil.getMillis()); event.setCancelled(true); } } } }); listen(new SafeListener<PacketEvent.Receive<ClientboundAddEntityPacket>>(mc) { @Override public void onEvent(PacketEvent.Receive<ClientboundAddEntityPacket> event, LocalPlayer player, ClientLevel clientLevel, MultiPlayerGameMode gameMode) { try { ClientboundAddEntityPacket packet = event.getPacket(); if (!packet.getType().equals(EntityType.END_CRYSTAL)) { return; } ClientLevel level = phobot.getThreadSafeLevelService().getLevel(); EndCrystal entity = new EndCrystal(level, event.getPacket().getX(), event.getPacket().getY(), event.getPacket().getZ()); if (Objects.equals(entity.blockPosition().below(), currentCrystalPos)) { if (currentSpeedminePos == null || !Objects.equals(currentSpeedminePos, speedmine.getCurrentPos())) { reset(); return; } if (entity.getBoundingBox().distanceToSqr(player.getEyePosition()) >= ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE) { reset(); return; } entity.setId(event.getPacket().getId()); phobot.getInventoryService().use(context -> { breakBlock(context, currentSpeedminePos, player, level, gameMode); phobot.getAttackService().attack(player, entity); var customBlockStateLevel = new BlockStateLevel.Delegating(level); CrystalPosition surroundBlockingPos = findPositionToBlockSurround(positions, currentSpeedminePos, customBlockStateLevel, player); if (surroundBlockingPos != null && surroundBlockingPos.getDamage() >= autoCrystal.minDamage().getValue()) { autoCrystal.placer().place(player, level, surroundBlockingPos); } else { // TODO: could update AutoTrap here? autoTrap.getBlackList().remove(currentSpeedminePos); } }); reset(); } } catch (Exception e) { log.error("Exception occurred during ClientboundAddEntityPacket receive", e); } } }); ResetUtil.onRespawnOrWorldChange(this, mc, this::reset); } @Override protected void updatePlacements(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { if (!autoCrystal.isEnabled() && autoCrystal.obbyPos() != null) { autoCrystal.updatePlacements(context, player, level, gameMode); } } public void reset() { currentSpeedminePos = null; currentCrystalPos = null; time = 0L; } private boolean breakBlock(InventoryContext context, BlockPos pos, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { autoTrap.getBlackList().put(pos, TimeUtil.getMillis()); return speedmine.breakCurrentPos(context, level, player, gameMode, false); } public boolean isValid(@Nullable CrystalPosition blowsUpDrop, @Nullable CrystalPosition blocksSurround, @Nullable CrystalPosition crystal) { if (blocksSurround == null) { if (crystal == null) { if (blowsUpDrop == null) { return false; } return blowsUpDrop.getDamage() >= autoCrystal.minDamage().getValue(); } return crystal.getDamage() >= autoCrystal.minDamage().getValue() || blowsUpDrop != null && blowsUpDrop.getDamage() >= autoCrystal.minDamage().getValue(); } // TODO: also check ratio return blocksSurround.getDamage() >= autoCrystal.minDamage().getValue() || blowsUpDrop != null && blowsUpDrop.getDamage() >= autoCrystal.minDamage().getValue(); } public @Nullable CrystalPosition findCrystalThatBlowsUpDrop(PositionsThatBlowUpDrops positions, BlockPos pos, BlockStateLevel.Delegating level, LocalPlayer player) { level.getMap().clear(); level.getMap().put(pos, Blocks.AIR.defaultBlockState()); Result result = new Result(); iterateOverBomberPositions(positions, pos, level, crystalPos -> { for (EndCrystal crystal : level.getEntities(EntityType.END_CRYSTAL, new AABB(crystalPos), endCrystal -> crystalPos.equals(endCrystal.blockPosition()))) { if (((IEntity) crystal).phobot$GetTimeSinceAttack() < 100L || !EntityUtil.isInAttackRange(player, crystal)) { continue; } crystalPos.reset(); crystalPos.setValid(true); crystalPos.getCrystals()[0] = crystal; crystalPos.incrementY(-1); // we calculate damage from below calculateDamage(crystalPos, result, player, level); } }, PositionUtil.DIRECTIONS.clone()); return result.getBestPos(); } public @Nullable CrystalPosition findPositionToBlockSurround(PositionsThatBlowUpDrops positions, BlockPos pos, BlockStateLevel.Delegating level, LocalPlayer player) { level.getMap().clear(); level.getMap().put(pos, Blocks.AIR.defaultBlockState()); Result result = new Result(); for (CrystalPosition crystalPosition : positions.blockingPositions) { crystalPosition.computeValidity(phobot.getAntiCheat(), level, player, EntityUtil.RANGE, pos, 0); if (crystalPosition.isValid()) { calculateDamage(crystalPosition, result, player, level); } } return CrystalPosition.copy(result.getBestPos()); } public @Nullable CrystalPosition findBestPositionToBlowUpDrop(PositionsThatBlowUpDrops positions, BlockPos pos, BlockStateLevel.Delegating level, LocalPlayer player) { Result result = new Result(); level.getMap().clear(); iterateOverBomberPositions(positions, pos, level, position -> { if (position != positions.center) { level.getMap().put(pos, Blocks.AIR.defaultBlockState()); } position.computeValidity(phobot.getAntiCheat(), level, player, EntityUtil.RANGE, pos.getX(), pos.getY() - (position == positions.getCenter() ? 0 : 1), pos.getZ(), 0); if (position.isValid()) { if (position.isObsidian()) { position.computeEntityValidity(level, phobot.getAntiCheat().isCC(), 0); if (!position.isClearOfEntities()) { return; } } if (position == positions.center) { level.getMap().put(position, Blocks.AIR.defaultBlockState()); } else { level.getMap().put(position, Blocks.OBSIDIAN.defaultBlockState()); } calculateDamage(position, result, player, level); level.getMap().remove(position); } }, Direction.NORTH, Direction.WEST, Direction.EAST, Direction.SOUTH, Direction.DOWN/*, no Direction.UP*/); return CrystalPosition.copy(result.getBestPos()); } private void iterateOverBomberPositions(PositionsThatBlowUpDrops positions, BlockPos pos, ClientLevel level, Consumer<CrystalPosition> action, Direction... directions) { positions.center.setWithCrystalPositionOffset(pos); action.accept(positions.center); for (int i = 0; i < positions.directionPositions[0].length; i++) { // go out in "circles", so that we check the ones closest first for (int j = 0; j < directions.length; j++) { Direction direction = directions[j]; if (direction == null) { continue; } CrystalPosition crystalPos = positions.directionPositions[direction.ordinal()][i]; crystalPos.setWithCrystalPositionOffset(pos); if (!level.isEmptyBlock(crystalPos)) { directions[j] = null; continue; // continue in another direction, further crystals will be blocked by this block } action.accept(crystalPos); } } } private void calculateDamage(CrystalPosition position, Result result, LocalPlayer player, BlockStateLevel.Delegating level) { MutableObject<CrystalPosition> reference = result.getPositionToCompareTo(position); float selfDamage = phobot.getAntiCheat().getDamageCalculator().getDamage(player, level, position); position.setSelfDamage(selfDamage); if (selfDamage < EntityUtil.getHealth(player)) { if (reference.getValue() == null) { reference.setValue(position); } for (Player enemy : level.players()) { if (EntityUtil.isEnemyInRange(getPingBypass(), player, enemy, EntityUtil.RANGE + CrystalPlacingModule.CRYSTAL_RADIUS)) { float damage = phobot.getAntiCheat().getDamageCalculator().getDamage(enemy, level, position); if (damage >= EntityUtil.getHealth(enemy)) { position.setKilling(true); } position.setDamageIfHigher(damage); } } evaluate(reference, position); } } public void evaluate(MutableObject<CrystalPosition> reference, CrystalPosition position) { if (reference.getValue() == null || position.getSelfDamage() < reference.getValue().getSelfDamage() && position.getDamage() > reference.getValue().getDamage() || position.isKilling() && !reference.getValue().isKilling() || position.getDamage() >= autoCrystal.minDamage().getValue() && position.getRatio(autoCrystal.balance().getValue()) > reference.getValue().getRatio(autoCrystal.balance().getValue())) { reference.setValue(position); } } public static class Result { private final MutableObject<CrystalPosition> position = new MutableObject<>(); private final MutableObject<CrystalPosition> blockedByCrystalPosition = new MutableObject<>(); private final MutableObject<CrystalPosition> obbyPosition = new MutableObject<>(); private final MutableObject<CrystalPosition> blockedByCrystalObbyPosition = new MutableObject<>(); public MutableObject<CrystalPosition> getPositionToCompareTo(CrystalPosition crystalPosition) { if (crystalPosition.isObsidian()) { if (crystalPosition.isBlockedByCrystal()) { return blockedByCrystalObbyPosition; } return obbyPosition; } else if (crystalPosition.isBlockedByCrystal()) { return blockedByCrystalPosition; } return position; } public @Nullable CrystalPosition getBestPos() { return position.getValue() != null ? position.getValue() : (blockedByCrystalPosition.getValue() != null ? blockedByCrystalPosition.getValue() : (obbyPosition.getValue() != null ? obbyPosition.getValue() : (blockedByCrystalObbyPosition.getValue() != null ? blockedByCrystalObbyPosition.getValue() : null))); } } @Getter public static class PositionsThatBlowUpDrops { private static final BlockPos[] BLOCKING_POSITIONS = new BlockPos[]{new BlockPos(0, -1, 0), new BlockPos(1, -1, 0), new BlockPos(-1, -1, 0), new BlockPos(0, -1, -1), new BlockPos(0, -1, 1)}; private final CrystalPosition[] blockingPositions = new CrystalPosition[BLOCKING_POSITIONS.length]; private final CrystalPosition[][] directionPositions = new CrystalPosition[PositionUtil.DIRECTIONS.length][]; private final CrystalPosition center = new CrystalPosition(BlockPos.ZERO);
private final MutPos computePos = new MutPos();
11
2023-12-22 14:32:16+00:00
24k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/gui/WaypointsGUI.java
[ { "identifier": "AutoRoom", "path": "build/sources/main/java/io/github/quantizr/core/AutoRoom.java", "snippet": "public class AutoRoom {\n Minecraft mc = Minecraft.getMinecraft();\n\n static int tickAmount = 1;\n public static List<String> autoTextOutput = null;\n public static boolean chatT...
import io.github.quantizr.core.AutoRoom; import io.github.quantizr.core.Waypoints; import io.github.quantizr.handlers.ConfigHandler; import io.github.quantizr.handlers.TextRenderer; import io.github.quantizr.utils.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumChatFormatting; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
14,798
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class WaypointsGUI extends GuiScreen { private GuiButton waypointsEnabled; private GuiButton showEntrance; private GuiButton showSuperboom; private GuiButton showSecrets; private GuiButton showFairySouls; private GuiButton disableWhenAllFound; private GuiButton sneakToDisable; private GuiButton close; public static List<GuiButton> secretButtonList = new ArrayList<>(Arrays.asList(new GuiButton[9])); private static boolean waypointGuiOpened = false; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); waypointGuiOpened = true; ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); waypointsEnabled = new GuiButton(0, width / 2 - 100, height / 6, 200, 20, waypointBtnText()); showEntrance = new GuiButton(1, (width / 2 - 100) - 110, height / 6 + 30, 200, 20, "Show Entrance Waypoints: " + getOnOff(Waypoints.showEntrance)); showSuperboom = new GuiButton(2, (width / 2 - 100) + 110, height / 6 + 30, 200, 20, "Show Superboom Waypoints: " + getOnOff(Waypoints.showSuperboom)); showSecrets = new GuiButton(3, (width / 2 - 100) - 110, height / 6 + 60, 200, 20, "Show Secret Waypoints: " + getOnOff(Waypoints.showSecrets)); showFairySouls = new GuiButton(4, (width / 2 - 100) + 110, height / 6 + 60, 200, 20, "Show Fairy Soul Waypoints: " + getOnOff(Waypoints.showFairySouls)); sneakToDisable = new GuiButton(5, (width / 2 - 100) - 110, height / 6 + 90, 200, 20, "Double-Tap Sneak to Hide Nearby: " + getOnOff(Waypoints.sneakToDisable)); disableWhenAllFound = new GuiButton(6, (width / 2 - 100) + 110, height / 6 + 90, 200, 20, "Disable when all secrets found: " + getOnOff(Waypoints.disableWhenAllFound)); close = new GuiButton(7, width / 2 - 100, (height / 6) * 5, 200, 20, "Close"); this.buttonList.add(waypointsEnabled); this.buttonList.add(showEntrance); this.buttonList.add(showSuperboom); this.buttonList.add(showSecrets); this.buttonList.add(showFairySouls); this.buttonList.add(sneakToDisable); this.buttonList.add(disableWhenAllFound); this.buttonList.add(close);
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class WaypointsGUI extends GuiScreen { private GuiButton waypointsEnabled; private GuiButton showEntrance; private GuiButton showSuperboom; private GuiButton showSecrets; private GuiButton showFairySouls; private GuiButton disableWhenAllFound; private GuiButton sneakToDisable; private GuiButton close; public static List<GuiButton> secretButtonList = new ArrayList<>(Arrays.asList(new GuiButton[9])); private static boolean waypointGuiOpened = false; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); waypointGuiOpened = true; ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); waypointsEnabled = new GuiButton(0, width / 2 - 100, height / 6, 200, 20, waypointBtnText()); showEntrance = new GuiButton(1, (width / 2 - 100) - 110, height / 6 + 30, 200, 20, "Show Entrance Waypoints: " + getOnOff(Waypoints.showEntrance)); showSuperboom = new GuiButton(2, (width / 2 - 100) + 110, height / 6 + 30, 200, 20, "Show Superboom Waypoints: " + getOnOff(Waypoints.showSuperboom)); showSecrets = new GuiButton(3, (width / 2 - 100) - 110, height / 6 + 60, 200, 20, "Show Secret Waypoints: " + getOnOff(Waypoints.showSecrets)); showFairySouls = new GuiButton(4, (width / 2 - 100) + 110, height / 6 + 60, 200, 20, "Show Fairy Soul Waypoints: " + getOnOff(Waypoints.showFairySouls)); sneakToDisable = new GuiButton(5, (width / 2 - 100) - 110, height / 6 + 90, 200, 20, "Double-Tap Sneak to Hide Nearby: " + getOnOff(Waypoints.sneakToDisable)); disableWhenAllFound = new GuiButton(6, (width / 2 - 100) + 110, height / 6 + 90, 200, 20, "Disable when all secrets found: " + getOnOff(Waypoints.disableWhenAllFound)); close = new GuiButton(7, width / 2 - 100, (height / 6) * 5, 200, 20, "Close"); this.buttonList.add(waypointsEnabled); this.buttonList.add(showEntrance); this.buttonList.add(showSuperboom); this.buttonList.add(showSecrets); this.buttonList.add(showFairySouls); this.buttonList.add(sneakToDisable); this.buttonList.add(disableWhenAllFound); this.buttonList.add(close);
if (Utils.inDungeons) {
4
2023-12-22 04:44:39+00:00
24k
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;
16,699
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) && img != null) { BadgeCard card = new BadgeCard(String.valueOf(inputInfo.loadLabel(ctx)), img, (state == TvInputManager.INPUT_STATE_CONNECTED_STANDBY) ? R.drawable.power_off : (state == TvInputManager.INPUT_STATE_CONNECTED ? R.drawable.running : null), new Card.Callback() { @Override public boolean onClicked(Card card) { tvView.tune(inputInfo.getId(), TvContract.buildChannelUriForPassthroughInput(inputInfo.getId())); hide(); return false; } @Override public void onHovered(Card card, boolean hovered) {} }); launcherBar.addItem(row, card); } } } row = launcherBar.addRow(new BadgeCard("", "Resume\nPlayback", R.drawable.icon_play_rounded, 0xFFFFFFFF,0xFFBF8C00,null)); rows.put(RESUME_ROW, row); timestamps.put(RESUME_ROW, 0L); row = launcherBar.addRow(new BadgeCard("", "Popular\nMovies", R.drawable.icon_recommend, 0xFFFFFFFF,0xFFC01F1F,null)); rows.put(POPULAR_MOVIES_ROW, row); timestamps.put(POPULAR_MOVIES_ROW, 0L); row = launcherBar.addRow(new BadgeCard("", "Popular\nSeries", R.drawable.icon_recommend, 0xFFFFFFFF,0xFF4F4FB0,null)); rows.put(POPULAR_SERIES_ROW, row); timestamps.put(POPULAR_SERIES_ROW, 0L); for (ApkRepo.App app : ApkRepo.getPlatformApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, 0L); } for (ApkRepo.App app : ApkRepo.getNonPlatformVideoApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, 0L); } for (ApkRepo.App app : ApkRepo.getAudioApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, System.currentTimeMillis()); } for (ApkRepo.App app : ApkRepo.getGamingApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, System.currentTimeMillis()); } row = launcherBar.addRow(new BadgeCard("", "Other\nApps", R.drawable.icon_apps, 0xFFFFFFFF,0xFF2CAAEE,null)); rows.put(OTHER_APPS_ROW, row); timestamps.put(OTHER_APPS_ROW, System.currentTimeMillis()); { List<ApkRepo.App> apps = new ArrayList<>(ApkRepo.getPlatformApps()); apps.addAll(ApkRepo.getNonPlatformVideoApps()); apps.addAll(ApkRepo.getAudioApps()); apps.addAll(ApkRepo.getGamingApps()); for (ApkRepo.App app : ApkRepo.getApps(null, apps)) { launcherBar.addItem(row, new BadgeCard(app.name, app.badge != null ? app.badge : app.icon, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); } } row = launcherBar.addRow( new BadgeCard("Settings", ApkRepo.getActionBadge(Settings.ACTION_SETTINGS), new Card.Callback() { @Override public boolean onClicked(Card card) { startActivity(new Intent(Settings.ACTION_SETTINGS)); return false; } @Override public void onHovered(Card card, boolean hovered) {} }) ); rows.put(SETTINGS_ROW, row); launcherBar.addItems(row, widgetBar.getAllWidgetCards()); timestamps.put(SETTINGS_ROW, System.currentTimeMillis()); //clockInterval = new Utils.Interval(() -> launcherBar.post(() -> updateClock()), 1000); } private void updateRows() { long timeNow = System.currentTimeMillis(); int row;
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) && img != null) { BadgeCard card = new BadgeCard(String.valueOf(inputInfo.loadLabel(ctx)), img, (state == TvInputManager.INPUT_STATE_CONNECTED_STANDBY) ? R.drawable.power_off : (state == TvInputManager.INPUT_STATE_CONNECTED ? R.drawable.running : null), new Card.Callback() { @Override public boolean onClicked(Card card) { tvView.tune(inputInfo.getId(), TvContract.buildChannelUriForPassthroughInput(inputInfo.getId())); hide(); return false; } @Override public void onHovered(Card card, boolean hovered) {} }); launcherBar.addItem(row, card); } } } row = launcherBar.addRow(new BadgeCard("", "Resume\nPlayback", R.drawable.icon_play_rounded, 0xFFFFFFFF,0xFFBF8C00,null)); rows.put(RESUME_ROW, row); timestamps.put(RESUME_ROW, 0L); row = launcherBar.addRow(new BadgeCard("", "Popular\nMovies", R.drawable.icon_recommend, 0xFFFFFFFF,0xFFC01F1F,null)); rows.put(POPULAR_MOVIES_ROW, row); timestamps.put(POPULAR_MOVIES_ROW, 0L); row = launcherBar.addRow(new BadgeCard("", "Popular\nSeries", R.drawable.icon_recommend, 0xFFFFFFFF,0xFF4F4FB0,null)); rows.put(POPULAR_SERIES_ROW, row); timestamps.put(POPULAR_SERIES_ROW, 0L); for (ApkRepo.App app : ApkRepo.getPlatformApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, 0L); } for (ApkRepo.App app : ApkRepo.getNonPlatformVideoApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, 0L); } for (ApkRepo.App app : ApkRepo.getAudioApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, System.currentTimeMillis()); } for (ApkRepo.App app : ApkRepo.getGamingApps()) { row = launcherBar.addRow(new BadgeCard(app.name, app.badge, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); rows.put(app.name, row); timestamps.put(app.name, System.currentTimeMillis()); } row = launcherBar.addRow(new BadgeCard("", "Other\nApps", R.drawable.icon_apps, 0xFFFFFFFF,0xFF2CAAEE,null)); rows.put(OTHER_APPS_ROW, row); timestamps.put(OTHER_APPS_ROW, System.currentTimeMillis()); { List<ApkRepo.App> apps = new ArrayList<>(ApkRepo.getPlatformApps()); apps.addAll(ApkRepo.getNonPlatformVideoApps()); apps.addAll(ApkRepo.getAudioApps()); apps.addAll(ApkRepo.getGamingApps()); for (ApkRepo.App app : ApkRepo.getApps(null, apps)) { launcherBar.addItem(row, new BadgeCard(app.name, app.badge != null ? app.badge : app.icon, new Card.Callback() { @Override public boolean onClicked(Card card) { ctx.startActivity(app.defaultIntent); return false; } @Override public void onHovered(Card card, boolean hovered) {} })); } } row = launcherBar.addRow( new BadgeCard("Settings", ApkRepo.getActionBadge(Settings.ACTION_SETTINGS), new Card.Callback() { @Override public boolean onClicked(Card card) { startActivity(new Intent(Settings.ACTION_SETTINGS)); return false; } @Override public void onHovered(Card card, boolean hovered) {} }) ); rows.put(SETTINGS_ROW, row); launcherBar.addItems(row, widgetBar.getAllWidgetCards()); timestamps.put(SETTINGS_ROW, System.currentTimeMillis()); //clockInterval = new Utils.Interval(() -> launcherBar.post(() -> updateClock()), 1000); } private void updateRows() { long timeNow = System.currentTimeMillis(); int row;
if (MovieRepo.getWatchNextTimestamp() > timestamps.get(RESUME_ROW)) {
3
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,196
package Chess.controller; public class ClickController { private final Chessboard chessboard;
package Chess.controller; public class ClickController { private final Chessboard chessboard;
private SquareComponent first;
1
2023-12-31 05:50:13+00:00
24k
psobiech/opengr8on
vclu/src/test/java/pl/psobiech/opengr8on/vclu/ServerTest.java
[ { "identifier": "CLUClient", "path": "lib/src/main/java/pl/psobiech/opengr8on/client/CLUClient.java", "snippet": "public class CLUClient extends Client implements Closeable {\n private static final Logger LOGGER = LoggerFactory.getLogger(CLUClient.class);\n\n private static final Duration DEFAULT_...
import java.net.Inet4Address; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import io.jstach.jstachio.JStachio; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import pl.psobiech.opengr8on.client.CLUClient; import pl.psobiech.opengr8on.client.CLUFiles; import pl.psobiech.opengr8on.client.CipherKey; import pl.psobiech.opengr8on.client.commands.LuaScriptCommand; import pl.psobiech.opengr8on.client.device.CLUDevice; import pl.psobiech.opengr8on.client.device.CipherTypeEnum; import pl.psobiech.opengr8on.tftp.TFTPServer; import pl.psobiech.opengr8on.tftp.TFTPServer.ServerMode; 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.ResourceUtil; import pl.psobiech.opengr8on.util.SocketUtil.UDPSocket; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue;
16,689
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.vclu; @Execution(ExecutionMode.CONCURRENT) class ServerTest { private static final Inet4Address LOCALHOST = IPv4AddressUtil.parseIPv4("127.0.0.1"); private ExecutorService executor = Executors.newCachedThreadPool(); private Path rootDirectory; private Path aDriveDirectory; private TFTPServer tftpServer; private CipherKey projectCipherKey; private CLUDevice cluDevice; private UDPSocket broadcastSocket; private UDPSocket socket; private Server server; @BeforeEach void setUp() throws Exception { executor = Executors.newCachedThreadPool(); rootDirectory = FileUtil.temporaryDirectory(); aDriveDirectory = rootDirectory.resolve("a"); FileUtil.mkdir(aDriveDirectory); broadcastSocket = new UDPSocket(LOCALHOST, 0, false); socket = new UDPSocket(LOCALHOST, 0, false); tftpServer = new TFTPServer(LOCALHOST, 0, ServerMode.GET_AND_REPLACE, rootDirectory); projectCipherKey = new CipherKey(RandomUtil.bytes(16), RandomUtil.bytes(16)); cluDevice = new CLUDevice( HexUtil.asLong(RandomUtil.hexString(8)), RandomUtil.hexString(12), LOCALHOST,
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.vclu; @Execution(ExecutionMode.CONCURRENT) class ServerTest { private static final Inet4Address LOCALHOST = IPv4AddressUtil.parseIPv4("127.0.0.1"); private ExecutorService executor = Executors.newCachedThreadPool(); private Path rootDirectory; private Path aDriveDirectory; private TFTPServer tftpServer; private CipherKey projectCipherKey; private CLUDevice cluDevice; private UDPSocket broadcastSocket; private UDPSocket socket; private Server server; @BeforeEach void setUp() throws Exception { executor = Executors.newCachedThreadPool(); rootDirectory = FileUtil.temporaryDirectory(); aDriveDirectory = rootDirectory.resolve("a"); FileUtil.mkdir(aDriveDirectory); broadcastSocket = new UDPSocket(LOCALHOST, 0, false); socket = new UDPSocket(LOCALHOST, 0, false); tftpServer = new TFTPServer(LOCALHOST, 0, ServerMode.GET_AND_REPLACE, rootDirectory); projectCipherKey = new CipherKey(RandomUtil.bytes(16), RandomUtil.bytes(16)); cluDevice = new CLUDevice( HexUtil.asLong(RandomUtil.hexString(8)), RandomUtil.hexString(12), LOCALHOST,
CipherTypeEnum.PROJECT,
5
2023-12-23 09:56:14+00:00
24k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/source/org/jfree/chart/plot/CompassPlot.java
[ { "identifier": "LegendItemCollection", "path": "lib/jfreechart-1.0.19/source/org/jfree/chart/LegendItemCollection.java", "snippet": "public class LegendItemCollection implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 1365215565...
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Polygon; import java.awt.Stroke; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.ResourceBundle; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.needle.ArrowNeedle; import org.jfree.chart.needle.LineNeedle; import org.jfree.chart.needle.LongNeedle; import org.jfree.chart.needle.MeterNeedle; import org.jfree.chart.needle.MiddlePinNeedle; import org.jfree.chart.needle.PinNeedle; import org.jfree.chart.needle.PlumNeedle; import org.jfree.chart.needle.PointerNeedle; import org.jfree.chart.needle.ShipNeedle; import org.jfree.chart.needle.WindNeedle; import org.jfree.chart.util.ParamChecks; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.data.general.DefaultValueDataset; import org.jfree.data.general.ValueDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleInsets; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintUtilities;
14,429
/* =========================================================== * 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.] * * ---------------- * CompassPlot.java * ---------------- * (C) Copyright 2002-2013, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * Arnaud Lelievre; * Martin Hoeller; * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 23-Jan-2003 : Removed one constructor (DG); * 26-Mar-2003 : Implemented Serializable (DG); * 27-Mar-2003 : Changed MeterDataset to ValueDataset (DG); * 21-Aug-2003 : Implemented Cloneable (DG); * 08-Sep-2003 : Added internationalization via use of properties * resourceBundle (RFE 690236) (AL); * 09-Sep-2003 : Changed Color --> Paint (DG); * 15-Sep-2003 : Added null data value check (bug report 805009) (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 16-Mar-2004 : Added support for revolutionDistance to enable support for * other units than degrees. * 16-Mar-2004 : Enabled LongNeedle to rotate about center. * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG); * 17-Apr-2005 : Fixed bug in clone() method (DG); * 05-May-2005 : Updated draw() method parameters (DG); * 08-Jun-2005 : Fixed equals() method to handle GradientPaint (DG); * 16-Jun-2005 : Renamed getData() --> getDatasets() and * addData() --> addDataset() (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 20-Mar-2007 : Fixed serialization (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by * Jess Thrysoee (DG); * 10-Oct-2011 : localization fix: bug #3353913 (MH); * 02-Jul-2013 : Use ParamChecks (DG); * */ package org.jfree.chart.plot; /** * A specialised plot that draws a compass to indicate a direction based on the * value from a {@link ValueDataset}. */ public class CompassPlot extends Plot implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 6924382802125527395L; /** The default label font. */ public static final Font DEFAULT_LABEL_FONT = new Font("SansSerif", Font.BOLD, 10); /** A constant for the label type. */ public static final int NO_LABELS = 0; /** A constant for the label type. */ public static final int VALUE_LABELS = 1; /** The label type (NO_LABELS, VALUE_LABELS). */ private int labelType; /** The label font. */ private Font labelFont; /** A flag that controls whether or not a border is drawn. */ private boolean drawBorder = false; /** The rose highlight paint. */ private transient Paint roseHighlightPaint = Color.black; /** The rose paint. */ private transient Paint rosePaint = Color.yellow; /** The rose center paint. */ private transient Paint roseCenterPaint = Color.white; /** The compass font. */ private Font compassFont = new Font("Arial", Font.PLAIN, 10); /** A working shape. */ private transient Ellipse2D circle1; /** A working shape. */ private transient Ellipse2D circle2; /** A working area. */ private transient Area a1; /** A working area. */ private transient Area a2; /** A working shape. */ private transient Rectangle2D rect1; /** An array of value datasets. */ private ValueDataset[] datasets = new ValueDataset[1]; /** An array of needles. */ private MeterNeedle[] seriesNeedle = new MeterNeedle[1]; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); /** * The count to complete one revolution. Can be arbitrarily set * For degrees (the default) it is 360, for radians this is 2*Pi, etc */ protected double revolutionDistance = 360; /** * Default constructor. */ public CompassPlot() { this(new DefaultValueDataset()); } /** * Constructs a new compass plot. * * @param dataset the dataset for the plot (<code>null</code> permitted). */ public CompassPlot(ValueDataset dataset) { super(); if (dataset != null) { this.datasets[0] = dataset; dataset.addChangeListener(this); } this.circle1 = new Ellipse2D.Double(); this.circle2 = new Ellipse2D.Double(); this.rect1 = new Rectangle2D.Double(); setSeriesNeedle(0); } /** * Returns the label type. Defined by the constants: {@link #NO_LABELS} * and {@link #VALUE_LABELS}. * * @return The label type. * * @see #setLabelType(int) */ public int getLabelType() { // FIXME: this attribute is never used - deprecate? return this.labelType; } /** * Sets the label type (either {@link #NO_LABELS} or {@link #VALUE_LABELS}. * * @param type the type. * * @see #getLabelType() */ public void setLabelType(int type) { // FIXME: this attribute is never used - deprecate? if ((type != NO_LABELS) && (type != VALUE_LABELS)) { throw new IllegalArgumentException( "MeterPlot.setLabelType(int): unrecognised type."); } if (this.labelType != type) { this.labelType = type; fireChangeEvent(); } } /** * Returns the label font. * * @return The label font. * * @see #setLabelFont(Font) */ public Font getLabelFont() { // FIXME: this attribute is not used - deprecate? return this.labelFont; } /** * Sets the label font and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param font the new label font. * * @see #getLabelFont() */ public void setLabelFont(Font font) { // FIXME: this attribute is not used - deprecate? ParamChecks.nullNotPermitted(font, "font"); this.labelFont = font; fireChangeEvent(); } /** * Returns the paint used to fill the outer circle of the compass. * * @return The paint (never <code>null</code>). * * @see #setRosePaint(Paint) */ public Paint getRosePaint() { return this.rosePaint; } /** * Sets the paint used to fill the outer circle of the compass, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRosePaint() */ public void setRosePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rosePaint = paint; fireChangeEvent(); } /** * Returns the paint used to fill the inner background area of the * compass. * * @return The paint (never <code>null</code>). * * @see #setRoseCenterPaint(Paint) */ public Paint getRoseCenterPaint() { return this.roseCenterPaint; } /** * Sets the paint used to fill the inner background area of the compass, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRoseCenterPaint() */ public void setRoseCenterPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.roseCenterPaint = paint; fireChangeEvent(); } /** * Returns the paint used to draw the circles, symbols and labels on the * compass. * * @return The paint (never <code>null</code>). * * @see #setRoseHighlightPaint(Paint) */ public Paint getRoseHighlightPaint() { return this.roseHighlightPaint; } /** * Sets the paint used to draw the circles, symbols and labels of the * compass, and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRoseHighlightPaint() */ public void setRoseHighlightPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.roseHighlightPaint = paint; fireChangeEvent(); } /** * Returns a flag that controls whether or not a border is drawn. * * @return The flag. * * @see #setDrawBorder(boolean) */ public boolean getDrawBorder() { return this.drawBorder; } /** * Sets a flag that controls whether or not a border is drawn. * * @param status the flag status. * * @see #getDrawBorder() */ public void setDrawBorder(boolean status) { this.drawBorder = status; fireChangeEvent(); } /** * Sets the series paint. * * @param series the series index. * @param paint the paint. * * @see #setSeriesOutlinePaint(int, Paint) */ public void setSeriesPaint(int series, Paint paint) { // super.setSeriesPaint(series, paint); if ((series >= 0) && (series < this.seriesNeedle.length)) { this.seriesNeedle[series].setFillPaint(paint); } } /** * Sets the series outline paint. * * @param series the series index. * @param p the paint. * * @see #setSeriesPaint(int, Paint) */ public void setSeriesOutlinePaint(int series, Paint p) { if ((series >= 0) && (series < this.seriesNeedle.length)) { this.seriesNeedle[series].setOutlinePaint(p); } } /** * Sets the series outline stroke. * * @param series the series index. * @param stroke the stroke. * * @see #setSeriesOutlinePaint(int, Paint) */ public void setSeriesOutlineStroke(int series, Stroke stroke) { if ((series >= 0) && (series < this.seriesNeedle.length)) { this.seriesNeedle[series].setOutlineStroke(stroke); } } /** * Sets the needle type. * * @param type the type. * * @see #setSeriesNeedle(int, int) */ public void setSeriesNeedle(int type) { setSeriesNeedle(0, type); } /** * Sets the needle for a series. The needle type is one of the following: * <ul> * <li>0 = {@link ArrowNeedle};</li> * <li>1 = {@link LineNeedle};</li> * <li>2 = {@link LongNeedle};</li> * <li>3 = {@link PinNeedle};</li> * <li>4 = {@link PlumNeedle};</li> * <li>5 = {@link PointerNeedle};</li> * <li>6 = {@link ShipNeedle};</li> * <li>7 = {@link WindNeedle};</li> * <li>8 = {@link ArrowNeedle};</li> * <li>9 = {@link MiddlePinNeedle};</li> * </ul> * @param index the series index. * @param type the needle type. * * @see #setSeriesNeedle(int) */ public void setSeriesNeedle(int index, int type) { switch (type) { case 0:
/* =========================================================== * 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.] * * ---------------- * CompassPlot.java * ---------------- * (C) Copyright 2002-2013, by the Australian Antarctic Division and * Contributors. * * Original Author: Bryan Scott (for the Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * Arnaud Lelievre; * Martin Hoeller; * * Changes: * -------- * 25-Sep-2002 : Version 1, contributed by Bryan Scott (DG); * 23-Jan-2003 : Removed one constructor (DG); * 26-Mar-2003 : Implemented Serializable (DG); * 27-Mar-2003 : Changed MeterDataset to ValueDataset (DG); * 21-Aug-2003 : Implemented Cloneable (DG); * 08-Sep-2003 : Added internationalization via use of properties * resourceBundle (RFE 690236) (AL); * 09-Sep-2003 : Changed Color --> Paint (DG); * 15-Sep-2003 : Added null data value check (bug report 805009) (DG); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 16-Mar-2004 : Added support for revolutionDistance to enable support for * other units than degrees. * 16-Mar-2004 : Enabled LongNeedle to rotate about center. * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG); * 17-Apr-2005 : Fixed bug in clone() method (DG); * 05-May-2005 : Updated draw() method parameters (DG); * 08-Jun-2005 : Fixed equals() method to handle GradientPaint (DG); * 16-Jun-2005 : Renamed getData() --> getDatasets() and * addData() --> addDataset() (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 20-Mar-2007 : Fixed serialization (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by * Jess Thrysoee (DG); * 10-Oct-2011 : localization fix: bug #3353913 (MH); * 02-Jul-2013 : Use ParamChecks (DG); * */ package org.jfree.chart.plot; /** * A specialised plot that draws a compass to indicate a direction based on the * value from a {@link ValueDataset}. */ public class CompassPlot extends Plot implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 6924382802125527395L; /** The default label font. */ public static final Font DEFAULT_LABEL_FONT = new Font("SansSerif", Font.BOLD, 10); /** A constant for the label type. */ public static final int NO_LABELS = 0; /** A constant for the label type. */ public static final int VALUE_LABELS = 1; /** The label type (NO_LABELS, VALUE_LABELS). */ private int labelType; /** The label font. */ private Font labelFont; /** A flag that controls whether or not a border is drawn. */ private boolean drawBorder = false; /** The rose highlight paint. */ private transient Paint roseHighlightPaint = Color.black; /** The rose paint. */ private transient Paint rosePaint = Color.yellow; /** The rose center paint. */ private transient Paint roseCenterPaint = Color.white; /** The compass font. */ private Font compassFont = new Font("Arial", Font.PLAIN, 10); /** A working shape. */ private transient Ellipse2D circle1; /** A working shape. */ private transient Ellipse2D circle2; /** A working area. */ private transient Area a1; /** A working area. */ private transient Area a2; /** A working shape. */ private transient Rectangle2D rect1; /** An array of value datasets. */ private ValueDataset[] datasets = new ValueDataset[1]; /** An array of needles. */ private MeterNeedle[] seriesNeedle = new MeterNeedle[1]; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); /** * The count to complete one revolution. Can be arbitrarily set * For degrees (the default) it is 360, for radians this is 2*Pi, etc */ protected double revolutionDistance = 360; /** * Default constructor. */ public CompassPlot() { this(new DefaultValueDataset()); } /** * Constructs a new compass plot. * * @param dataset the dataset for the plot (<code>null</code> permitted). */ public CompassPlot(ValueDataset dataset) { super(); if (dataset != null) { this.datasets[0] = dataset; dataset.addChangeListener(this); } this.circle1 = new Ellipse2D.Double(); this.circle2 = new Ellipse2D.Double(); this.rect1 = new Rectangle2D.Double(); setSeriesNeedle(0); } /** * Returns the label type. Defined by the constants: {@link #NO_LABELS} * and {@link #VALUE_LABELS}. * * @return The label type. * * @see #setLabelType(int) */ public int getLabelType() { // FIXME: this attribute is never used - deprecate? return this.labelType; } /** * Sets the label type (either {@link #NO_LABELS} or {@link #VALUE_LABELS}. * * @param type the type. * * @see #getLabelType() */ public void setLabelType(int type) { // FIXME: this attribute is never used - deprecate? if ((type != NO_LABELS) && (type != VALUE_LABELS)) { throw new IllegalArgumentException( "MeterPlot.setLabelType(int): unrecognised type."); } if (this.labelType != type) { this.labelType = type; fireChangeEvent(); } } /** * Returns the label font. * * @return The label font. * * @see #setLabelFont(Font) */ public Font getLabelFont() { // FIXME: this attribute is not used - deprecate? return this.labelFont; } /** * Sets the label font and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param font the new label font. * * @see #getLabelFont() */ public void setLabelFont(Font font) { // FIXME: this attribute is not used - deprecate? ParamChecks.nullNotPermitted(font, "font"); this.labelFont = font; fireChangeEvent(); } /** * Returns the paint used to fill the outer circle of the compass. * * @return The paint (never <code>null</code>). * * @see #setRosePaint(Paint) */ public Paint getRosePaint() { return this.rosePaint; } /** * Sets the paint used to fill the outer circle of the compass, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRosePaint() */ public void setRosePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rosePaint = paint; fireChangeEvent(); } /** * Returns the paint used to fill the inner background area of the * compass. * * @return The paint (never <code>null</code>). * * @see #setRoseCenterPaint(Paint) */ public Paint getRoseCenterPaint() { return this.roseCenterPaint; } /** * Sets the paint used to fill the inner background area of the compass, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRoseCenterPaint() */ public void setRoseCenterPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.roseCenterPaint = paint; fireChangeEvent(); } /** * Returns the paint used to draw the circles, symbols and labels on the * compass. * * @return The paint (never <code>null</code>). * * @see #setRoseHighlightPaint(Paint) */ public Paint getRoseHighlightPaint() { return this.roseHighlightPaint; } /** * Sets the paint used to draw the circles, symbols and labels of the * compass, and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRoseHighlightPaint() */ public void setRoseHighlightPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.roseHighlightPaint = paint; fireChangeEvent(); } /** * Returns a flag that controls whether or not a border is drawn. * * @return The flag. * * @see #setDrawBorder(boolean) */ public boolean getDrawBorder() { return this.drawBorder; } /** * Sets a flag that controls whether or not a border is drawn. * * @param status the flag status. * * @see #getDrawBorder() */ public void setDrawBorder(boolean status) { this.drawBorder = status; fireChangeEvent(); } /** * Sets the series paint. * * @param series the series index. * @param paint the paint. * * @see #setSeriesOutlinePaint(int, Paint) */ public void setSeriesPaint(int series, Paint paint) { // super.setSeriesPaint(series, paint); if ((series >= 0) && (series < this.seriesNeedle.length)) { this.seriesNeedle[series].setFillPaint(paint); } } /** * Sets the series outline paint. * * @param series the series index. * @param p the paint. * * @see #setSeriesPaint(int, Paint) */ public void setSeriesOutlinePaint(int series, Paint p) { if ((series >= 0) && (series < this.seriesNeedle.length)) { this.seriesNeedle[series].setOutlinePaint(p); } } /** * Sets the series outline stroke. * * @param series the series index. * @param stroke the stroke. * * @see #setSeriesOutlinePaint(int, Paint) */ public void setSeriesOutlineStroke(int series, Stroke stroke) { if ((series >= 0) && (series < this.seriesNeedle.length)) { this.seriesNeedle[series].setOutlineStroke(stroke); } } /** * Sets the needle type. * * @param type the type. * * @see #setSeriesNeedle(int, int) */ public void setSeriesNeedle(int type) { setSeriesNeedle(0, type); } /** * Sets the needle for a series. The needle type is one of the following: * <ul> * <li>0 = {@link ArrowNeedle};</li> * <li>1 = {@link LineNeedle};</li> * <li>2 = {@link LongNeedle};</li> * <li>3 = {@link PinNeedle};</li> * <li>4 = {@link PlumNeedle};</li> * <li>5 = {@link PointerNeedle};</li> * <li>6 = {@link ShipNeedle};</li> * <li>7 = {@link WindNeedle};</li> * <li>8 = {@link ArrowNeedle};</li> * <li>9 = {@link MiddlePinNeedle};</li> * </ul> * @param index the series index. * @param type the needle type. * * @see #setSeriesNeedle(int) */ public void setSeriesNeedle(int index, int type) { switch (type) { case 0:
setSeriesNeedle(index, new ArrowNeedle(true));
2
2023-12-24 12:36:47+00:00
24k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/MayOBees.java
[ { "identifier": "MainCommand", "path": "src/main/java/com/github/may2beez/mayobees/command/MainCommand.java", "snippet": "@Command(value = \"m2b\", description = \"MayOBees Command\", aliases = {\"mayobees\"})\npublic class MainCommand {\n @Main\n private void main() {\n MayOBees.CONFIG.ope...
import cc.polyfrost.oneconfig.utils.commands.CommandManager; import com.github.may2beez.mayobees.command.MainCommand; import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.handler.GameStateHandler; import com.github.may2beez.mayobees.handler.RotationHandler; import com.github.may2beez.mayobees.module.ModuleManager; import com.github.may2beez.mayobees.module.impl.other.Failsafes; import com.github.may2beez.mayobees.util.helper.AudioManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent;
14,453
package com.github.may2beez.mayobees; @Mod(modid = "mayobees", useMetadata=true) public class MayOBees { public static final MayOBeesConfig CONFIG = new MayOBeesConfig(); public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); @Mod.EventHandler public void init(FMLInitializationEvent event) { MinecraftForge.EVENT_BUS.register(RotationHandler.getInstance()); MinecraftForge.EVENT_BUS.register(GameStateHandler.getInstance()); MinecraftForge.EVENT_BUS.register(AudioManager.getInstance());
package com.github.may2beez.mayobees; @Mod(modid = "mayobees", useMetadata=true) public class MayOBees { public static final MayOBeesConfig CONFIG = new MayOBeesConfig(); public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); @Mod.EventHandler public void init(FMLInitializationEvent event) { MinecraftForge.EVENT_BUS.register(RotationHandler.getInstance()); MinecraftForge.EVENT_BUS.register(GameStateHandler.getInstance()); MinecraftForge.EVENT_BUS.register(AudioManager.getInstance());
MinecraftForge.EVENT_BUS.register(Failsafes.getInstance());
5
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,332
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);
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);
4
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,200
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());
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());
2
2023-12-31 10:56:59+00:00
24k
HuXin0817/shop_api
framework/src/main/java/cn/lili/modules/goods/serviceimpl/CategoryServiceImpl.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.event.TransactionCommitSendMQEvent; import cn.lili.common.exception.ServiceException; import cn.lili.common.properties.RocketmqCustomProperties; import cn.lili.modules.goods.entity.dos.Category; import cn.lili.modules.goods.entity.dto.CategorySearchParams; import cn.lili.modules.goods.entity.vos.CategoryVO; import cn.lili.modules.goods.mapper.CategoryMapper; import cn.lili.modules.goods.service.CategoryBrandService; import cn.lili.modules.goods.service.CategoryParameterGroupService; import cn.lili.modules.goods.service.CategoryService; import cn.lili.modules.goods.service.CategorySpecificationService; import cn.lili.rocketmq.tags.GoodsTagsEnum; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.stream.Collectors;
18,376
package cn.lili.modules.goods.serviceimpl; /** * 商品分类业务层实现 * * @author pikachu * @since 2020-02-23 15:18:56 */ @Service @CacheConfig(cacheNames = "{CATEGORY}") public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService { private static final String DELETE_FLAG_COLUMN = "delete_flag"; /** * 缓存 */ @Autowired private Cache cache; @Autowired private CategoryBrandService categoryBrandService; @Autowired private CategoryParameterGroupService categoryParameterGroupService; @Autowired
package cn.lili.modules.goods.serviceimpl; /** * 商品分类业务层实现 * * @author pikachu * @since 2020-02-23 15:18:56 */ @Service @CacheConfig(cacheNames = "{CATEGORY}") public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService { private static final String DELETE_FLAG_COLUMN = "delete_flag"; /** * 缓存 */ @Autowired private Cache cache; @Autowired private CategoryBrandService categoryBrandService; @Autowired private CategoryParameterGroupService categoryParameterGroupService; @Autowired
private CategorySpecificationService categorySpecificationService;
13
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,955
/* * 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() { return new MetadataRequest.Builder(new ArrayList<>(topics.keySet()), true); } //构建获取新主题元数据的请求 @Override public synchronized MetadataRequest.Builder newMetadataRequestBuilderForNewTopics() { return new MetadataRequest.Builder(new ArrayList<>(newTopics), true); } //往元数据添加一个topic public synchronized void add(String topic, long nowMs) { Objects.requireNonNull(topic, "topic cannot be null"); //将topic存放到带有过期时间的topic集合,如果返回结果为空,就表示是第一次添加这个topic //此时将这个topic放到新topic集合,并发起更新新topic的请求(这里没有实际发,只是修改状态位)。 if (topics.put(topic, nowMs + metadataIdleMs) == null) { newTopics.add(topic); requestUpdateForNewTopics(); } } //请求更新topic public synchronized int requestUpdateForTopic(String topic) { //如果这个topic在新topic列表,那就走请求更新新topic的逻辑,否则走更新topic的逻辑 if (newTopics.contains(topic)) { return requestUpdateForNewTopics(); } else { return requestUpdate(); } } // Visible for testing synchronized Set<String> topics() { return topics.keySet(); } // Visible for testing synchronized Set<String> newTopics() { return newTopics; } public synchronized boolean containsTopic(String topic) { return topics.containsKey(topic); } //判断元数据中是否应该保留该主题 @Override public synchronized boolean retainTopic(String topic, boolean isInternal, long nowMs) { //从带过期时间的主题列表中获取该topic Long expireMs = topics.get(topic); //如果过期时间为空,说明不在topic列表,直接返回false。 //如果在新的topic集合中,返回true。 //如果元数据已经过期了,那就从topic过期列表移除这个topic,返回false。 //否则返回true。 if (expireMs == null) { return false; } else if (newTopics.contains(topic)) { return true; } else if (expireMs <= nowMs) { log.debug("Removing unused topic {} from the metadata list, expiryMs {} now {}", topic, expireMs, nowMs); topics.remove(topic); return false; } else { return true; } } //阻塞等待更新元数据信息的线程 public synchronized void awaitUpdate(final int lastVersion, final long timeoutMs) throws InterruptedException { //获取当前时间 long currentTimeMs = time.milliseconds(); //截止时间 = 当前时间+ 超时时间 <0 取Long的最大值,否则取当前时间+ 超时时间 long deadlineMs = currentTimeMs + timeoutMs < 0 ? Long.MAX_VALUE : currentTimeMs + timeoutMs; //尝试阻塞等待,这里的time是SystemTime time.waitObject(this, () -> { // Throw fatal exceptions, if there are any. Recoverable topic errors will be handled by the caller. maybeThrowFatalException(); return updateVersion() > lastVersion || isClosed(); }, deadlineMs); if (isClosed()) throw new KafkaException("Requested metadata update after close"); } @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() { return new MetadataRequest.Builder(new ArrayList<>(topics.keySet()), true); } //构建获取新主题元数据的请求 @Override public synchronized MetadataRequest.Builder newMetadataRequestBuilderForNewTopics() { return new MetadataRequest.Builder(new ArrayList<>(newTopics), true); } //往元数据添加一个topic public synchronized void add(String topic, long nowMs) { Objects.requireNonNull(topic, "topic cannot be null"); //将topic存放到带有过期时间的topic集合,如果返回结果为空,就表示是第一次添加这个topic //此时将这个topic放到新topic集合,并发起更新新topic的请求(这里没有实际发,只是修改状态位)。 if (topics.put(topic, nowMs + metadataIdleMs) == null) { newTopics.add(topic); requestUpdateForNewTopics(); } } //请求更新topic public synchronized int requestUpdateForTopic(String topic) { //如果这个topic在新topic列表,那就走请求更新新topic的逻辑,否则走更新topic的逻辑 if (newTopics.contains(topic)) { return requestUpdateForNewTopics(); } else { return requestUpdate(); } } // Visible for testing synchronized Set<String> topics() { return topics.keySet(); } // Visible for testing synchronized Set<String> newTopics() { return newTopics; } public synchronized boolean containsTopic(String topic) { return topics.containsKey(topic); } //判断元数据中是否应该保留该主题 @Override public synchronized boolean retainTopic(String topic, boolean isInternal, long nowMs) { //从带过期时间的主题列表中获取该topic Long expireMs = topics.get(topic); //如果过期时间为空,说明不在topic列表,直接返回false。 //如果在新的topic集合中,返回true。 //如果元数据已经过期了,那就从topic过期列表移除这个topic,返回false。 //否则返回true。 if (expireMs == null) { return false; } else if (newTopics.contains(topic)) { return true; } else if (expireMs <= nowMs) { log.debug("Removing unused topic {} from the metadata list, expiryMs {} now {}", topic, expireMs, nowMs); topics.remove(topic); return false; } else { return true; } } //阻塞等待更新元数据信息的线程 public synchronized void awaitUpdate(final int lastVersion, final long timeoutMs) throws InterruptedException { //获取当前时间 long currentTimeMs = time.milliseconds(); //截止时间 = 当前时间+ 超时时间 <0 取Long的最大值,否则取当前时间+ 超时时间 long deadlineMs = currentTimeMs + timeoutMs < 0 ? Long.MAX_VALUE : currentTimeMs + timeoutMs; //尝试阻塞等待,这里的time是SystemTime time.waitObject(this, () -> { // Throw fatal exceptions, if there are any. Recoverable topic errors will be handled by the caller. maybeThrowFatalException(); return updateVersion() > lastVersion || isClosed(); }, deadlineMs); if (isClosed()) throw new KafkaException("Requested metadata update after close"); } @Override
public synchronized void update(int requestVersion, MetadataResponse response, boolean isPartialUpdate, long nowMs) {
4
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;
20,361
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();
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) {
4
2023-11-10 14:28:40+00:00
24k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/listeners/RitualListener.java
[ { "identifier": "Devotions", "path": "src/main/java/me/xidentified/devotions/Devotions.java", "snippet": "@Getter\npublic class Devotions extends JavaPlugin {\n @Getter private static Devotions instance;\n private DevotionManager devotionManager;\n private RitualManager ritualManager;\n priv...
import me.xidentified.devotions.Devotions; import me.xidentified.devotions.managers.MeditationManager; import me.xidentified.devotions.managers.RitualManager; import me.xidentified.devotions.managers.ShrineManager; import me.xidentified.devotions.rituals.Ritual; import me.xidentified.devotions.rituals.RitualObjective; import me.xidentified.devotions.util.Messages; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.List;
14,896
package me.xidentified.devotions.listeners; public class RitualListener implements Listener { private final Devotions plugin;
package me.xidentified.devotions.listeners; public class RitualListener implements Listener { private final Devotions plugin;
private final RitualManager ritualManager;
2
2023-11-10 07:03:24+00:00
24k
SplitfireUptown/datalinkx
flinkx/flinkx-rdb/flinkx-rdb-reader/src/main/java/com.dtstack.flinkx.rdb.inputformat/JdbcInputFormat.java
[ { "identifier": "ConstantValue", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/constants/ConstantValue.java", "snippet": "public class ConstantValue {\n\n public static final String STAR_SYMBOL = \"*\";\n public static final String POINT_SYMBOL = \".\";\n public static final Stri...
import com.dtstack.flinkx.constants.ConstantValue; import com.dtstack.flinkx.constants.Metrics; import com.dtstack.flinkx.enums.ColumnType; import com.dtstack.flinkx.inputformat.BaseRichInputFormat; import com.dtstack.flinkx.rdb.DatabaseInterface; import com.dtstack.flinkx.rdb.datareader.IncrementConfig; import com.dtstack.flinkx.rdb.type.TypeConverterInterface; import com.dtstack.flinkx.rdb.util.DbUtil; import com.dtstack.flinkx.reader.MetaColumn; import com.dtstack.flinkx.restore.FormatState; import com.dtstack.flinkx.util.ClassUtil; import com.dtstack.flinkx.util.ExceptionUtil; import com.dtstack.flinkx.util.FileSystemUtil; import com.dtstack.flinkx.util.GsonUtil; import com.dtstack.flinkx.util.RetryUtil; import com.dtstack.flinkx.util.StringUtil; import com.dtstack.flinkx.util.UrlUtil; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import org.apache.commons.lang3.StringUtils; import org.apache.flink.core.io.InputSplit; import org.apache.flink.types.Row; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.io.IOUtils; import java.io.IOException; import java.math.BigInteger; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit;
20,406
} } catch (SQLException se) { LOG.error("querySql: " + querySql); throw new IllegalArgumentException("open() failed." + se.getMessage(), se); } boolean splitWithRowCol = numPartitions > 1 && StringUtils.isNotEmpty(splitKey) && splitKey.contains("("); if (splitWithRowCol) { columnCount = columnCount - 1; } checkSize(columnCount, metaColumns); columnTypeList = DbUtil.analyzeColumnType(resultSet, metaColumns); LOG.info("JdbcInputFormat[{}]open: end", jobName); } @Override public InputSplit[] createInputSplitsInternal(int minNumSplits) { JdbcInputSplit[] splits = new JdbcInputSplit[minNumSplits]; for (int i = 0; i < minNumSplits; i++) { splits[i] = new JdbcInputSplit(i, numPartitions, i, incrementConfig.getStartLocation(), null); } return splits; } @Override public boolean reachedEnd() throws IOException{ if (hasNext) { return false; } else { if (incrementConfig.isPolling()) { try { TimeUnit.MILLISECONDS.sleep(incrementConfig.getPollingInterval()); //sqlserver、DB2驱动包不支持isValid(),这里先注释掉,后续更换驱动包 //间隔轮询检测数据库连接是否断开,超时时间三秒,断开后自动重连 // if(!dbConn.isValid(3)){ // dbConn = DbUtil.getConnection(dbUrl, username, password); // //重新连接后还是不可用则认为数据库异常,任务失败 // if(!dbConn.isValid(3)){ // String message = String.format("cannot connect to %s, username = %s, please check %s is available.", dbUrl, username, databaseInterface.getDatabaseType()); // LOG.error(message); // throw new RuntimeException(message); // } // } if(!dbConn.getAutoCommit()){ dbConn.setAutoCommit(true); } DbUtil.closeDbResources(resultSet, null, null, false); //此处endLocation理应不会为空 queryForPolling(endLocationAccumulator.getLocalValue().toString()); return false; } catch (InterruptedException e) { LOG.warn("interrupted while waiting for polling, e = {}", ExceptionUtil.getErrorMessage(e)); } catch (SQLException e) { DbUtil.closeDbResources(resultSet, ps, null, false); String message = String.format("error to execute sql = %s, startLocation = %s, e = %s", querySql, endLocationAccumulator.getLocalValue(), ExceptionUtil.getErrorMessage(e)); LOG.error(message); throw new RuntimeException(message, e); } } return true; } } @Override public Row nextRecordInternal(Row row) throws IOException { try { updateColumnCount(); if (!ConstantValue.STAR_SYMBOL.equals(metaColumns.get(0).getName())) { for (int i = 0; i < columnCount; i++) { Object val = row.getField(i); if (val == null && metaColumns.get(i).getValue() != null) { val = metaColumns.get(i).getValue(); } if (val instanceof String) { val = StringUtil.string2col(String.valueOf(val), metaColumns.get(i).getType(), metaColumns.get(i).getTimeFormat()); row.setField(i, val); } } } boolean isUpdateLocation = incrementConfig.isPolling() || (incrementConfig.isIncrement() && !incrementConfig.isUseMaxFunc()); if (isUpdateLocation) { String location = null; Object obj = resultSet.getObject(incrementConfig.getColumnName()); if(obj != null) { if((obj instanceof java.util.Date || obj.getClass().getSimpleName().toUpperCase().contains(ColumnType.TIMESTAMP.name())) ) { obj = resultSet.getTimestamp(incrementConfig.getColumnName()).getTime(); } location = String.valueOf(obj); endLocationAccumulator.add(new BigInteger(location)); } LOG.trace("update endLocationAccumulator, current Location = {}", location); } count++; if (count == fetchSize) { long current = System.currentTimeMillis(); LOG.error(">>>>>>>> jobId: {} end read use time: {} count: {}", jobName, current - timestamp, count); timestamp = current; count = 0; } hasNext = resultSet.next(); if (restoreConfig.isRestore()) { lastRow = row; } return row; } catch (SQLException se) { throw new IOException("Couldn't read data - " + se.getMessage(), se); } catch (Exception npe) { throw new IOException("Couldn't access resultSet", npe); } } @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 com.dtstack.flinkx.rdb.inputformat; /** * InputFormat for reading data from a database and generate Rows. * <p> * Company: www.dtstack.com * * @author huyifan.zju@163.com */ public class JdbcInputFormat extends BaseRichInputFormat { public static final long serialVersionUID = 1L; public static final int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY; public static int resultSetType = ResultSet.TYPE_FORWARD_ONLY; public DatabaseInterface databaseInterface; public String table; public String queryTemplate; public String customSql; public String querySql; public String splitKey; public int fetchSize = 10000; public int queryTimeOut; public IncrementConfig incrementConfig; public String username; public String password; public String driverName; public String dbUrl; public Properties properties; public transient Connection dbConn; public transient Statement statement; public transient PreparedStatement ps; public transient ResultSet resultSet; public boolean hasNext; public List<MetaColumn> metaColumns; public List<String> columnTypeList; public int columnCount; public MetaColumn restoreColumn; public Row lastRow = null; public long count = 0; public long timestamp = 0; //for postgre public TypeConverterInterface typeConverter; public int numPartitions; public StringAccumulator maxValueAccumulator; public BigIntegerMaximum endLocationAccumulator; public BigIntegerMaximum startLocationAccumulator; //轮询增量标识字段类型 public ColumnType type; //The hadoop config for metric public Map<String, Object> hadoopConfig; @Override public void openInputFormat() throws IOException { super.openInputFormat(); if (restoreConfig == null || !restoreConfig.isRestore()){ return; } if (restoreConfig.getRestoreColumnIndex() == -1) { throw new IllegalArgumentException("Restore column index must specified"); } restoreColumn = metaColumns.get(restoreConfig.getRestoreColumnIndex()); } @Override public void openInternal(InputSplit inputSplit) throws IOException { LOG.info("inputSplit = {}", inputSplit); ClassUtil.forName(driverName, getClass().getClassLoader()); initMetric(inputSplit); if (!canReadData(inputSplit)) { LOG.warn("Not read data when the start location are equal to end location"); hasNext = false; return; } querySql = buildQuerySql(inputSplit); try { executeQuery(((JdbcInputSplit) inputSplit).getStartLocation()); if(!resultSet.isClosed()){ columnCount = resultSet.getMetaData().getColumnCount(); } } catch (SQLException se) { LOG.error("querySql: " + querySql); throw new IllegalArgumentException("open() failed." + se.getMessage(), se); } boolean splitWithRowCol = numPartitions > 1 && StringUtils.isNotEmpty(splitKey) && splitKey.contains("("); if (splitWithRowCol) { columnCount = columnCount - 1; } checkSize(columnCount, metaColumns); columnTypeList = DbUtil.analyzeColumnType(resultSet, metaColumns); LOG.info("JdbcInputFormat[{}]open: end", jobName); } @Override public InputSplit[] createInputSplitsInternal(int minNumSplits) { JdbcInputSplit[] splits = new JdbcInputSplit[minNumSplits]; for (int i = 0; i < minNumSplits; i++) { splits[i] = new JdbcInputSplit(i, numPartitions, i, incrementConfig.getStartLocation(), null); } return splits; } @Override public boolean reachedEnd() throws IOException{ if (hasNext) { return false; } else { if (incrementConfig.isPolling()) { try { TimeUnit.MILLISECONDS.sleep(incrementConfig.getPollingInterval()); //sqlserver、DB2驱动包不支持isValid(),这里先注释掉,后续更换驱动包 //间隔轮询检测数据库连接是否断开,超时时间三秒,断开后自动重连 // if(!dbConn.isValid(3)){ // dbConn = DbUtil.getConnection(dbUrl, username, password); // //重新连接后还是不可用则认为数据库异常,任务失败 // if(!dbConn.isValid(3)){ // String message = String.format("cannot connect to %s, username = %s, please check %s is available.", dbUrl, username, databaseInterface.getDatabaseType()); // LOG.error(message); // throw new RuntimeException(message); // } // } if(!dbConn.getAutoCommit()){ dbConn.setAutoCommit(true); } DbUtil.closeDbResources(resultSet, null, null, false); //此处endLocation理应不会为空 queryForPolling(endLocationAccumulator.getLocalValue().toString()); return false; } catch (InterruptedException e) { LOG.warn("interrupted while waiting for polling, e = {}", ExceptionUtil.getErrorMessage(e)); } catch (SQLException e) { DbUtil.closeDbResources(resultSet, ps, null, false); String message = String.format("error to execute sql = %s, startLocation = %s, e = %s", querySql, endLocationAccumulator.getLocalValue(), ExceptionUtil.getErrorMessage(e)); LOG.error(message); throw new RuntimeException(message, e); } } return true; } } @Override public Row nextRecordInternal(Row row) throws IOException { try { updateColumnCount(); if (!ConstantValue.STAR_SYMBOL.equals(metaColumns.get(0).getName())) { for (int i = 0; i < columnCount; i++) { Object val = row.getField(i); if (val == null && metaColumns.get(i).getValue() != null) { val = metaColumns.get(i).getValue(); } if (val instanceof String) { val = StringUtil.string2col(String.valueOf(val), metaColumns.get(i).getType(), metaColumns.get(i).getTimeFormat()); row.setField(i, val); } } } boolean isUpdateLocation = incrementConfig.isPolling() || (incrementConfig.isIncrement() && !incrementConfig.isUseMaxFunc()); if (isUpdateLocation) { String location = null; Object obj = resultSet.getObject(incrementConfig.getColumnName()); if(obj != null) { if((obj instanceof java.util.Date || obj.getClass().getSimpleName().toUpperCase().contains(ColumnType.TIMESTAMP.name())) ) { obj = resultSet.getTimestamp(incrementConfig.getColumnName()).getTime(); } location = String.valueOf(obj); endLocationAccumulator.add(new BigInteger(location)); } LOG.trace("update endLocationAccumulator, current Location = {}", location); } count++; if (count == fetchSize) { long current = System.currentTimeMillis(); LOG.error(">>>>>>>> jobId: {} end read use time: {} count: {}", jobName, current - timestamp, count); timestamp = current; count = 0; } hasNext = resultSet.next(); if (restoreConfig.isRestore()) { lastRow = row; } return row; } catch (SQLException se) { throw new IOException("Couldn't read data - " + se.getMessage(), se); } catch (Exception npe) { throw new IOException("Couldn't access resultSet", npe); } } @Override
public FormatState getFormatState() {
9
2023-11-16 02:22:52+00:00
24k
bdmarius/jndarray-toolbox
src/main/java/internals/TensorElementMath.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.Map; import java.util.function.BiFunction; import java.util.function.Function;
19,882
package internals; public class TensorElementMath { static Tensor powerOf(Tensor tensor, Number value) { return performBiFunctionOperation(tensor, value, NumberUtils.POWER_OF); } static Tensor log(Tensor tensor) { return performFunctionOperation(tensor, NumberUtils.LOG); } static Tensor exp(Tensor tensor) { return performFunctionOperation(tensor, NumberUtils.EXP); } static Tensor sqrt(Tensor tensor) { return performFunctionOperation(tensor, NumberUtils.SQRT); } static Tensor minus(Tensor tensor) { return performFunctionOperation(tensor, NumberUtils.MINUS); } static Tensor min(Tensor tensor, Number value) { return performBiFunctionOperation(tensor, value, NumberUtils.MIN); } static Tensor max(Tensor tensor, Number value) { return performBiFunctionOperation(tensor, value, NumberUtils.MAX); } static Tensor clip(Tensor tensor, Number minValue, Number maxValue) { Tensor firstResult = performBiFunctionOperation(tensor, minValue, NumberUtils.MAX); return performBiFunctionOperation(firstResult, maxValue, NumberUtils.MIN); } private static Tensor performFunctionOperation(Tensor tensor, Map<JNumDataType, Function<Number, Number>> operation) { for (int i = 0; i < tensor.getInternalArraySize(); i++) { Number valueInTensor = tensor.getFromInternalArray(i); tensor.setInInternalArray(i, operation.get(tensor.getDataType()).apply(valueInTensor)); } return tensor; } private static Tensor performBiFunctionOperation(Tensor tensor, Number value, Map<JNumDataType, Map<JNumDataType, BiFunction<Number, Number, Number>>> operation) {
package internals; public class TensorElementMath { static Tensor powerOf(Tensor tensor, Number value) { return performBiFunctionOperation(tensor, value, NumberUtils.POWER_OF); } static Tensor log(Tensor tensor) { return performFunctionOperation(tensor, NumberUtils.LOG); } static Tensor exp(Tensor tensor) { return performFunctionOperation(tensor, NumberUtils.EXP); } static Tensor sqrt(Tensor tensor) { return performFunctionOperation(tensor, NumberUtils.SQRT); } static Tensor minus(Tensor tensor) { return performFunctionOperation(tensor, NumberUtils.MINUS); } static Tensor min(Tensor tensor, Number value) { return performBiFunctionOperation(tensor, value, NumberUtils.MIN); } static Tensor max(Tensor tensor, Number value) { return performBiFunctionOperation(tensor, value, NumberUtils.MAX); } static Tensor clip(Tensor tensor, Number minValue, Number maxValue) { Tensor firstResult = performBiFunctionOperation(tensor, minValue, NumberUtils.MAX); return performBiFunctionOperation(firstResult, maxValue, NumberUtils.MIN); } private static Tensor performFunctionOperation(Tensor tensor, Map<JNumDataType, Function<Number, Number>> operation) { for (int i = 0; i < tensor.getInternalArraySize(); i++) { Number valueInTensor = tensor.getFromInternalArray(i); tensor.setInInternalArray(i, operation.get(tensor.getDataType()).apply(valueInTensor)); } return tensor; } private static Tensor performBiFunctionOperation(Tensor tensor, Number value, Map<JNumDataType, Map<JNumDataType, BiFunction<Number, Number, Number>>> operation) {
JNumDataType valueDataType = TypeUtils.parseDataType(value.getClass());
2
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,873
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;
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;
0
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,146
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();
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();
25
2023-11-12 01:19:17+00:00
24k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/client/gui/hud/items/HudItemAirQuality.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;
19,079
package enviromine.client.gui.hud.items; public class HudItemAirQuality extends HudItem { @Override public String getName() { return "Air Quality"; } public String getNameLoc() { return StatCollector.translateToLocal("options.enviromine.hud.air"); } @Override public String getButtonLabel() { return getNameLoc() + " Bar"; } @Override public Alignment getDefaultAlignment() { return Alignment.BOTTOMRIGHT; } @Override public int getDefaultPosX() { return(((HUDRegistry.screenWidth - 4) - getWidth())); } @Override public int getDefaultPosY() { return(HUDRegistry.screenHeight - 15); } @Override public int getWidth() { return UI_Settings.minimalHud && !rotated ? 0 : 64; } @Override public int getHeight() { return 8; } @Override public boolean isEnabledByDefault() { return EM_Settings.enableAirQ; } @Override public boolean isBlinking() { if(blink() && Gui_EventManager.tracker.airQuality < 25) { return true; } else { return false; } } @Override public int getDefaultID() { return 3; } @Override public void render() { EntityClientPlayerMP ecplayermp = Minecraft.getMinecraft().thePlayer; if( (EM_Settings.dimensionProperties.containsKey(ecplayermp.dimension) && !EM_Settings.dimensionProperties.get(ecplayermp.dimension).trackAirQuality) || !EM_Settings.enableAirQ
package enviromine.client.gui.hud.items; public class HudItemAirQuality extends HudItem { @Override public String getName() { return "Air Quality"; } public String getNameLoc() { return StatCollector.translateToLocal("options.enviromine.hud.air"); } @Override public String getButtonLabel() { return getNameLoc() + " Bar"; } @Override public Alignment getDefaultAlignment() { return Alignment.BOTTOMRIGHT; } @Override public int getDefaultPosX() { return(((HUDRegistry.screenWidth - 4) - getWidth())); } @Override public int getDefaultPosY() { return(HUDRegistry.screenHeight - 15); } @Override public int getWidth() { return UI_Settings.minimalHud && !rotated ? 0 : 64; } @Override public int getHeight() { return 8; } @Override public boolean isEnabledByDefault() { return EM_Settings.enableAirQ; } @Override public boolean isBlinking() { if(blink() && Gui_EventManager.tracker.airQuality < 25) { return true; } else { return false; } } @Override public int getDefaultID() { return 3; } @Override public void render() { EntityClientPlayerMP ecplayermp = Minecraft.getMinecraft().thePlayer; if( (EM_Settings.dimensionProperties.containsKey(ecplayermp.dimension) && !EM_Settings.dimensionProperties.get(ecplayermp.dimension).trackAirQuality) || !EM_Settings.enableAirQ
|| (EM_Settings.matterOverdriveAndroidImmunities && EnviroUtils.isPlayerCurrentlyMOAndroid(ecplayermp))
6
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;
19,975
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;
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);
9
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;
15,131
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() {
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())) {
4
2023-11-18 15:13:30+00:00
24k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/service/impl/RoleServiceImpl.java
[ { "identifier": "BadRequestException", "path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java", "snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) ...
import com.dimple.exception.BadRequestException; import com.dimple.exception.EntityExistException; import com.dimple.modules.system.domain.Menu; import com.dimple.modules.system.domain.Role; import com.dimple.modules.system.domain.User; import com.dimple.modules.system.repository.RoleRepository; import com.dimple.modules.system.repository.UserRepository; import com.dimple.modules.system.service.RoleService; import com.dimple.modules.system.service.dto.RoleDTO; import com.dimple.modules.system.service.dto.RoleQueryCriteria; import com.dimple.modules.system.service.dto.RoleSmallDTO; import com.dimple.modules.system.service.dto.UserDTO; import com.dimple.modules.system.service.mapstruct.RoleMapper; import com.dimple.modules.system.service.mapstruct.RoleSmallMapper; import com.dimple.utils.FileUtil; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.RedisUtils; 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.data.domain.Sort; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors;
14,928
package com.dimple.modules.system.service.impl; /** * @className: RoleServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "role") public class RoleServiceImpl implements RoleService { private final RoleRepository roleRepository; private final RoleMapper roleMapper; private final RoleSmallMapper roleSmallMapper; private final RedisUtils redisUtils; private final UserRepository userRepository; @Override public List<RoleDTO> queryAll() { Sort sort = new Sort(Sort.Direction.ASC, "level"); return roleMapper.toDto(roleRepository.findAll(sort)); } @Override public List<RoleDTO> queryAll(RoleQueryCriteria criteria) { return roleMapper.toDto(roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder))); } @Override public Object queryAll(RoleQueryCriteria criteria, Pageable pageable) { Page<Role> page = roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
package com.dimple.modules.system.service.impl; /** * @className: RoleServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "role") public class RoleServiceImpl implements RoleService { private final RoleRepository roleRepository; private final RoleMapper roleMapper; private final RoleSmallMapper roleSmallMapper; private final RedisUtils redisUtils; private final UserRepository userRepository; @Override public List<RoleDTO> queryAll() { Sort sort = new Sort(Sort.Direction.ASC, "level"); return roleMapper.toDto(roleRepository.findAll(sort)); } @Override public List<RoleDTO> queryAll(RoleQueryCriteria criteria) { return roleMapper.toDto(roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder))); } @Override public Object queryAll(RoleQueryCriteria criteria, Pageable pageable) { Page<Role> page = roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
return PageUtil.toPage(page.map(roleMapper::toDto));
15
2023-11-10 03:30:36+00:00
24k
LazyCoder0101/LazyCoder
ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/component/operation/component/typeset/format/main/MainSetTypeContainer.java
[ { "identifier": "FormatTypeFeatureSelectionModel", "path": "database/src/main/java/com/lazycoder/database/model/featureSelectionModel/FormatTypeFeatureSelectionModel.java", "snippet": "@Data\npublic class FormatTypeFeatureSelectionModel extends AbstractFeatureSelectionModel implements DataFormatType {\n...
import com.lazycoder.database.model.featureSelectionModel.FormatTypeFeatureSelectionModel; import com.lazycoder.lazycodercommon.vo.FunctionUseProperty; import com.lazycoder.service.fileStructure.SysFileStructure; import com.lazycoder.service.service.SysService; import com.lazycoder.uicodegeneration.component.CodeGenerationFrameHolder; import com.lazycoder.uicodegeneration.component.operation.container.MainSetContainer; import com.lazycoder.uicodegeneration.component.operation.container.OpratingContainerInterface; import com.lazycoder.uicodegeneration.component.operation.container.sendparam.MainSetTypeOperatingContainerParam; import com.lazycoder.uicodegeneration.proj.stostr.operation.containerput.MainSetTypeContainerModel; import com.lazycoder.uiutils.folder.Drawer; import com.lazycoder.uiutils.folder.Folder; import com.lazycoder.uiutils.htmlstyte.HTMLText; import com.lazycoder.uiutils.mycomponent.MyButton; import com.lazycoder.uiutils.utils.SysUtil; import com.lazycoder.utils.swing.LazyCoderOptionPane; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import lombok.Getter;
19,995
} } } } } } @Override public Dimension getRequiredDimension() { int w = getDrawer().getContentWidth(), h = (int) (getDrawer().getContentHeight() * getDrawer().getRatio()) + HIDDEN_HEIGHT; return new Dimension(w, h); } /** * 生成事先设置的需要生成的方法 */ private void autoGenerateOpratingContainers() { List<FormatTypeFeatureSelectionModel> list = SysService.MAIN_SET_SERVICE.getFeatureList(mainSetTypeName); if (list != null) { MainSetContainer opratingContainer = null; for (FormatTypeFeatureSelectionModel selectionModel : list) { if (selectionModel.getSetProperty() == FunctionUseProperty.autoGenerateOnce.getSysDictionaryValue() || selectionModel.getSetProperty() == FunctionUseProperty.autoGenerateOnceCanOnlyBeUsedOnce.getSysDictionaryValue()) { opratingContainer = mainSetCodeControlPane.addOpratingPane(selectionModel, true); if (opratingContainer == null) { String text = "必填模板无法添加\"" + selectionModel.getTypeName() + "\"分类的\"" + selectionModel.getShowText() + "\"(" + selectionModel.getTypeSerialNumber() + ")(" + selectionModel.getOrdinal() + ")功能,找不到该功能的对应位置! (✪ω✪)"; String logtext = getClass() + "(添加功能异常)" + "必填模板无法添加\"" + selectionModel.getTypeName() + "\"模块的\"" + selectionModel.getShowText() + "\"(" + selectionModel.getTypeSerialNumber() + ")(" + selectionModel.getOrdinal() + ")功能,找不到该功能的对应标记!"; CodeGenerationFrameHolder.errorLogging(text, logtext); } } else if (selectionModel.getSetProperty() == FunctionUseProperty.autoGenerateOnceAndCanNotDel.getSysDictionaryValue()) { opratingContainer = mainSetCodeControlPane.addOpratingPane(selectionModel, false); if (opratingContainer == null) { String text = "必填模板无法添加\"" + selectionModel.getTypeName() + "\"模块的\"" + selectionModel.getShowText() + "\"(" + selectionModel.getTypeSerialNumber() + ")(" + selectionModel.getOrdinal() + ")功能,找不到该功能的对应位置! (✪ω✪)"; String logtext = getClass() + "(添加功能异常)" + "必填模板无法添加\"" + selectionModel.getTypeName() + "\"模块的\"" + selectionModel.getShowText() + "\"(" + selectionModel.getTypeSerialNumber() + ")(" + selectionModel.getOrdinal() + ")功能,找不到该功能的对应标记!"; CodeGenerationFrameHolder.errorLogging(text, logtext); } } } } } public void autoCollapse(OpratingContainerInterface currentOpratingContainer) { if (currentOpratingContainer.getFirstCommandOpratingContainer() != null && currentOpratingContainer.getFirstCommandOpratingContainer() instanceof MainSetContainer) { MainSetContainer mainSetContainer = (MainSetContainer) currentOpratingContainer.getFirstCommandOpratingContainer(); if (mainSetContainer != null) { if (this.mainSetTypeName.equals(mainSetContainer.getMainSetTypeName())) { expandHiddenPanel(); mainSetCodeControlPane.autoCollapse(currentOpratingContainer); } else { packUpHiddenPanel(); } } } } /** * 负责布局面板组件 */ class MainSetTypeLayout implements LayoutManager { /** * x坐标 */ private int xCoordinates = 0; @Override public void addLayoutComponent(String name, Component comp) { } @Override public void removeLayoutComponent(Component comp) { } @Override public Dimension preferredLayoutSize(Container parent) { return parent.getPreferredSize(); } @Override public Dimension minimumLayoutSize(Container parent) { return parent.getMinimumSize(); } @Override public void layoutContainer(Container parent) { int w = parent.getWidth(), h = parent.getHeight(), dHeight = HIDDEN_HEIGHT; getHiddenButton().setBounds(0, 0, w - MAIN_SET_BUTTON_WIDTH, HIDDEN_HEIGHT); mainSetTypeButton.setBounds(w - MAIN_SET_BUTTON_WIDTH, 0, MAIN_SET_BUTTON_WIDTH, HIDDEN_HEIGHT); // 抽屉只显示抽出的比例 getDrawer().setBounds(xCoordinates, dHeight, w, h - dHeight); } } class MainSetTypeMenuItem extends JMenuItem {// implements Runnable { /** * */ private static final long serialVersionUID = -490331634707256399L; private FormatTypeFeatureSelectionModel featureSelectionModel; public MainSetTypeMenuItem(FormatTypeFeatureSelectionModel featureSelectionModel) { // TODO Auto-generated constructor stub super(featureSelectionModel.getShowText()); this.featureSelectionModel = featureSelectionModel; addActionListener(listener); if (featureSelectionModel != null && ("[]".equals(featureSelectionModel.getNoteListParam()) == false)) {
package com.lazycoder.uicodegeneration.component.operation.component.typeset.format.main; public class MainSetTypeContainer extends Folder { public final static double PROPORTION = 0.87 * 0.35; private static ImageIcon moreIcon = new ImageIcon( SysFileStructure.getImageFolder().getAbsolutePath() + File.separator + "CodeGeneration" + File.separator + "更多.png"); /** * */ private static final long serialVersionUID = -5089021262623704531L; private static final int HIDDEN_HEIGHT = 30, MAIN_SET_TYPE_JSP_HEIGHT = 350, MAIN_SET_BUTTON_WIDTH = 80; private MainSetTypeHiddenButton hiddenButton; private MainSetCodeControlPane mainSetCodeControlPane; private JScrollPane mainSetCodeControlJSP; private MyButton mainSetTypeButton; private JPopupMenu menu; @Getter private String mainSetTypeName = ""; private MainSetTypeOperatingContainerParam mainSetTypeOperatingContainerParam; public MainSetTypeContainer(MainSetTypeOperatingContainerParam mainSetTypeOperatingContainerParam, boolean expanded) { // TODO Auto-generated constructor stub super(); this.mainSetTypeOperatingContainerParam = mainSetTypeOperatingContainerParam; this.mainSetTypeName = mainSetTypeOperatingContainerParam.getMainSetType(); init(expanded); autoGenerateOpratingContainers(); } public MainSetTypeContainer(MainSetTypeOperatingContainerParam mainSetTypeOperatingContainerParam, MainSetTypeContainerModel codeControlPaneModel, boolean expanded) { // TODO Auto-generated constructor stub this.mainSetTypeOperatingContainerParam = mainSetTypeOperatingContainerParam; this.mainSetTypeName = mainSetTypeOperatingContainerParam.getMainSetType(); init(expanded); mainSetCodeControlPane.restoreContent(codeControlPaneModel); } private void init(boolean expanded) { int width = (int) (PROPORTION * SysUtil.SCREEN_SIZE.getWidth()); setLayout(new MainSetTypeLayout()); menu = new JPopupMenu(); hiddenButton = new MainSetTypeHiddenButton(mainSetTypeName, expanded) { @Override public void doSomethingWhenMousePressed(boolean expanded) { mainSetCodeControlPane.collapseThis(); super.doSomethingWhenMousePressed(expanded); } // @Override // public void doClick() { // mainSetCodeControlPane.collapseThis(); // super.doClick(); // } }; hiddenButton.setSize(width, HIDDEN_HEIGHT); setHiddenButton(hiddenButton); add(hiddenButton); mainSetTypeButton = new MyButton(moreIcon); mainSetTypeButton.setSize(MAIN_SET_BUTTON_WIDTH, HIDDEN_HEIGHT); mainSetTypeButton.addMouseListener(mouseAdapter); add(mainSetTypeButton); mainSetCodeControlPane = new MainSetCodeControlPane(mainSetTypeOperatingContainerParam); mainSetCodeControlJSP = mainSetCodeControlPane.getParentScrollPane(); mainSetCodeControlJSP.setSize(width, MAIN_SET_TYPE_JSP_HEIGHT); Drawer drawer = new Drawer(expanded ? 1 : 0, mainSetCodeControlJSP); this.setDrawer(drawer); add(drawer); } private MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub updateMenuItems(); menu.show(mainSetTypeButton, e.getX(), e.getY()); super.mouseEntered(e); } }; public void delModuleOpratingContainerFromComponent(String moduleId) { mainSetCodeControlPane.delModuleOpratingContainerFromComponent(moduleId); } public void delThis() { mainSetCodeControlPane.delThis(); } public ArrayList<OpratingContainerInterface> getAllOpratingContainer() { // TODO Auto-generated method stub return mainSetCodeControlPane.getAllOpratingContainer(); } public void collapseThis() { // TODO Auto-generated method stub mainSetCodeControlPane.collapseThis(); } public MainSetTypeContainerModel getFormatStructureModel() { MainSetTypeContainerModel model = mainSetCodeControlPane.getFormatStructureModel(); model.setMainSetTypeName(mainSetTypeName); return model; } private void updateMenuItems() { menu.removeAll(); List<FormatTypeFeatureSelectionModel> list = SysService.MAIN_SET_SERVICE.getFeatureList(mainSetTypeName); if (list != null) { MainSetTypeMenuItem tempItem; for (FormatTypeFeatureSelectionModel tempModel : list) { tempItem = new MainSetTypeMenuItem(tempModel); menu.add(tempItem); //如果该菜单是只能添加一次的和自动生成只能添加一次的,查看当前添加的功能里面有没有和添加这个菜单对应的功能,有的话,将该菜单失能 if (tempModel.getSetProperty() == FunctionUseProperty.onlyBeUsedOnce.getSysDictionaryValue() || tempModel.getSetProperty() == FunctionUseProperty.autoGenerateOnceCanOnlyBeUsedOnce.getSysDictionaryValue()) { MainSetContainer theOpratingContainer; ArrayList<OpratingContainerInterface> opratingContainerList = mainSetCodeControlPane.getAllOpratingContainerListInThisPane(); for (OpratingContainerInterface opratingContainer : opratingContainerList) { if (opratingContainer instanceof MainSetContainer) { theOpratingContainer = (MainSetContainer) opratingContainer; if (tempModel.getOrdinal() == theOpratingContainer.getOrdinalInUserDB()) { tempItem.setEnabled(false); break; } } } } } } } @Override public Dimension getRequiredDimension() { int w = getDrawer().getContentWidth(), h = (int) (getDrawer().getContentHeight() * getDrawer().getRatio()) + HIDDEN_HEIGHT; return new Dimension(w, h); } /** * 生成事先设置的需要生成的方法 */ private void autoGenerateOpratingContainers() { List<FormatTypeFeatureSelectionModel> list = SysService.MAIN_SET_SERVICE.getFeatureList(mainSetTypeName); if (list != null) { MainSetContainer opratingContainer = null; for (FormatTypeFeatureSelectionModel selectionModel : list) { if (selectionModel.getSetProperty() == FunctionUseProperty.autoGenerateOnce.getSysDictionaryValue() || selectionModel.getSetProperty() == FunctionUseProperty.autoGenerateOnceCanOnlyBeUsedOnce.getSysDictionaryValue()) { opratingContainer = mainSetCodeControlPane.addOpratingPane(selectionModel, true); if (opratingContainer == null) { String text = "必填模板无法添加\"" + selectionModel.getTypeName() + "\"分类的\"" + selectionModel.getShowText() + "\"(" + selectionModel.getTypeSerialNumber() + ")(" + selectionModel.getOrdinal() + ")功能,找不到该功能的对应位置! (✪ω✪)"; String logtext = getClass() + "(添加功能异常)" + "必填模板无法添加\"" + selectionModel.getTypeName() + "\"模块的\"" + selectionModel.getShowText() + "\"(" + selectionModel.getTypeSerialNumber() + ")(" + selectionModel.getOrdinal() + ")功能,找不到该功能的对应标记!"; CodeGenerationFrameHolder.errorLogging(text, logtext); } } else if (selectionModel.getSetProperty() == FunctionUseProperty.autoGenerateOnceAndCanNotDel.getSysDictionaryValue()) { opratingContainer = mainSetCodeControlPane.addOpratingPane(selectionModel, false); if (opratingContainer == null) { String text = "必填模板无法添加\"" + selectionModel.getTypeName() + "\"模块的\"" + selectionModel.getShowText() + "\"(" + selectionModel.getTypeSerialNumber() + ")(" + selectionModel.getOrdinal() + ")功能,找不到该功能的对应位置! (✪ω✪)"; String logtext = getClass() + "(添加功能异常)" + "必填模板无法添加\"" + selectionModel.getTypeName() + "\"模块的\"" + selectionModel.getShowText() + "\"(" + selectionModel.getTypeSerialNumber() + ")(" + selectionModel.getOrdinal() + ")功能,找不到该功能的对应标记!"; CodeGenerationFrameHolder.errorLogging(text, logtext); } } } } } public void autoCollapse(OpratingContainerInterface currentOpratingContainer) { if (currentOpratingContainer.getFirstCommandOpratingContainer() != null && currentOpratingContainer.getFirstCommandOpratingContainer() instanceof MainSetContainer) { MainSetContainer mainSetContainer = (MainSetContainer) currentOpratingContainer.getFirstCommandOpratingContainer(); if (mainSetContainer != null) { if (this.mainSetTypeName.equals(mainSetContainer.getMainSetTypeName())) { expandHiddenPanel(); mainSetCodeControlPane.autoCollapse(currentOpratingContainer); } else { packUpHiddenPanel(); } } } } /** * 负责布局面板组件 */ class MainSetTypeLayout implements LayoutManager { /** * x坐标 */ private int xCoordinates = 0; @Override public void addLayoutComponent(String name, Component comp) { } @Override public void removeLayoutComponent(Component comp) { } @Override public Dimension preferredLayoutSize(Container parent) { return parent.getPreferredSize(); } @Override public Dimension minimumLayoutSize(Container parent) { return parent.getMinimumSize(); } @Override public void layoutContainer(Container parent) { int w = parent.getWidth(), h = parent.getHeight(), dHeight = HIDDEN_HEIGHT; getHiddenButton().setBounds(0, 0, w - MAIN_SET_BUTTON_WIDTH, HIDDEN_HEIGHT); mainSetTypeButton.setBounds(w - MAIN_SET_BUTTON_WIDTH, 0, MAIN_SET_BUTTON_WIDTH, HIDDEN_HEIGHT); // 抽屉只显示抽出的比例 getDrawer().setBounds(xCoordinates, dHeight, w, h - dHeight); } } class MainSetTypeMenuItem extends JMenuItem {// implements Runnable { /** * */ private static final long serialVersionUID = -490331634707256399L; private FormatTypeFeatureSelectionModel featureSelectionModel; public MainSetTypeMenuItem(FormatTypeFeatureSelectionModel featureSelectionModel) { // TODO Auto-generated constructor stub super(featureSelectionModel.getShowText()); this.featureSelectionModel = featureSelectionModel; addActionListener(listener); if (featureSelectionModel != null && ("[]".equals(featureSelectionModel.getNoteListParam()) == false)) {
HTMLText noteTip = CodeGenerationFrameHolder.getNoteToolTip(featureSelectionModel.getNoteListParam());
11
2023-11-16 11:55:06+00:00
24k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506/KSBatchSwitch.java
[ { "identifier": "ByteArrayBuffer", "path": "app/src/main/java/kr/or/kashi/hde/base/ByteArrayBuffer.java", "snippet": "public final class ByteArrayBuffer {\n private static final int INITIAL_CAPACITY = 16;\n private static final int CAPACITY_INCREMENT = 8;\n\n private byte[] mBuffer;\n privat...
import kr.or.kashi.hde.ksx4506.KSAddress; import kr.or.kashi.hde.ksx4506.KSDeviceContextBase; import kr.or.kashi.hde.ksx4506.KSPacket; import java.util.Map; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.util.Log; import kr.or.kashi.hde.base.ByteArrayBuffer; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.base.PropertyTask; import kr.or.kashi.hde.base.PropertyValue; import kr.or.kashi.hde.HomePacket; import kr.or.kashi.hde.MainContext; import kr.or.kashi.hde.HomeDevice; import kr.or.kashi.hde.device.BatchSwitch;
19,059
data.append(packet.data[0]); // same with the byte in the request. sendPacket(createPacket(CMD_SWITCH_SETTING_RESULT_RSP, data.toArray())); return PARSE_OK_STATE_UPDATED; } protected int parseSwitchSettingResultRsp(KSPacket packet, PropertyMap outProps) { // Ignore return PARSE_OK_STATE_UPDATED; } protected void makeStatusRspBytes(PropertyMap props, ByteArrayBuffer outData) { final long states = props.get(BatchSwitch.PROP_SWITCH_STATES, Long.class); int data = 0; if (mGasLockingReqTriggered) data |= (1 << 0); if (mOutingSettingReqTriggered) data |= (1 << 1); if ((states & BatchSwitch.Switch.BATCH_LIGHT_OFF) == 0) data |= (1 << 2); if ((states & BatchSwitch.Switch.POWER_SAVING) == 0) data |= (1 << 3); if (mElevatorUpCallReqTriggered) data |= (1 << 4); if (mElevatorDownCallReqTriggered) data |= (1 << 5); outData.append(data); } protected @ParseResult int parseStatusRspBytes(byte[] data, PropertyMap outProps) { long curStates = (long) outProps.get(BatchSwitch.PROP_SWITCH_STATES).getValue(); long newStates = curStates; boolean newReqTriggered = false; if ((data[1] & (1 << 0)) != 0) { if (mGasLockingReqTriggered == false) { mGasLockingReqTriggered = true; mSavedGasLocking = (curStates & BatchSwitch.Switch.GAS_LOCKING) != 0; newReqTriggered |= true; } newStates |= BatchSwitch.Switch.GAS_LOCKING; if (DBG) Log.d(TAG, "parse-usr-req-frame: gas_locking req received"); } else { if (mGasLockingReqTriggered) { if (DBG) Log.d(TAG, "parse-usr-req-frame: gas_locking req cleared, but still waitting for confirming"); } } if ((data[1] & (1 << 1)) != 0) { if (mOutingSettingReqTriggered == false) { mOutingSettingReqTriggered = true; mSavedOutingSetting = (curStates & BatchSwitch.Switch.OUTING_SETTING) != 0; newReqTriggered |= true; } newStates |= BatchSwitch.Switch.OUTING_SETTING; if (DBG) Log.d(TAG, "parse-usr-req-frame: outing_setting req received"); } else { if (mOutingSettingReqTriggered) { if (DBG) Log.d(TAG, "parse-usr-req-frame: outing_setting req cleared, but still waitting for confirming"); } } if ((data[1] & (1 << 2)) != 0) { newStates &= ~BatchSwitch.Switch.BATCH_LIGHT_OFF; } else { newStates |= BatchSwitch.Switch.BATCH_LIGHT_OFF; } if ((data[1] & (1 << 3)) != 0) { newStates &= ~BatchSwitch.Switch.POWER_SAVING; } else { newStates |= BatchSwitch.Switch.POWER_SAVING; } if ((data[1] & (1 << 4)) != 0) { newStates |= BatchSwitch.Switch.ELEVATOR_UP_CALL; if (mElevatorUpCallReqTriggered == false) { mElevatorUpCallReqTriggered = true; newReqTriggered |= true; } if (DBG) Log.d(TAG, "parse-usr-req-frame: elevator_up_call req received"); } else { if (mElevatorUpCallReqTriggered) { if (DBG) Log.d(TAG, "parse-usr-req-frame: elevator_call req cleared, but still waitting for confirming"); } } if ((data[1] & (1 << 5)) != 0) { newStates |= BatchSwitch.Switch.ELEVATOR_DOWN_CALL; if (mElevatorDownCallReqTriggered == false) { mElevatorDownCallReqTriggered = true; newReqTriggered |= true; } if (DBG) Log.d(TAG, "parse-usr-req-frame: elevator_down_call req received"); } else { if (mElevatorDownCallReqTriggered) { if (DBG) Log.d(TAG, "parse-usr-req-frame: elevator_call req cleared, but still waitting for confirming"); } } if (newReqTriggered) { startTimeoutIfReqTriggered(); } if (newStates == curStates) { return PARSE_OK_NONE; // nothing changed } // Update switch state. outProps.put(BatchSwitch.PROP_SWITCH_STATES, newStates); // Update common on/off state too. final boolean isOn = ((newStates & BatchSwitch.Switch.BATCH_LIGHT_OFF) == 0); outProps.put(HomeDevice.PROP_ONOFF, isOn); return PARSE_OK_STATE_UPDATED; } protected boolean onSetSwitchStatesTask(PropertyMap reqProps, PropertyMap outProps) { long curStates = (Long) getProperty(BatchSwitch.PROP_SWITCH_STATES).getValue(); long newStates = (Long) reqProps.get(BatchSwitch.PROP_SWITCH_STATES).getValue(); long difStates = curStates ^ newStates;
/* * 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; /** * [KS X 4506] The batch-switch implementation for BatchSwitch */ public class KSBatchSwitch extends KSDeviceContextBase { private static final String TAG = "KSBatchSwitch"; private static final boolean DBG = true; // [HACK/DEBUG] Some devices doesn't consider the failure cases. public static final boolean HACK_NEVER_FAIL = false; public static final int CMD_FULL_CONTROL_REQ = 0x42; // sub-id : 0F or FF public static final int CMD_SWITCH_SETTING_RESULT_REQ = 0x43; public static final int CMD_SWITCH_SETTING_RESULT_RSP = 0xC3; public static final int CMD_ELEVATOR_FLOOR_DISPLAY_REQ = 0x44; public static final int CMD_ELEVATOR_FLOOR_DISPLAY_RSP = 0xC4; private final Handler mReqTimeoutHandler; private static final long REQ_TIMEOUT = 7 * 1000L; private boolean mGasLockingReqTriggered = false; private boolean mOutingSettingReqTriggered = false; private boolean mElevatorUpCallReqTriggered = false; private boolean mElevatorDownCallReqTriggered = false; private boolean mSavedGasLocking = false; private boolean mSavedOutingSetting = false; public KSBatchSwitch(MainContext mainContext, Map defaultProps) { super(mainContext, defaultProps, BatchSwitch.class); mReqTimeoutHandler = new Handler(Looper.getMainLooper()); if (isMaster()) { // Register the tasks to be performed when specific property changes. setPropertyTask(HomeDevice.PROP_ONOFF, this::onSetSwitchStatesTask); setPropertyTask(BatchSwitch.PROP_SWITCH_STATES, this::onSetSwitchStatesTask); setPropertyTask(BatchSwitch.PROP_DISPLAY_STATES, this::onSetDisplayStatesTask); } else { setPropertyTask(HomeDevice.PROP_ONOFF, this::onSetSwitchStatesTaskForSlave); setPropertyTask(BatchSwitch.PROP_SWITCH_STATES, this::onSetSwitchStatesTaskForSlave); } } protected int getCapabilities() { return CAP_STATUS_SINGLE | CAP_CHARAC_SINGLE; } @Override public void onDetachedFromStream() { mReqTimeoutHandler.removeCallbacksAndMessages(null); mGasLockingReqTriggered = false; mOutingSettingReqTriggered = false; mElevatorUpCallReqTriggered = false; mElevatorDownCallReqTriggered = false; super.onDetachedFromStream(); } @Override public @ParseResult int parsePayload(KSPacket packet, PropertyMap outProps) { switch (packet.commandType) { case CMD_SWITCH_SETTING_RESULT_REQ: return parseSwitchSettingResultReq(packet, outProps); case CMD_SWITCH_SETTING_RESULT_RSP: return parseSwitchSettingResultRsp(packet, outProps); case CMD_ELEVATOR_FLOOR_DISPLAY_RSP: { // Same with the response of status. return parseStatusRspBytes(packet.data, outProps); } } return super.parsePayload(packet, outProps); } @Override protected @ParseResult int parseStatusReq(KSPacket packet, PropertyMap outProps) { parseStatusReqData(packet.data, outProps); ByteArrayBuffer data = new ByteArrayBuffer(); data.append(0); // no error makeStatusRspBytes(getReadPropertyMap(), data); sendPacket(createPacket(CMD_STATUS_RSP, data.toArray())); return PARSE_OK_STATE_UPDATED; } @Override protected @ParseResult int parseStatusRsp(KSPacket packet, PropertyMap outProps) { if (packet.data.length < 2) { if (DBG) Log.w(TAG, "parse-status-rsp: wrong size of data " + packet.data.length); return PARSE_ERROR_MALFORMED_PACKET; } final int error = packet.data[0] & 0xFF; if (error != 0) { if (DBG) Log.d(TAG, "parse-status-rsp: error occurred! " + error); onErrorOccurred(HomeDevice.Error.UNKNOWN); return PARSE_OK_ERROR_RECEIVED; } return parseStatusRspBytes(packet.data, outProps); } @Override protected @ParseResult int parseCharacteristicReq(KSPacket packet, PropertyMap outProps) { // No data to parse from request packet. final PropertyMap props = getReadPropertyMap(); final ByteArrayBuffer data = new ByteArrayBuffer(); data.append(0); // no error final long supportedSwitches = outProps.get(BatchSwitch.PROP_SUPPORTED_SWITCHES, Long.class); final long supportedDisplays = outProps.get(BatchSwitch.PROP_SUPPORTED_DISPLAYS, Long.class); int supportData = 0; if ((supportedSwitches | BatchSwitch.Switch.GAS_LOCKING) != 0) supportData |= (1 << 0); if ((supportedSwitches | BatchSwitch.Switch.OUTING_SETTING) != 0) supportData |= (1 << 1); if ((supportedSwitches | BatchSwitch.Switch.POWER_SAVING) != 0) supportData |= (1 << 2); if ((supportedSwitches | BatchSwitch.Switch.ELEVATOR_UP_CALL) != 0) supportData |= (1 << 3); if ((supportedSwitches | BatchSwitch.Switch.ELEVATOR_DOWN_CALL) != 0) supportData |= (1 << 3); if ((supportedDisplays | BatchSwitch.Display.ELEVATOR_FLOOR) != 0) supportData |= (1 << 4); data.append(supportData); data.append(0); // Reserved // Send response packet. sendPacket(createPacket(CMD_CHARACTERISTIC_RSP, data.toArray())); return PARSE_OK_STATE_UPDATED; } @Override protected @ParseResult int parseCharacteristicRsp(KSPacket packet, PropertyMap outProps) { // TODO: check if single device, group is not allowed if (packet.data.length < 2) { if (DBG) Log.w(TAG, "parse-chr-rsp: wrong size of data " + packet.data.length); return PARSE_ERROR_MALFORMED_PACKET; } final int error = packet.data[0] & 0xFF; if (error != 0) { if (DBG) Log.d(TAG, "parse-chr-rsp: error occurred! " + error); onErrorOccurred(HomeDevice.Error.UNKNOWN); return PARSE_OK_ERROR_RECEIVED; } long supportedSwitches = 0; long supportedDisplays = 0; final int data1 = packet.data[1] & 0xFF; supportedSwitches |= BatchSwitch.Switch.BATCH_LIGHT_OFF; if ((data1 & (1 << 0)) != 0) supportedSwitches |= (BatchSwitch.Switch.GAS_LOCKING); if ((data1 & (1 << 1)) != 0) supportedSwitches |= (BatchSwitch.Switch.OUTING_SETTING); if ((data1 & (1 << 2)) != 0) supportedSwitches |= (BatchSwitch.Switch.POWER_SAVING); if ((data1 & (1 << 3)) != 0) supportedSwitches |= (BatchSwitch.Switch.ELEVATOR_UP_CALL | BatchSwitch.Switch.ELEVATOR_DOWN_CALL); if ((data1 & (1 << 4)) != 0) supportedDisplays |= (BatchSwitch.Display.ELEVATOR_FLOOR); outProps.put(BatchSwitch.PROP_SUPPORTED_SWITCHES, supportedSwitches); outProps.put(BatchSwitch.PROP_SUPPORTED_DISPLAYS, supportedDisplays); // Set the display states also on if supported. outProps.put(BatchSwitch.PROP_DISPLAY_STATES, supportedDisplays); return PARSE_OK_PEER_DETECTED; } @Override protected int parseSingleControlReq(KSPacket packet, PropertyMap outProps) { // Parse requst packet. parseSingleControlReqData(packet.data, outProps); // Send response packet. final ByteArrayBuffer data = new ByteArrayBuffer(); data.append(0); // no error makeStatusRspBytes(outProps, data); sendPacket(createPacket(CMD_SINGLE_CONTROL_RSP, data.toArray())); return PARSE_OK_STATE_UPDATED; } @Override protected @ParseResult int parseSingleControlRsp(KSPacket packet, PropertyMap outProps) { final int error = packet.data[0] & 0xFF; if (error != 0) { if (DBG) Log.d(TAG, "parse-single-ctrl-rsp: error occurred! " + error); onErrorOccurred(HomeDevice.Error.UNKNOWN); return PARSE_OK_ERROR_RECEIVED; } // HACK: Don't parse the response packet of control request because // some device return wrong state although we're expecting at least // it would be maintaining the last value if the device can't apply // the request immediately. // --- BLOCKED BELOW ---------------------------------------------- // parseStatusRspBytes(packet.data, outProps); return PARSE_OK_ACTION_PERFORMED; } protected int parseSwitchSettingResultReq(KSPacket packet, PropertyMap outProps) { // Parse request packet. parseSwitchSettingResultData(packet.data, outProps); // Send response packet. final ByteArrayBuffer data = new ByteArrayBuffer(); data.append(0); // no error data.append(packet.data[0]); // same with the byte in the request. sendPacket(createPacket(CMD_SWITCH_SETTING_RESULT_RSP, data.toArray())); return PARSE_OK_STATE_UPDATED; } protected int parseSwitchSettingResultRsp(KSPacket packet, PropertyMap outProps) { // Ignore return PARSE_OK_STATE_UPDATED; } protected void makeStatusRspBytes(PropertyMap props, ByteArrayBuffer outData) { final long states = props.get(BatchSwitch.PROP_SWITCH_STATES, Long.class); int data = 0; if (mGasLockingReqTriggered) data |= (1 << 0); if (mOutingSettingReqTriggered) data |= (1 << 1); if ((states & BatchSwitch.Switch.BATCH_LIGHT_OFF) == 0) data |= (1 << 2); if ((states & BatchSwitch.Switch.POWER_SAVING) == 0) data |= (1 << 3); if (mElevatorUpCallReqTriggered) data |= (1 << 4); if (mElevatorDownCallReqTriggered) data |= (1 << 5); outData.append(data); } protected @ParseResult int parseStatusRspBytes(byte[] data, PropertyMap outProps) { long curStates = (long) outProps.get(BatchSwitch.PROP_SWITCH_STATES).getValue(); long newStates = curStates; boolean newReqTriggered = false; if ((data[1] & (1 << 0)) != 0) { if (mGasLockingReqTriggered == false) { mGasLockingReqTriggered = true; mSavedGasLocking = (curStates & BatchSwitch.Switch.GAS_LOCKING) != 0; newReqTriggered |= true; } newStates |= BatchSwitch.Switch.GAS_LOCKING; if (DBG) Log.d(TAG, "parse-usr-req-frame: gas_locking req received"); } else { if (mGasLockingReqTriggered) { if (DBG) Log.d(TAG, "parse-usr-req-frame: gas_locking req cleared, but still waitting for confirming"); } } if ((data[1] & (1 << 1)) != 0) { if (mOutingSettingReqTriggered == false) { mOutingSettingReqTriggered = true; mSavedOutingSetting = (curStates & BatchSwitch.Switch.OUTING_SETTING) != 0; newReqTriggered |= true; } newStates |= BatchSwitch.Switch.OUTING_SETTING; if (DBG) Log.d(TAG, "parse-usr-req-frame: outing_setting req received"); } else { if (mOutingSettingReqTriggered) { if (DBG) Log.d(TAG, "parse-usr-req-frame: outing_setting req cleared, but still waitting for confirming"); } } if ((data[1] & (1 << 2)) != 0) { newStates &= ~BatchSwitch.Switch.BATCH_LIGHT_OFF; } else { newStates |= BatchSwitch.Switch.BATCH_LIGHT_OFF; } if ((data[1] & (1 << 3)) != 0) { newStates &= ~BatchSwitch.Switch.POWER_SAVING; } else { newStates |= BatchSwitch.Switch.POWER_SAVING; } if ((data[1] & (1 << 4)) != 0) { newStates |= BatchSwitch.Switch.ELEVATOR_UP_CALL; if (mElevatorUpCallReqTriggered == false) { mElevatorUpCallReqTriggered = true; newReqTriggered |= true; } if (DBG) Log.d(TAG, "parse-usr-req-frame: elevator_up_call req received"); } else { if (mElevatorUpCallReqTriggered) { if (DBG) Log.d(TAG, "parse-usr-req-frame: elevator_call req cleared, but still waitting for confirming"); } } if ((data[1] & (1 << 5)) != 0) { newStates |= BatchSwitch.Switch.ELEVATOR_DOWN_CALL; if (mElevatorDownCallReqTriggered == false) { mElevatorDownCallReqTriggered = true; newReqTriggered |= true; } if (DBG) Log.d(TAG, "parse-usr-req-frame: elevator_down_call req received"); } else { if (mElevatorDownCallReqTriggered) { if (DBG) Log.d(TAG, "parse-usr-req-frame: elevator_call req cleared, but still waitting for confirming"); } } if (newReqTriggered) { startTimeoutIfReqTriggered(); } if (newStates == curStates) { return PARSE_OK_NONE; // nothing changed } // Update switch state. outProps.put(BatchSwitch.PROP_SWITCH_STATES, newStates); // Update common on/off state too. final boolean isOn = ((newStates & BatchSwitch.Switch.BATCH_LIGHT_OFF) == 0); outProps.put(HomeDevice.PROP_ONOFF, isOn); return PARSE_OK_STATE_UPDATED; } protected boolean onSetSwitchStatesTask(PropertyMap reqProps, PropertyMap outProps) { long curStates = (Long) getProperty(BatchSwitch.PROP_SWITCH_STATES).getValue(); long newStates = (Long) reqProps.get(BatchSwitch.PROP_SWITCH_STATES).getValue(); long difStates = curStates ^ newStates;
final KSAddress address = (KSAddress)getAddress();
8
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,037
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();
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();
3
2023-11-16 09:05:44+00:00
24k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/events/listeners/UtilityListener.java
[ { "identifier": "SkyBlock", "path": "src/main/java/com/sweattypalms/skyblock/SkyBlock.java", "snippet": "public final class SkyBlock extends JavaPlugin {\n\n private static SkyBlock instance;\n\n public static SkyBlock getInstance() {\n return instance;\n }\n\n public boolean debug = ...
import com.sweattypalms.skyblock.SkyBlock; import com.sweattypalms.skyblock.api.sequence.Sequence; import com.sweattypalms.skyblock.api.sequence.SequenceAction; import com.sweattypalms.skyblock.core.enchants.EnchantManager; import com.sweattypalms.skyblock.core.events.def.SkyblockDeathEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockInteractEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockMobDamagePlayerEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockPlayerDamageEntityEvent; import com.sweattypalms.skyblock.core.helpers.PlaceholderFormatter; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import com.sweattypalms.skyblock.core.items.builder.abilities.TriggerType; import com.sweattypalms.skyblock.core.items.builder.armor.IHeadHelmet; import com.sweattypalms.skyblock.core.items.builder.item.IShortBow; import com.sweattypalms.skyblock.core.mobs.builder.ISkyblockMob; import com.sweattypalms.skyblock.core.mobs.builder.dragons.DragonManager; import com.sweattypalms.skyblock.core.mobs.builder.dragons.IEndDragon; import com.sweattypalms.skyblock.core.mobs.builder.dragons.loot.IDragonLoot; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import net.minecraft.server.v1_8_R3.EntityLiving; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEnderDragonPart; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftItem; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftLivingEntity; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.*; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Text; import java.util.List;
17,431
} @EventHandler public void equipHelmetThroughEvent(PlayerInteractEvent event) { Player player = event.getPlayer(); ItemStack itemInHand = player.getInventory().getItemInHand(); SkyblockItem skyblockItem = SkyblockItem.fromItemStack(itemInHand); if (skyblockItem == null) return; if (skyblockItem.getItemType() != SkyblockItemType.HELMET || !(skyblockItem instanceof IHeadHelmet)) return; if (player.getInventory().getHelmet() == null || player.getInventory().getHelmet().getType() == Material.AIR) { player.getInventory().setHelmet(itemInHand); player.getInventory().setItemInHand(null); } } /** * For forwarding the EntityDeathEvent to the SkyblockDeathEvent * * @param event EntityDeathEvent */ @EventHandler(priority = EventPriority.LOW) public void onDeathBukkit(EntityDeathEvent event) { LivingEntity livingEntity = event.getEntity(); event.setDroppedExp(0); event.getDrops().clear(); if (livingEntity instanceof Player player) { SkyblockDeathEvent _event = new SkyblockDeathEvent(player, SkyblockDeathEvent.DeathCause.OTHER); Bukkit.getPluginManager().callEvent(_event); return; } EntityLiving entityLiving = ((CraftLivingEntity) event.getEntity()).getHandle(); if (!(entityLiving instanceof ISkyblockMob skyblockMob)) return; SkyblockDeathEvent _event = getSkyblockDeathEvent(livingEntity); SkyBlock.getInstance().getServer().getPluginManager().callEvent(_event); } @EventHandler public void playerDeathBukkit(PlayerDeathEvent event) { event.setDeathMessage(null); event.setKeepInventory(true); event.setKeepLevel(true); event.setDroppedExp(0); new Sequence().add( new SequenceAction(() -> { event.getEntity().spigot().respawn(); event.getEntity().updateInventory(); }, 1) ).start(); } @EventHandler public void onPlayerRegainHealth(EntityRegainHealthEvent event) { if (event.getRegainReason() == EntityRegainHealthEvent.RegainReason.SATIATED || event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN) event.setCancelled(true); } @EventHandler public void onBowPull(EntityShootBowEvent event) { if (!(event.getEntity() instanceof Player player)) return; SkyblockPlayer skyblockPlayer = SkyblockPlayer.getSkyblockPlayer(player); double bowPull = event.getForce(); skyblockPlayer.getStatsManager().setMaxStat(Stats.BOW_PULL, bowPull); if (skyblockPlayer.getInventoryManager().getSkyblockItemInHand() instanceof IShortBow) { event.setCancelled(true); } } @EventHandler public void projectileHitEvent(ProjectileHitEvent event) { List<LivingEntity> nearby = event.getEntity().getNearbyEntities(1, 1, 1).stream().map(entity -> entity instanceof LivingEntity ? (LivingEntity) entity : null).filter(entity -> !(entity instanceof ArmorStand)).toList(); if (nearby.size() == 0) return; LivingEntity en = nearby.get(0); if (event.getEntity() instanceof FallingBlock || en instanceof FallingBlock) return; if (event.getEntity().getShooter() == null) return; LivingEntity shooter = (LivingEntity) event.getEntity().getShooter(); if (shooter instanceof Player && en instanceof Player) { return; } EntityLiving entityLiving = ((CraftLivingEntity) shooter).getHandle(); if (entityLiving instanceof ISkyblockMob skyblockMob && en instanceof Player player) { SkyblockMobDamagePlayerEvent skyblockMobDamagePlayerEvent = new SkyblockMobDamagePlayerEvent( player, shooter ); Bukkit.getPluginManager().callEvent(skyblockMobDamagePlayerEvent); return; } LivingEntity hitEntity = en instanceof EnderDragonPart ? ((EnderDragonPart) en).getParent() : (LivingEntity) en; if (shooter instanceof Player player && ((CraftLivingEntity) hitEntity).getHandle() instanceof ISkyblockMob skyblockMob) { SkyblockPlayerDamageEntityEvent skyblockPlayerDamageEntityEvent = new SkyblockPlayerDamageEntityEvent( hitEntity, player, SkyblockPlayerDamageEntityEvent.DamageType.ARROW ); Bukkit.getPluginManager().callEvent(skyblockPlayerDamageEntityEvent); return; } } @EventHandler public void pickupItemEvent(PlayerPickupItemEvent event) { Player player = event.getPlayer(); Item item = event.getItem(); ItemStack itemStack = item.getItemStack();
package com.sweattypalms.skyblock.core.events.listeners; public class UtilityListener implements Listener { @NotNull private static SkyblockDeathEvent getSkyblockDeathEvent(LivingEntity livingEntity) { SkyblockDeathEvent.DeathCause reason; EntityDamageEvent lastDamageCause = livingEntity.getLastDamageCause(); if (lastDamageCause == null) { reason = SkyblockDeathEvent.DeathCause.OTHER; } else { reason = SkyblockDeathEvent.DeathCause.getCause(lastDamageCause.getCause()); } SkyblockDeathEvent _event; if (reason == SkyblockDeathEvent.DeathCause.ENTITY) { _event = new SkyblockDeathEvent(livingEntity.getKiller(), livingEntity); } else { _event = new SkyblockDeathEvent(livingEntity, reason); } return _event; } @EventHandler public void onJoin(PlayerJoinEvent event) { String message = "$eWelcome to $cSkyblock$e!"; message = PlaceholderFormatter.format(message); event.getPlayer().sendMessage(message); event.setJoinMessage(null); if (SkyblockPlayer.getSkyblockPlayer(event.getPlayer()) != null) return; new SkyblockPlayer(event.getPlayer()); } @EventHandler(priority = EventPriority.LOW) public void interactEventForwarder(PlayerInteractEvent event) { Player player = event.getPlayer(); SkyblockPlayer skyblockPlayer = SkyblockPlayer.getSkyblockPlayer(player); TriggerType triggerType = TriggerType.getTriggerType(event.getAction()); if (triggerType == null || triggerType == TriggerType.NONE) return; SkyblockInteractEvent skyblockInteractEvent = new SkyblockInteractEvent(skyblockPlayer, triggerType); if (event.getClickedBlock() != null) { skyblockInteractEvent.setInteractedBlock(event.getClickedBlock()); } SkyBlock.getInstance().getServer().getPluginManager().callEvent(skyblockInteractEvent); if (skyblockInteractEvent.isCancelled()) event.setCancelled(true); } @EventHandler public void equipHelmetThroughEvent(PlayerInteractEvent event) { Player player = event.getPlayer(); ItemStack itemInHand = player.getInventory().getItemInHand(); SkyblockItem skyblockItem = SkyblockItem.fromItemStack(itemInHand); if (skyblockItem == null) return; if (skyblockItem.getItemType() != SkyblockItemType.HELMET || !(skyblockItem instanceof IHeadHelmet)) return; if (player.getInventory().getHelmet() == null || player.getInventory().getHelmet().getType() == Material.AIR) { player.getInventory().setHelmet(itemInHand); player.getInventory().setItemInHand(null); } } /** * For forwarding the EntityDeathEvent to the SkyblockDeathEvent * * @param event EntityDeathEvent */ @EventHandler(priority = EventPriority.LOW) public void onDeathBukkit(EntityDeathEvent event) { LivingEntity livingEntity = event.getEntity(); event.setDroppedExp(0); event.getDrops().clear(); if (livingEntity instanceof Player player) { SkyblockDeathEvent _event = new SkyblockDeathEvent(player, SkyblockDeathEvent.DeathCause.OTHER); Bukkit.getPluginManager().callEvent(_event); return; } EntityLiving entityLiving = ((CraftLivingEntity) event.getEntity()).getHandle(); if (!(entityLiving instanceof ISkyblockMob skyblockMob)) return; SkyblockDeathEvent _event = getSkyblockDeathEvent(livingEntity); SkyBlock.getInstance().getServer().getPluginManager().callEvent(_event); } @EventHandler public void playerDeathBukkit(PlayerDeathEvent event) { event.setDeathMessage(null); event.setKeepInventory(true); event.setKeepLevel(true); event.setDroppedExp(0); new Sequence().add( new SequenceAction(() -> { event.getEntity().spigot().respawn(); event.getEntity().updateInventory(); }, 1) ).start(); } @EventHandler public void onPlayerRegainHealth(EntityRegainHealthEvent event) { if (event.getRegainReason() == EntityRegainHealthEvent.RegainReason.SATIATED || event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN) event.setCancelled(true); } @EventHandler public void onBowPull(EntityShootBowEvent event) { if (!(event.getEntity() instanceof Player player)) return; SkyblockPlayer skyblockPlayer = SkyblockPlayer.getSkyblockPlayer(player); double bowPull = event.getForce(); skyblockPlayer.getStatsManager().setMaxStat(Stats.BOW_PULL, bowPull); if (skyblockPlayer.getInventoryManager().getSkyblockItemInHand() instanceof IShortBow) { event.setCancelled(true); } } @EventHandler public void projectileHitEvent(ProjectileHitEvent event) { List<LivingEntity> nearby = event.getEntity().getNearbyEntities(1, 1, 1).stream().map(entity -> entity instanceof LivingEntity ? (LivingEntity) entity : null).filter(entity -> !(entity instanceof ArmorStand)).toList(); if (nearby.size() == 0) return; LivingEntity en = nearby.get(0); if (event.getEntity() instanceof FallingBlock || en instanceof FallingBlock) return; if (event.getEntity().getShooter() == null) return; LivingEntity shooter = (LivingEntity) event.getEntity().getShooter(); if (shooter instanceof Player && en instanceof Player) { return; } EntityLiving entityLiving = ((CraftLivingEntity) shooter).getHandle(); if (entityLiving instanceof ISkyblockMob skyblockMob && en instanceof Player player) { SkyblockMobDamagePlayerEvent skyblockMobDamagePlayerEvent = new SkyblockMobDamagePlayerEvent( player, shooter ); Bukkit.getPluginManager().callEvent(skyblockMobDamagePlayerEvent); return; } LivingEntity hitEntity = en instanceof EnderDragonPart ? ((EnderDragonPart) en).getParent() : (LivingEntity) en; if (shooter instanceof Player player && ((CraftLivingEntity) hitEntity).getHandle() instanceof ISkyblockMob skyblockMob) { SkyblockPlayerDamageEntityEvent skyblockPlayerDamageEntityEvent = new SkyblockPlayerDamageEntityEvent( hitEntity, player, SkyblockPlayerDamageEntityEvent.DamageType.ARROW ); Bukkit.getPluginManager().callEvent(skyblockPlayerDamageEntityEvent); return; } } @EventHandler public void pickupItemEvent(PlayerPickupItemEvent event) { Player player = event.getPlayer(); Item item = event.getItem(); ItemStack itemStack = item.getItemStack();
if (((CraftItem) event.getItem()).getHandle() instanceof IDragonLoot dragonLoot) {
17
2023-11-15 15:05:58+00:00
24k
GoogleCloudPlatform/dataflow-ordered-processing
simulator/src/main/java/com/google/cloud/simulator/Simulator.java
[ { "identifier": "Matcher", "path": "business-model/src/main/java/com/google/cloud/orderbook/Matcher.java", "snippet": "public class Matcher {\n\n // Ordering orders in a tree -- ordered by price and orderId\n // (orderId is always increasing)\n private class OrderKey {\n\n OrderKey(long price, lon...
import com.google.cloud.orderbook.Matcher; import com.google.cloud.orderbook.MatcherContext; import com.google.cloud.orderbook.Order; import com.google.cloud.orderbook.model.OrderBookEvent; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.lang.Math;
20,698
/* * 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.simulator; /* * Simulator that generates orders against a matcher. */ public class Simulator { /** * Create a complex (multiple contract) simulator. * * @param context MatcherContext for the context of the matching engine * @param numContracts Number of contracts to generate * @param midPrice Starting mid price for all contracts * @param seed Random seed (0 = default randomization) * @param degreeDist Degree of uneven distribution (0 = unform, 1 = linear, 2 = power of 2, etc) * @return Iterable<OrderbookEvent> -- produce OrderBookEvents from the simulator */ static public Iterator<List<OrderBookEvent>> getComplexSimulator(
/* * 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.simulator; /* * Simulator that generates orders against a matcher. */ public class Simulator { /** * Create a complex (multiple contract) simulator. * * @param context MatcherContext for the context of the matching engine * @param numContracts Number of contracts to generate * @param midPrice Starting mid price for all contracts * @param seed Random seed (0 = default randomization) * @param degreeDist Degree of uneven distribution (0 = unform, 1 = linear, 2 = power of 2, etc) * @return Iterable<OrderbookEvent> -- produce OrderBookEvents from the simulator */ static public Iterator<List<OrderBookEvent>> getComplexSimulator(
MatcherContext context,
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,490
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){ if(program.compareTo(project) < 0) return false; return true; } // project root protected ProjectRoot root; public ProjectRoot getRoot(){return root;} // tree generation public DefaultMutableTreeNode getTree(){ return root.getTree(); } // updates menu offshoot entities public void updateDependencies(){ buildDictionary(); root.generateMenu(); } //region dictionary---------------------------- // dictionary protected HashMap<Long, ProjectFile> dictionary; //build dictionary public void buildDictionary(){ dictionary = new HashMap<>(); // generate new dictionary addDict(root); // build from root } // build dictionary recursive protected void addDict(ProjectUnitCore root){ // case file: add to dictionary if (root instanceof ProjectFile){ ProjectFile unit = (ProjectFile) root; //cast object dictionary.put(unit.getID(), unit); } //recurse to all children for file types else if (root instanceof ProjectFolderInterface){ ProjectFolderInterface unit = (ProjectFolderInterface) root; //cast object for (ProjectUnitCore child: unit.getChildren()){ addDict(child); } } } //query dictionary; returns null if none found public ProjectFile getFile(long code){ // return null if nocode if(code == Program.getDefaultFileCode()) return null; return dictionary.get(code); } // endregion // save file------------------------------------ // GSON builder private static final Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag .setPrettyPrinting() // creates a pretty version of the output .registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter
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){ if(program.compareTo(project) < 0) return false; return true; } // project root protected ProjectRoot root; public ProjectRoot getRoot(){return root;} // tree generation public DefaultMutableTreeNode getTree(){ return root.getTree(); } // updates menu offshoot entities public void updateDependencies(){ buildDictionary(); root.generateMenu(); } //region dictionary---------------------------- // dictionary protected HashMap<Long, ProjectFile> dictionary; //build dictionary public void buildDictionary(){ dictionary = new HashMap<>(); // generate new dictionary addDict(root); // build from root } // build dictionary recursive protected void addDict(ProjectUnitCore root){ // case file: add to dictionary if (root instanceof ProjectFile){ ProjectFile unit = (ProjectFile) root; //cast object dictionary.put(unit.getID(), unit); } //recurse to all children for file types else if (root instanceof ProjectFolderInterface){ ProjectFolderInterface unit = (ProjectFolderInterface) root; //cast object for (ProjectUnitCore child: unit.getChildren()){ addDict(child); } } } //query dictionary; returns null if none found public ProjectFile getFile(long code){ // return null if nocode if(code == Program.getDefaultFileCode()) return null; return dictionary.get(code); } // endregion // save file------------------------------------ // GSON builder private static final Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag .setPrettyPrinting() // creates a pretty version of the output .registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter
.registerTypeAdapter(TreeUnit.class, new RendererTypeAdapter()) // register sorting deserializer for renderer
2
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,597
package com.erapor.erapor.service; @Service public class UserServices { @Autowired AccountsRepository accountsRepository; @Autowired Validator validator; @Transactional public void register(RegisterDTO registerDTO){ Set<ConstraintViolation<RegisterDTO>> constraintViolation = validator.validate(registerDTO); if(constraintViolation.isEmpty()){ throw new ConstraintViolationException(constraintViolation); } if(accountsRepository.findByEmail(registerDTO.getEmail())){ throw new ApiException("email already exist!"); } AccountsDAO accountsDAO = new AccountsDAO(); accountsDAO.setEmail(registerDTO.getEmail());
package com.erapor.erapor.service; @Service public class UserServices { @Autowired AccountsRepository accountsRepository; @Autowired Validator validator; @Transactional public void register(RegisterDTO registerDTO){ Set<ConstraintViolation<RegisterDTO>> constraintViolation = validator.validate(registerDTO); if(constraintViolation.isEmpty()){ throw new ConstraintViolationException(constraintViolation); } if(accountsRepository.findByEmail(registerDTO.getEmail())){ throw new ApiException("email already exist!"); } AccountsDAO accountsDAO = new AccountsDAO(); accountsDAO.setEmail(registerDTO.getEmail());
accountsDAO.setPassword(BCrypt.hashpw(registerDTO.getPassword(),BCrypt.gensalt()));
4
2023-11-11 19:40:43+00:00
24k
shizotoaster/thaumon
forge/src/main/java/jdlenl/thaumon/itemgroup/forge/ThaumonItemGroupForge.java
[ { "identifier": "Thaumon", "path": "common/src/main/java/jdlenl/thaumon/Thaumon.java", "snippet": "public class Thaumon {\n public static final String MOD_ID = \"thaumon\";\n public static Logger logger = LoggerFactory.getLogger(MOD_ID);\n\n public static void init() {\n ThaumonItems.ini...
import jdlenl.thaumon.Thaumon; import jdlenl.thaumon.block.ThaumonBlocks; import jdlenl.thaumon.item.ThaumonItems; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.registry.RegistryKeys; import net.minecraft.text.Text; import net.minecraftforge.registries.DeferredRegister; import java.util.function.Supplier;
14,652
package jdlenl.thaumon.itemgroup.forge; public class ThaumonItemGroupForge { public static final DeferredRegister<ItemGroup> ITEM_GROUPS = DeferredRegister.create(RegistryKeys.ITEM_GROUP, Thaumon.MOD_ID); public static final Supplier<ItemGroup> THAUMON_GROUP = ITEM_GROUPS.register("thaumon_item_group",
package jdlenl.thaumon.itemgroup.forge; public class ThaumonItemGroupForge { public static final DeferredRegister<ItemGroup> ITEM_GROUPS = DeferredRegister.create(RegistryKeys.ITEM_GROUP, Thaumon.MOD_ID); public static final Supplier<ItemGroup> THAUMON_GROUP = ITEM_GROUPS.register("thaumon_item_group",
() -> ItemGroup.builder().displayName(Text.translatable("itemgroup.thaumon.thaumon_item_group")).icon(() -> new ItemStack(ThaumonBlocks.ELDRITCH_LANTERN.get().asItem()))
1
2023-11-16 06:03:29+00:00
24k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/manager/CheckManager.java
[ { "identifier": "Reach", "path": "src/main/java/ac/grim/grimac/checks/impl/combat/Reach.java", "snippet": "public class Reach extends PacketCheck {\n // Concurrent to support weird entity trackers\n private final ConcurrentLinkedQueue<Integer> playerAttackQueue = new ConcurrentLinkedQueue<>();\n\n...
import ac.grim.grimac.checks.impl.combat.Reach; import ac.grim.grimac.checks.impl.groundspoof.NoFallA; import ac.grim.grimac.checks.impl.movement.*; import ac.grim.grimac.checks.impl.prediction.DebugHandler; import ac.grim.grimac.checks.impl.prediction.NoFallB; import ac.grim.grimac.checks.impl.prediction.OffsetHandler; import ac.grim.grimac.checks.impl.scaffolding.AirLiquidPlace; import ac.grim.grimac.checks.impl.velocity.ExplosionHandler; import ac.grim.grimac.checks.impl.velocity.KnockbackHandler; import ac.grim.grimac.checks.type.*; import ac.grim.grimac.events.packets.PacketEntityReplication; import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.predictionengine.GhostBlockDetector; import ac.grim.grimac.utils.anticheat.update.*; import ac.grim.grimac.utils.latency.CompensatedCooldown; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.ImmutableClassToInstanceMap; import io.github.retrooper.packetevents.event.impl.PacketPlayReceiveEvent; import io.github.retrooper.packetevents.event.impl.PacketPlaySendEvent;
18,751
package ac.grim.grimac.manager; public class CheckManager { ClassToInstanceMap<PacketCheck> packetChecks; ClassToInstanceMap<PositionCheck> positionCheck; ClassToInstanceMap<RotationCheck> rotationCheck; ClassToInstanceMap<VehicleCheck> vehicleCheck; ClassToInstanceMap<BlockPlaceCheck> blockPlaceCheck; ClassToInstanceMap<PostPredictionCheck> postPredictionCheck; public CheckManager(GrimPlayer player) { // Include post checks in the packet check too packetChecks = new ImmutableClassToInstanceMap.Builder<PacketCheck>() .put(Reach.class, new Reach(player)) .put(PacketEntityReplication.class, new PacketEntityReplication(player)) .put(ExplosionHandler.class, new ExplosionHandler(player)) .put(KnockbackHandler.class, new KnockbackHandler(player)) //.put(CompensatedInventory.class, new CompensatedInventory(player)) .put(NoFallA.class, new NoFallA(player)) .put(TimerCheck.class, new TimerCheck(player)) .put(VehicleTimer.class, new VehicleTimer(player)) // This desync class causes too many desync's to be used in production, blocks missing on client side // This has to be fixed with packet based block placing instead of spamming blocks to the player //.put(AntiUseItemDesync.class, new AntiUseItemDesync(player)) .put(SetbackBlocker.class, new SetbackBlocker(player)) // Must be last class otherwise we can't check while blocking packets .build(); positionCheck = new ImmutableClassToInstanceMap.Builder<PositionCheck>() .put(PredictionRunner.class, new PredictionRunner(player)) .put(CompensatedCooldown.class, new CompensatedCooldown(player)) .build(); rotationCheck = new ImmutableClassToInstanceMap.Builder<RotationCheck>() .build(); vehicleCheck = new ImmutableClassToInstanceMap.Builder<VehicleCheck>() .put(VehiclePredictionRunner.class, new VehiclePredictionRunner(player)) .build(); postPredictionCheck = new ImmutableClassToInstanceMap.Builder<PostPredictionCheck>()
package ac.grim.grimac.manager; public class CheckManager { ClassToInstanceMap<PacketCheck> packetChecks; ClassToInstanceMap<PositionCheck> positionCheck; ClassToInstanceMap<RotationCheck> rotationCheck; ClassToInstanceMap<VehicleCheck> vehicleCheck; ClassToInstanceMap<BlockPlaceCheck> blockPlaceCheck; ClassToInstanceMap<PostPredictionCheck> postPredictionCheck; public CheckManager(GrimPlayer player) { // Include post checks in the packet check too packetChecks = new ImmutableClassToInstanceMap.Builder<PacketCheck>() .put(Reach.class, new Reach(player)) .put(PacketEntityReplication.class, new PacketEntityReplication(player)) .put(ExplosionHandler.class, new ExplosionHandler(player)) .put(KnockbackHandler.class, new KnockbackHandler(player)) //.put(CompensatedInventory.class, new CompensatedInventory(player)) .put(NoFallA.class, new NoFallA(player)) .put(TimerCheck.class, new TimerCheck(player)) .put(VehicleTimer.class, new VehicleTimer(player)) // This desync class causes too many desync's to be used in production, blocks missing on client side // This has to be fixed with packet based block placing instead of spamming blocks to the player //.put(AntiUseItemDesync.class, new AntiUseItemDesync(player)) .put(SetbackBlocker.class, new SetbackBlocker(player)) // Must be last class otherwise we can't check while blocking packets .build(); positionCheck = new ImmutableClassToInstanceMap.Builder<PositionCheck>() .put(PredictionRunner.class, new PredictionRunner(player)) .put(CompensatedCooldown.class, new CompensatedCooldown(player)) .build(); rotationCheck = new ImmutableClassToInstanceMap.Builder<RotationCheck>() .build(); vehicleCheck = new ImmutableClassToInstanceMap.Builder<VehicleCheck>() .put(VehiclePredictionRunner.class, new VehiclePredictionRunner(player)) .build(); postPredictionCheck = new ImmutableClassToInstanceMap.Builder<PostPredictionCheck>()
.put(GhostBlockDetector.class, new GhostBlockDetector(player))
10
2023-11-11 05:14:12+00:00
24k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/dialog/TimeDialog.java
[ { "identifier": "BaseDialog", "path": "library/base/src/main/java/com/hjq/base/BaseDialog.java", "snippet": "public class BaseDialog extends AppCompatDialog implements LifecycleOwner,\n ActivityAction, ResourcesAction, HandlerAction, ClickAction, AnimAction, KeyboardAction,\n DialogInterfa...
import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import com.hjq.base.BaseDialog; import com.buaa.food.R; import com.buaa.food.aop.SingleClick; import com.buaa.food.app.AppAdapter; import com.buaa.food.manager.PickerLayoutManager; import java.util.ArrayList; import java.util.Calendar;
14,690
} mHourAdapter.setData(hourData); mMinuteAdapter.setData(minuteData); mSecondAdapter.setData(secondData); mHourManager = new PickerLayoutManager.Builder(context) .build(); mMinuteManager = new PickerLayoutManager.Builder(context) .build(); mSecondManager = new PickerLayoutManager.Builder(context) .build(); mHourView.setLayoutManager(mHourManager); mMinuteView.setLayoutManager(mMinuteManager); mSecondView.setLayoutManager(mSecondManager); mHourView.setAdapter(mHourAdapter); mMinuteView.setAdapter(mMinuteAdapter); mSecondView.setAdapter(mSecondAdapter); Calendar calendar = Calendar.getInstance(); setHour(calendar.get(Calendar.HOUR_OF_DAY)); setMinute(calendar.get(Calendar.MINUTE)); setSecond(calendar.get(Calendar.SECOND)); } public Builder setListener(OnListener listener) { mListener = listener; return this; } /** * 不选择秒数 */ public Builder setIgnoreSecond() { mSecondView.setVisibility(View.GONE); return this; } public Builder setTime(String time) { // 102030 if (time.matches("\\d{6}")) { setHour(time.substring(0, 2)); setMinute(time.substring(2, 4)); setSecond(time.substring(4, 6)); // 10:20:30 } else if (time.matches("\\d{2}:\\d{2}:\\d{2}")) { setHour(time.substring(0, 2)); setMinute(time.substring(3, 5)); setSecond(time.substring(6, 8)); } return this; } public Builder setHour(String hour) { return setHour(Integer.parseInt(hour)); } public Builder setHour(int hour) { int index = hour; if (index < 0 || hour == 24) { index = 0; } else if (index > mHourAdapter.getCount() - 1) { index = mHourAdapter.getCount() - 1; } mHourView.scrollToPosition(index); return this; } public Builder setMinute(String minute) { return setMinute(Integer.parseInt(minute)); } public Builder setMinute(int minute) { int index = minute; if (index < 0) { index = 0; } else if (index > mMinuteAdapter.getCount() - 1) { index = mMinuteAdapter.getCount() - 1; } mMinuteView.scrollToPosition(index); return this; } public Builder setSecond(String second) { return setSecond(Integer.parseInt(second)); } public Builder setSecond(int second) { int index = second; if (index < 0) { index = 0; } else if (index > mSecondAdapter.getCount() - 1) { index = mSecondAdapter.getCount() - 1; } mSecondView.scrollToPosition(index); return this; } @SingleClick @Override public void onClick(View view) { int viewId = view.getId(); if (viewId == R.id.tv_ui_confirm) { autoDismiss(); if (mListener == null) { return; } mListener.onSelected(getDialog(), mHourManager.getPickedPosition(), mMinuteManager.getPickedPosition(), mSecondManager.getPickedPosition()); } else if (viewId == R.id.tv_ui_cancel) { autoDismiss(); if (mListener == null) { return; } mListener.onCancel(getDialog()); } } }
package com.buaa.food.ui.dialog; public final class TimeDialog { public static final class Builder extends CommonDialog.Builder<Builder> { private final RecyclerView mHourView; private final RecyclerView mMinuteView; private final RecyclerView mSecondView; private final PickerLayoutManager mHourManager; private final PickerLayoutManager mMinuteManager; private final PickerLayoutManager mSecondManager; private final PickerAdapter mHourAdapter; private final PickerAdapter mMinuteAdapter; private final PickerAdapter mSecondAdapter; @Nullable private OnListener mListener; @SuppressWarnings("all") public Builder(Context context) { super(context); setCustomView(R.layout.time_dialog); setTitle(R.string.time_title); mHourView = findViewById(R.id.rv_time_hour); mMinuteView = findViewById(R.id.rv_time_minute); mSecondView = findViewById(R.id.rv_time_second); mHourAdapter = new PickerAdapter(context); mMinuteAdapter = new PickerAdapter(context); mSecondAdapter = new PickerAdapter(context); // 生产小时 ArrayList<String> hourData = new ArrayList<>(24); for (int i = 0; i <= 23; i++) { hourData.add((i < 10 ? "0" : "") + i + " " + getString(R.string.common_hour)); } // 生产分钟 ArrayList<String> minuteData = new ArrayList<>(60); for (int i = 0; i <= 59; i++) { minuteData.add((i < 10 ? "0" : "") + i + " " + getString(R.string.common_minute)); } // 生产秒钟 ArrayList<String> secondData = new ArrayList<>(60); for (int i = 0; i <= 59; i++) { secondData.add((i < 10 ? "0" : "") + i + " " + getString(R.string.common_second)); } mHourAdapter.setData(hourData); mMinuteAdapter.setData(minuteData); mSecondAdapter.setData(secondData); mHourManager = new PickerLayoutManager.Builder(context) .build(); mMinuteManager = new PickerLayoutManager.Builder(context) .build(); mSecondManager = new PickerLayoutManager.Builder(context) .build(); mHourView.setLayoutManager(mHourManager); mMinuteView.setLayoutManager(mMinuteManager); mSecondView.setLayoutManager(mSecondManager); mHourView.setAdapter(mHourAdapter); mMinuteView.setAdapter(mMinuteAdapter); mSecondView.setAdapter(mSecondAdapter); Calendar calendar = Calendar.getInstance(); setHour(calendar.get(Calendar.HOUR_OF_DAY)); setMinute(calendar.get(Calendar.MINUTE)); setSecond(calendar.get(Calendar.SECOND)); } public Builder setListener(OnListener listener) { mListener = listener; return this; } /** * 不选择秒数 */ public Builder setIgnoreSecond() { mSecondView.setVisibility(View.GONE); return this; } public Builder setTime(String time) { // 102030 if (time.matches("\\d{6}")) { setHour(time.substring(0, 2)); setMinute(time.substring(2, 4)); setSecond(time.substring(4, 6)); // 10:20:30 } else if (time.matches("\\d{2}:\\d{2}:\\d{2}")) { setHour(time.substring(0, 2)); setMinute(time.substring(3, 5)); setSecond(time.substring(6, 8)); } return this; } public Builder setHour(String hour) { return setHour(Integer.parseInt(hour)); } public Builder setHour(int hour) { int index = hour; if (index < 0 || hour == 24) { index = 0; } else if (index > mHourAdapter.getCount() - 1) { index = mHourAdapter.getCount() - 1; } mHourView.scrollToPosition(index); return this; } public Builder setMinute(String minute) { return setMinute(Integer.parseInt(minute)); } public Builder setMinute(int minute) { int index = minute; if (index < 0) { index = 0; } else if (index > mMinuteAdapter.getCount() - 1) { index = mMinuteAdapter.getCount() - 1; } mMinuteView.scrollToPosition(index); return this; } public Builder setSecond(String second) { return setSecond(Integer.parseInt(second)); } public Builder setSecond(int second) { int index = second; if (index < 0) { index = 0; } else if (index > mSecondAdapter.getCount() - 1) { index = mSecondAdapter.getCount() - 1; } mSecondView.scrollToPosition(index); return this; } @SingleClick @Override public void onClick(View view) { int viewId = view.getId(); if (viewId == R.id.tv_ui_confirm) { autoDismiss(); if (mListener == null) { return; } mListener.onSelected(getDialog(), mHourManager.getPickedPosition(), mMinuteManager.getPickedPosition(), mSecondManager.getPickedPosition()); } else if (viewId == R.id.tv_ui_cancel) { autoDismiss(); if (mListener == null) { return; } mListener.onCancel(getDialog()); } } }
private static final class PickerAdapter extends AppAdapter<String> {
1
2023-11-14 10:04:26+00:00
24k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/mixins/mixin/EntityDiggingFXMixin.java
[ { "identifier": "BlockModelDragonFly", "path": "src/main/java/useless/dragonfly/model/block/BlockModelDragonFly.java", "snippet": "public class BlockModelDragonFly extends BlockModelRenderBlocks {\n\tpublic BlockModel baseModel;\n\tpublic boolean render3d;\n\tpublic float renderScale;\n\tpublic Blocksta...
import net.minecraft.client.entity.fx.EntityDiggingFX; import net.minecraft.client.entity.fx.EntityFX; import net.minecraft.client.render.block.model.BlockModel; import net.minecraft.client.render.block.model.BlockModelDispatcher; import net.minecraft.core.block.Block; import net.minecraft.core.util.helper.Side; import net.minecraft.core.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import useless.dragonfly.model.block.BlockModelDragonFly; import useless.dragonfly.registries.TextureRegistry;
15,771
package useless.dragonfly.mixins.mixin; @Mixin(value = EntityDiggingFX.class, remap = false) public class EntityDiggingFXMixin extends EntityFX { @Shadow private Block block; public EntityDiggingFXMixin(World world, double x, double y, double z, double motionX, double motionY, double motionZ) { super(world, x, y, z, motionX, motionY, motionZ); } @Redirect(method = "<init>(Lnet/minecraft/core/world/World;DDDDDDLnet/minecraft/core/block/Block;II)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/core/block/Block;getBlockTextureFromSideAndMetadata(Lnet/minecraft/core/util/helper/Side;I)I")) private int particleFromModel(Block instance, Side side, int meta){ BlockModel model = BlockModelDispatcher.getInstance().getDispatch(instance); int tex; if (model instanceof BlockModelDragonFly){
package useless.dragonfly.mixins.mixin; @Mixin(value = EntityDiggingFX.class, remap = false) public class EntityDiggingFXMixin extends EntityFX { @Shadow private Block block; public EntityDiggingFXMixin(World world, double x, double y, double z, double motionX, double motionY, double motionZ) { super(world, x, y, z, motionX, motionY, motionZ); } @Redirect(method = "<init>(Lnet/minecraft/core/world/World;DDDDDDLnet/minecraft/core/block/Block;II)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/core/block/Block;getBlockTextureFromSideAndMetadata(Lnet/minecraft/core/util/helper/Side;I)I")) private int particleFromModel(Block instance, Side side, int meta){ BlockModel model = BlockModelDispatcher.getInstance().getDispatch(instance); int tex; if (model instanceof BlockModelDragonFly){
tex = TextureRegistry.getIndexOrDefault(((BlockModelDragonFly) model).getModelsFromState(block, (int) x, (int) y, (int) z, true)[0].model.getTexture("particle"), block.getBlockTextureFromSideAndMetadata(Side.BOTTOM, meta));
1
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.*;
14,877
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;
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) () -> {
2
2023-11-12 07:49:59+00:00
24k
Shushandr/offroad
src/net/sourceforge/offroad/actions/RemovePointFromPolylineAction.java
[ { "identifier": "LatLon", "path": "src/net/osmand/data/LatLon.java", "snippet": "@XmlRootElement\npublic class LatLon implements Serializable {\n\tpublic void setLongitude(double pLongitude) {\n\t\tlongitude = pLongitude;\n\t}\n\n\tpublic void setLatitude(double pLatitude) {\n\t\tlatitude = pLatitude;\n...
import net.osmand.plus.views.DrawPolylineLayer.Polyline; import net.sourceforge.offroad.OsmWindow; import java.awt.event.ActionEvent; import net.osmand.data.LatLon;
19,595
/** OffRoad Copyright (C) 2017 Christian Foltin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.sourceforge.offroad.actions; /** * @author foltin * @date 19.05.2017 */ public class RemovePointFromPolylineAction extends OffRoadAction { private Polyline mPolyline; private LatLon mLatLon;
/** OffRoad Copyright (C) 2017 Christian Foltin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.sourceforge.offroad.actions; /** * @author foltin * @date 19.05.2017 */ public class RemovePointFromPolylineAction extends OffRoadAction { private Polyline mPolyline; private LatLon mLatLon;
public RemovePointFromPolylineAction(OsmWindow pContext, Polyline pPolyline, LatLon pLatLon) {
2
2023-11-15 05:04:55+00:00
24k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/config/HrmConfigController.java
[ { "identifier": "OperationLog", "path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperationLog.java", "snippet": "@Getter\n@Setter\npublic class OperationLog {\n //操作对象\n private Object operationObject;\n //操作详情\n private String operationInfo;\n\n private BehaviorEnu...
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.StrUtil; import com.kakarote.common.log.annotation.OperateLog; import com.kakarote.common.log.entity.OperationLog; import com.kakarote.common.log.entity.OperationResult; import com.kakarote.common.log.enums.ApplyEnum; import com.kakarote.common.log.enums.BehaviorEnum; import com.kakarote.common.log.enums.OperateObjectEnum; import com.kakarote.common.log.enums.OperateTypeEnum; import com.kakarote.core.common.Result; import com.kakarote.core.entity.BasePage; import com.kakarote.core.entity.PageEntity; import com.kakarote.hrm.common.LanguageFieldUtil; import com.kakarote.hrm.constant.ConfigType; import com.kakarote.hrm.constant.LabelGroupEnum; import com.kakarote.hrm.entity.BO.AddEmployeeFieldBO; import com.kakarote.hrm.entity.BO.AddInsuranceSchemeBO; import com.kakarote.hrm.entity.BO.DeleteRecruitChannelBO; import com.kakarote.hrm.entity.BO.SetAchievementTableBO; import com.kakarote.hrm.entity.PO.*; import com.kakarote.hrm.entity.VO.*; import com.kakarote.hrm.service.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
15,894
@ApiOperation("删除招聘渠道") public Result deleteRecruitChannel(@RequestBody DeleteRecruitChannelBO deleteRecruitChannelBO) { employeeService.lambdaUpdate() .set(HrmEmployee::getChannelId, deleteRecruitChannelBO.getChangeChannelId()) .eq(HrmEmployee::getChannelId, deleteRecruitChannelBO.getDeleteChannelId()) .update(); recruitCandidateService.lambdaUpdate() .set(HrmRecruitCandidate::getChannelId, deleteRecruitChannelBO.getChangeChannelId()) .eq(HrmRecruitCandidate::getChannelId, deleteRecruitChannelBO.getDeleteChannelId()) .update(); recruitChannelService.removeById(deleteRecruitChannelBO.getDeleteChannelId()); return Result.ok(); } /** * --------------淘汰原因--------------- */ @PostMapping("/saveRecruitEliminate") @ApiOperation("保存淘汰原因") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_BUSINESS_PARAM_SETTING, behavior = BehaviorEnum.UPDATE) public Result saveRecruitEliminate(@RequestBody List<String> data) { configService.lambdaUpdate().eq(HrmConfig::getType, ConfigType.ELIMINATION_REASONS.getValue()).remove(); List<HrmConfig> collect = data.stream().map(value -> { HrmConfig hrmConfig = new HrmConfig(); hrmConfig.setType(ConfigType.ELIMINATION_REASONS.getValue()); hrmConfig.setValue(value); return hrmConfig; }).collect(Collectors.toList()); configService.saveBatch(collect); OperationLog operationLog = new OperationLog(); operationLog.setOperationObject("淘汰原因"); operationLog.setOperationInfo("编辑淘汰原因"); return OperationResult.ok(operationLog); } @PostMapping("/queryRecruitEliminateList") @ApiOperation("查询淘汰原因") public Result<RecruitEliminateVO> queryRecruitEliminateList() { RecruitEliminateVO eliminateVO = new RecruitEliminateVO(); List<String> list = configService.lambdaQuery().eq(HrmConfig::getType, ConfigType.ELIMINATION_REASONS.getValue()).list() .stream().map(HrmConfig::getValue).collect(Collectors.toList()); Map<String, String> keyMap = new HashMap<>(); if (CollectionUtil.isNotEmpty(list)) { for (int i = 0; i < list.size(); i++) { if (StrUtil.isNotBlank(list.get(i))) { //添加语言包key keyMap.putAll(LanguageFieldUtil.getFieldNameKeyMap(StrUtil.toString(i), "hrm.config.1.", list.get(i))); } } eliminateVO.setLanguageKeyMap(keyMap); } eliminateVO.setRecruit(list); eliminateVO.setLanguageKeyMap(keyMap); return Result.ok(eliminateVO); } /** * --------------自定义字段--------------- */ @PostMapping("/queryFields") @ApiOperation("查询后台配置自定义字段列表") public Result<List<FiledListVO>> queryFields() { List<FiledListVO> fieldList = employeeFieldService.queryFields(); return Result.ok(fieldList); } @PostMapping("/queryFieldByLabel/{labelGroup}") @ApiOperation("查询后台配置自定义字段列表") public Result<List<List<HrmEmployeeField>>> queryFieldByLabel(@ApiParam("1 个人信息 2 通讯信息 7 联系人信息 11 岗位信息") @PathVariable("labelGroup") Integer labelGroup) { List<List<HrmEmployeeField>> data = employeeFieldService.queryFieldByLabel(labelGroup); return Result.ok(data); } @PostMapping("/saveField") @ApiOperation("保存后台自定义字段") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, behavior = BehaviorEnum.UPDATE, object = OperateObjectEnum.HUMAN_MANAGEMENT_CUSTOM_FIELD) public Result saveField(@RequestBody AddEmployeeFieldBO addEmployeeFieldBO) { employeeFieldService.saveField(addEmployeeFieldBO); LabelGroupEnum parse = LabelGroupEnum.parse(addEmployeeFieldBO.getLabelGroup()); OperationLog operationLog = new OperationLog(); operationLog.setOperationObject(parse.getName()); operationLog.setOperationInfo("修改了" + parse.getName() + "自定义字段"); return OperationResult.ok(operationLog); } /** * --------------社保方案--------------- */ @PostMapping("/addInsuranceScheme") @ApiOperation("添加社保方案") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_INSURANCE_SCHEME_SETTING) public Result addInsuranceScheme(@Valid @RequestBody AddInsuranceSchemeBO addInsuranceSchemeBO) { OperationLog operationLog = insuranceSchemeService.setInsuranceScheme(addInsuranceSchemeBO); return OperationResult.ok(operationLog); } @PostMapping("/setInsuranceScheme") @ApiOperation("修改社保方案") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_INSURANCE_SCHEME_SETTING) public Result setInsuranceScheme(@Valid @RequestBody AddInsuranceSchemeBO addInsuranceSchemeBO) { OperationLog operationLog = insuranceSchemeService.setInsuranceScheme(addInsuranceSchemeBO); return OperationResult.ok(operationLog); } @PostMapping("/deleteInsuranceScheme/{schemeId}") @ApiOperation("删除社保方案") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_INSURANCE_SCHEME_SETTING, behavior = BehaviorEnum.DELETE) public Result deleteInsuranceScheme(@PathVariable("schemeId") Long schemeId) { OperationLog operationLog = insuranceSchemeService.deleteInsuranceScheme(schemeId); return OperationResult.ok(operationLog); } @PostMapping("/queryInsuranceSchemePageList") @ApiOperation("查询参保方案列表")
package com.kakarote.hrm.controller.config; @RestController @RequestMapping("/hrmConfig") @Api(tags = "人力资源后台配置接口") public class HrmConfigController { @Autowired private IHrmConfigService configService; @Autowired private IHrmEmployeeFieldService employeeFieldService; @Autowired private IHrmInsuranceSchemeService insuranceSchemeService; @Autowired private IHrmAchievementTableService achievementTableService; @Autowired private IHrmRecruitChannelService recruitChannelService; @Autowired private IHrmEmployeeService employeeService; @Autowired private IHrmRecruitCandidateService recruitCandidateService; /** * --------------招聘渠道--------------- */ @PostMapping("/saveRecruitChannel") @ApiOperation("保存招聘渠道") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_BUSINESS_PARAM_SETTING, behavior = BehaviorEnum.UPDATE) public Result saveRecruitChannel(@RequestBody List<HrmRecruitChannel> channelList) { recruitChannelService.saveOrUpdateBatch(channelList); OperationLog operationLog = new OperationLog(); operationLog.setOperationObject("招聘渠道"); operationLog.setOperationInfo("编辑招聘渠道"); return OperationResult.ok(operationLog); } @PostMapping("/queryRecruitChannelList") @ApiOperation("查询招聘渠道配置列表") public Result<List<HrmRecruitChannel>> queryRecruitChannelList() { List<HrmRecruitChannel> list = recruitChannelService.list(); if (CollectionUtil.isNotEmpty(list)) { for (HrmRecruitChannel channel : list) { //添加语言包key channel.setLanguageKeyMap(LanguageFieldUtil.getFieldNameKeyMap("value_resourceKey", "admin.recruitChannel.", channel.getValue())); } } return Result.ok(list); } @PostMapping("/deleteRecruitChannel") @ApiOperation("删除招聘渠道") public Result deleteRecruitChannel(@RequestBody DeleteRecruitChannelBO deleteRecruitChannelBO) { employeeService.lambdaUpdate() .set(HrmEmployee::getChannelId, deleteRecruitChannelBO.getChangeChannelId()) .eq(HrmEmployee::getChannelId, deleteRecruitChannelBO.getDeleteChannelId()) .update(); recruitCandidateService.lambdaUpdate() .set(HrmRecruitCandidate::getChannelId, deleteRecruitChannelBO.getChangeChannelId()) .eq(HrmRecruitCandidate::getChannelId, deleteRecruitChannelBO.getDeleteChannelId()) .update(); recruitChannelService.removeById(deleteRecruitChannelBO.getDeleteChannelId()); return Result.ok(); } /** * --------------淘汰原因--------------- */ @PostMapping("/saveRecruitEliminate") @ApiOperation("保存淘汰原因") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_BUSINESS_PARAM_SETTING, behavior = BehaviorEnum.UPDATE) public Result saveRecruitEliminate(@RequestBody List<String> data) { configService.lambdaUpdate().eq(HrmConfig::getType, ConfigType.ELIMINATION_REASONS.getValue()).remove(); List<HrmConfig> collect = data.stream().map(value -> { HrmConfig hrmConfig = new HrmConfig(); hrmConfig.setType(ConfigType.ELIMINATION_REASONS.getValue()); hrmConfig.setValue(value); return hrmConfig; }).collect(Collectors.toList()); configService.saveBatch(collect); OperationLog operationLog = new OperationLog(); operationLog.setOperationObject("淘汰原因"); operationLog.setOperationInfo("编辑淘汰原因"); return OperationResult.ok(operationLog); } @PostMapping("/queryRecruitEliminateList") @ApiOperation("查询淘汰原因") public Result<RecruitEliminateVO> queryRecruitEliminateList() { RecruitEliminateVO eliminateVO = new RecruitEliminateVO(); List<String> list = configService.lambdaQuery().eq(HrmConfig::getType, ConfigType.ELIMINATION_REASONS.getValue()).list() .stream().map(HrmConfig::getValue).collect(Collectors.toList()); Map<String, String> keyMap = new HashMap<>(); if (CollectionUtil.isNotEmpty(list)) { for (int i = 0; i < list.size(); i++) { if (StrUtil.isNotBlank(list.get(i))) { //添加语言包key keyMap.putAll(LanguageFieldUtil.getFieldNameKeyMap(StrUtil.toString(i), "hrm.config.1.", list.get(i))); } } eliminateVO.setLanguageKeyMap(keyMap); } eliminateVO.setRecruit(list); eliminateVO.setLanguageKeyMap(keyMap); return Result.ok(eliminateVO); } /** * --------------自定义字段--------------- */ @PostMapping("/queryFields") @ApiOperation("查询后台配置自定义字段列表") public Result<List<FiledListVO>> queryFields() { List<FiledListVO> fieldList = employeeFieldService.queryFields(); return Result.ok(fieldList); } @PostMapping("/queryFieldByLabel/{labelGroup}") @ApiOperation("查询后台配置自定义字段列表") public Result<List<List<HrmEmployeeField>>> queryFieldByLabel(@ApiParam("1 个人信息 2 通讯信息 7 联系人信息 11 岗位信息") @PathVariable("labelGroup") Integer labelGroup) { List<List<HrmEmployeeField>> data = employeeFieldService.queryFieldByLabel(labelGroup); return Result.ok(data); } @PostMapping("/saveField") @ApiOperation("保存后台自定义字段") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, behavior = BehaviorEnum.UPDATE, object = OperateObjectEnum.HUMAN_MANAGEMENT_CUSTOM_FIELD) public Result saveField(@RequestBody AddEmployeeFieldBO addEmployeeFieldBO) { employeeFieldService.saveField(addEmployeeFieldBO); LabelGroupEnum parse = LabelGroupEnum.parse(addEmployeeFieldBO.getLabelGroup()); OperationLog operationLog = new OperationLog(); operationLog.setOperationObject(parse.getName()); operationLog.setOperationInfo("修改了" + parse.getName() + "自定义字段"); return OperationResult.ok(operationLog); } /** * --------------社保方案--------------- */ @PostMapping("/addInsuranceScheme") @ApiOperation("添加社保方案") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_INSURANCE_SCHEME_SETTING) public Result addInsuranceScheme(@Valid @RequestBody AddInsuranceSchemeBO addInsuranceSchemeBO) { OperationLog operationLog = insuranceSchemeService.setInsuranceScheme(addInsuranceSchemeBO); return OperationResult.ok(operationLog); } @PostMapping("/setInsuranceScheme") @ApiOperation("修改社保方案") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_INSURANCE_SCHEME_SETTING) public Result setInsuranceScheme(@Valid @RequestBody AddInsuranceSchemeBO addInsuranceSchemeBO) { OperationLog operationLog = insuranceSchemeService.setInsuranceScheme(addInsuranceSchemeBO); return OperationResult.ok(operationLog); } @PostMapping("/deleteInsuranceScheme/{schemeId}") @ApiOperation("删除社保方案") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_INSURANCE_SCHEME_SETTING, behavior = BehaviorEnum.DELETE) public Result deleteInsuranceScheme(@PathVariable("schemeId") Long schemeId) { OperationLog operationLog = insuranceSchemeService.deleteInsuranceScheme(schemeId); return OperationResult.ok(operationLog); } @PostMapping("/queryInsuranceSchemePageList") @ApiOperation("查询参保方案列表")
public Result<BasePage<InsuranceSchemeListVO>> queryInsuranceSchemePageList(@RequestBody PageEntity pageEntity) {
8
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,297
} 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
/* * 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) {
28
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;
16,982
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() {
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();
5
2023-10-20 07:08:37+00:00
24k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/recipe/machineRecipe/GTCMMachineRecipePool.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.common.GTCMItemList.AdvancedMegaOilCracker; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.AnnihilationConstrainer; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.BiosphereIII; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.CircuitConverter; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.CrystallineInfinitier; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.DualInputBuffer_LuV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.DualInputBuffer_UHV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.DualInputBuffer_UV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.DualInputBuffer_ZPM; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.GravitationalLens; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.HolySeparator; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.InfiniteAirHatch; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.InfiniteWirelessDynamoHatch; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.IntensifyChemicalDistorter; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.LargeIndustrialCokingFactory; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.MagneticDomainConstructor; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.MagneticDrivePressureFormer; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.MagneticMixer; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.MegaBrickedBlastFurnace; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.MiracleDoor; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.MoleculeDeconstructor; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.OpticalSOC; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.OreProcessingFactory; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.ParticleTrapTimeSpaceShield; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeEV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeHV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeIV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeLV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeLuV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeMAX; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeMV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeUEV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeUHV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeUIV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeUMV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeUV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeUXV; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhotonControllerUpgradeZPM; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.PhysicalFormSwitcher; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.Scavenger; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.Silksong; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.SpaceScaler; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.SpaceWarper; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.StellarConstructionFrameMaterial; import static com.Nxer.TwistSpaceTechnology.util.Utils.copyAmount; import static com.Nxer.TwistSpaceTechnology.util.Utils.setStackSize; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_EV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_HV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_IV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_LV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_LuV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_MAX; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_MV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UEV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UHV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UIV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UMV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UXV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_ZPM; import static com.dreammaster.gthandler.CustomItemList.AutoclaveUHV; import static com.dreammaster.gthandler.CustomItemList.CentrifugeUV; import static com.dreammaster.gthandler.CustomItemList.CompressorUHV; import static com.dreammaster.gthandler.CustomItemList.CuttingMachineUHV; import static com.dreammaster.gthandler.CustomItemList.ElectrolyzerUV; import static com.dreammaster.gthandler.CustomItemList.ElectromagneticSeparatorUHV; import static com.dreammaster.gthandler.CustomItemList.ExtractorUHV; import static com.dreammaster.gthandler.CustomItemList.FluidExtractorUV; import static com.dreammaster.gthandler.CustomItemList.FluidSolidifierUV; import static com.dreammaster.gthandler.CustomItemList.HighEnergyFlowCircuit; import static com.dreammaster.gthandler.CustomItemList.MixerUV; import static com.dreammaster.gthandler.CustomItemList.PikoCircuit; import static com.dreammaster.gthandler.CustomItemList.PolarizerUHV; import static com.dreammaster.gthandler.CustomItemList.QuantumCircuit; import static com.dreammaster.gthandler.CustomItemList.SlicingMachineUHV; import static com.dreammaster.gthandler.CustomItemList.Transformer_MAX_UXV; import static com.dreammaster.gthandler.CustomItemList.Transformer_UIV_UEV; import static com.dreammaster.gthandler.CustomItemList.Transformer_UMV_UIV; import static com.dreammaster.gthandler.CustomItemList.Transformer_UXV_UMV; import static com.dreammaster.gthandler.CustomItemList.WiremillUV; import static com.github.technus.tectech.thing.CustomItemList.EOH_Infinite_Energy_Casing; import static com.github.technus.tectech.thing.CustomItemList.EOH_Reinforced_Temporal_Casing; import static com.github.technus.tectech.thing.CustomItemList.Machine_Multi_Transformer; import static com.github.technus.tectech.thing.CustomItemList.SpacetimeCompressionFieldGeneratorTier8; import static com.github.technus.tectech.thing.CustomItemList.StabilisationFieldGeneratorTier8; import static com.github.technus.tectech.thing.CustomItemList.TimeAccelerationFieldGeneratorTier8; import static com.github.technus.tectech.thing.CustomItemList.eM_Coil; import static com.github.technus.tectech.thing.CustomItemList.eM_Containment_Field; import static com.github.technus.tectech.thing.CustomItemList.eM_Hollow; import static com.github.technus.tectech.thing.CustomItemList.eM_Spacetime; import static com.github.technus.tectech.thing.CustomItemList.eM_Teleportation; import static com.github.technus.tectech.thing.CustomItemList.eM_Ultimate_Containment; import static com.github.technus.tectech.thing.CustomItemList.eM_Ultimate_Containment_Advanced; import static com.github.technus.tectech.thing.CustomItemList.eM_Ultimate_Containment_Field; import static galaxyspace.core.register.GSMaterials.tantalumCarbideHafniumCarbideMixture; import static goodgenerator.util.ItemRefer.Component_Assembly_Line; import static gregtech.api.enums.Mods.GTPlusPlus; import static gregtech.api.util.GT_RecipeBuilder.HOURS; import static gregtech.api.util.GT_RecipeConstants.AssemblyLine; import static gregtech.api.util.GT_RecipeConstants.RESEARCH_ITEM; import static gregtech.api.util.GT_RecipeConstants.RESEARCH_TIME; import static gtPlusPlus.xmod.gregtech.api.enums.GregtechItemList.Hatch_Air_Intake_Extreme; import static gtPlusPlus.xmod.gregtech.api.enums.GregtechItemList.Industrial_Extruder; import static gtPlusPlus.xmod.gregtech.api.enums.GregtechItemList.Industrial_PlatePress; import static gtPlusPlus.xmod.gregtech.api.enums.GregtechItemList.Mega_AlloyBlastSmelter; import net.glease.ggfab.GGItemList; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import com.Nxer.TwistSpaceTechnology.TwistSpaceTechnology; import com.Nxer.TwistSpaceTechnology.common.GTCMItemList; import com.Nxer.TwistSpaceTechnology.common.material.MaterialPool; import com.Nxer.TwistSpaceTechnology.common.recipeMap.GTCMRecipe; import com.Nxer.TwistSpaceTechnology.loader.MachineLoader; import com.Nxer.TwistSpaceTechnology.recipe.IRecipePool; import com.Nxer.TwistSpaceTechnology.util.recipes.TST_RecipeBuilder; import com.dreammaster.gthandler.CustomItemList; import com.elisis.gtnhlanth.common.register.WerkstoffMaterialPool; import com.github.bartimaeusnek.bartworks.common.configs.ConfigHandler; import com.github.bartimaeusnek.bartworks.common.loaders.BioItemList; import com.github.bartimaeusnek.bartworks.common.loaders.ItemRegistry; import com.github.bartimaeusnek.bartworks.system.material.WerkstoffLoader; import goodgenerator.items.MyMaterial; import goodgenerator.util.ItemRefer; import gregtech.api.enums.GT_Values; import gregtech.api.enums.ItemList; import gregtech.api.enums.Materials; import gregtech.api.enums.MaterialsUEVplus; import gregtech.api.enums.OrePrefixes; import gregtech.api.enums.TierEU; import gregtech.api.interfaces.IItemContainer; import gregtech.api.interfaces.IRecipeMap; import gregtech.api.recipe.RecipeMaps; import gregtech.api.util.GT_ModHandler; import gregtech.api.util.GT_OreDictUnificator; import gregtech.api.util.GT_RecipeConstants; import gregtech.api.util.GT_Utility; import gtPlusPlus.api.recipe.GTPPRecipeMaps; import gtPlusPlus.core.material.ALLOY; import gtPlusPlus.xmod.gregtech.api.enums.GregtechItemList; import ic2.core.Ic2Items;
21,319
package com.Nxer.TwistSpaceTechnology.recipe.machineRecipe; public class GTCMMachineRecipePool implements IRecipePool { // spotless:off @Override public void loadRecipes() { TwistSpaceTechnology.LOG.info("GTCMMachineRecipePool loading recipes."); Fluid solderIndAlloy = FluidRegistry.getFluid("molten.indalloy140"); Fluid solderPlasma = FluidRegistry.getFluid("molten.mutatedlivingsolder"); Fluid celestialTungsten = FluidRegistry.getFluid("molten.celestialtungsten"); IItemContainer eM_Power = com.github.technus.tectech.thing.CustomItemList.eM_Power; final IRecipeMap assemblyLine = GT_RecipeConstants.AssemblyLine; final IRecipeMap assembler = RecipeMaps.assemblerRecipes; // test machine recipe /* GT_Values.RA.stdBuilder() .itemInputs(GT_Utility.getIntegratedCircuit(1)) .fluidInputs( Materials.Hydrogen.getGas(1000), Materials.Helium.getGas(1000), WerkstoffLoader.Neon.getFluidOrGas(1000), Materials.Argon.getGas(1000), WerkstoffLoader.Krypton.getFluidOrGas(1000), WerkstoffLoader.Xenon.getFluidOrGas(1000), Materials.Radon.getGas(1000)) .fluidOutputs(MaterialPool.TestingMaterial.getMolten(144)) // GTNH Version 2.4.1+ don't need call this method , BUT! .specialValue(11451) // set special value, like HeatCapacity is the special value of EBF recipes .noOptimize() // disable the auto optimize of GT Machine recipes .eut(1919810) .duration(114514 * 20) .addTo(GTCMRecipe.instance.IntensifyChemicalDistorterRecipes); */ /* * 2.4.0 and earlier need call these methods: * noItemInputs(); noItemOutputs(); noFluidInputs(); noFluidOutputs(); * So had better call. */ // Intensify Chemical Distorter GT_Values.RA.stdBuilder() .itemInputs( GT_Utility.getIntegratedCircuit(10), copyAmount(1, ItemRegistry.megaMachines[3]), Materials.Carbon.getNanite(16), ItemList.Emitter_UV.get(16), new Object[]{OrePrefixes.circuit.get(Materials.SuperconductorUHV),16}) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 16)) .itemOutputs(IntensifyChemicalDistorter.get(1)) .noOptimize() .eut(RECIPE_UHV) .duration(20 * 120) .addTo(assembler); // region PreciseHighEnergyPhotonicQuantumMaster // PreciseHighEnergyPhotonicQuantumMaster Controller GT_Values.RA.stdBuilder() .itemInputs( eM_Power.get(4), GT_ModHandler.getModItem("gregtech", "gt.blockmachines", 8, 10932), WerkstoffMaterialPool.CeriumDopedLutetiumAluminiumGarnet.get(OrePrefixes.lens, 64), GT_ModHandler.getModItem(GTPlusPlus.ID, "MU-metaitem.01", 1L, 32105), ItemList.Emitter_UV.get(5), ItemList.Field_Generator_UV.get(1), new Object[] { OrePrefixes.circuit.get(Materials.SuperconductorUHV), 4 }, copyAmount(64, Ic2Items.iridiumPlate), GT_Utility.getIntegratedCircuit(10)) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 128)) .itemOutputs(copyAmount(1, MachineLoader.PreciseHighEnergyPhotonicQuantumMaster)) .noOptimize() .eut(RECIPE_UHV) .duration(20 * 120) .addTo(assembler); // Upgrade LV GT_Values.RA.stdBuilder() .itemInputs( ItemList.Casing_Advanced_Iridium.get(1), GT_ModHandler.getModItem("gregtech", "gt.blockmachines", 1, 11100), ItemList.Transformer_MV_LV.get(1), ItemList.Emitter_LV.get(1), GT_OreDictUnificator.get(OrePrefixes.lens, Materials.Diamond, 3), ItemList.Field_Generator_LV.get(1), new Object[] { OrePrefixes.circuit.get(Materials.Basic), 4 }, GT_Utility.getIntegratedCircuit(10)) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 2)) .itemOutputs(PhotonControllerUpgradeLV.get(1)) .eut(RECIPE_LV) .duration(20 * 10) .addTo(assembler); // Upgrade MV GT_Values.RA.stdBuilder() .itemInputs( ItemList.Casing_Advanced_Iridium.get(1), GT_ModHandler.getModItem("gregtech", "gt.blockmachines", 1, 11101), ItemList.Transformer_HV_MV.get(1), ItemList.Emitter_MV.get(1), GT_OreDictUnificator.get(OrePrefixes.lens, Materials.Diamond, 6), ItemList.Field_Generator_MV.get(1), new Object[] { OrePrefixes.circuit.get(Materials.Good), 4 }, GT_Utility.getIntegratedCircuit(10)) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 8)) .itemOutputs(PhotonControllerUpgradeMV.get(1)) .eut(RECIPE_MV) .duration(20 * 20) .addTo(assembler); // Upgrade HV GT_Values.RA.stdBuilder() .itemInputs( ItemList.Casing_Advanced_Iridium.get(1), GT_ModHandler.getModItem("gregtech", "gt.blockmachines", 1, 11102), ItemList.Transformer_EV_HV.get(1), ItemList.Emitter_HV.get(1), GT_OreDictUnificator.get(OrePrefixes.lens, Materials.Diamond, 12), ItemList.Field_Generator_HV.get(1), new Object[] { OrePrefixes.circuit.get(Materials.Advanced), 4 }, GT_Utility.getIntegratedCircuit(10)) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 32)) .itemOutputs(PhotonControllerUpgradeHV.get(1)) .eut(RECIPE_HV) .duration(20 * 40) .addTo(assembler); // Upgrade EV GT_Values.RA.stdBuilder() .itemInputs( ItemList.Casing_Advanced_Iridium.get(1), GT_ModHandler.getModItem("gregtech", "gt.blockmachines", 1, 11103), ItemList.Transformer_IV_EV.get(1), ItemList.Emitter_EV.get(1), GT_OreDictUnificator.get(OrePrefixes.lens, Materials.Diamond, 24), ItemList.Field_Generator_EV.get(1), new Object[] { OrePrefixes.circuit.get(Materials.Data), 4 }, GT_Utility.getIntegratedCircuit(10)) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 128)) .itemOutputs(PhotonControllerUpgradeEV.get(1))
package com.Nxer.TwistSpaceTechnology.recipe.machineRecipe; public class GTCMMachineRecipePool implements IRecipePool { // spotless:off @Override public void loadRecipes() { TwistSpaceTechnology.LOG.info("GTCMMachineRecipePool loading recipes."); Fluid solderIndAlloy = FluidRegistry.getFluid("molten.indalloy140"); Fluid solderPlasma = FluidRegistry.getFluid("molten.mutatedlivingsolder"); Fluid celestialTungsten = FluidRegistry.getFluid("molten.celestialtungsten"); IItemContainer eM_Power = com.github.technus.tectech.thing.CustomItemList.eM_Power; final IRecipeMap assemblyLine = GT_RecipeConstants.AssemblyLine; final IRecipeMap assembler = RecipeMaps.assemblerRecipes; // test machine recipe /* GT_Values.RA.stdBuilder() .itemInputs(GT_Utility.getIntegratedCircuit(1)) .fluidInputs( Materials.Hydrogen.getGas(1000), Materials.Helium.getGas(1000), WerkstoffLoader.Neon.getFluidOrGas(1000), Materials.Argon.getGas(1000), WerkstoffLoader.Krypton.getFluidOrGas(1000), WerkstoffLoader.Xenon.getFluidOrGas(1000), Materials.Radon.getGas(1000)) .fluidOutputs(MaterialPool.TestingMaterial.getMolten(144)) // GTNH Version 2.4.1+ don't need call this method , BUT! .specialValue(11451) // set special value, like HeatCapacity is the special value of EBF recipes .noOptimize() // disable the auto optimize of GT Machine recipes .eut(1919810) .duration(114514 * 20) .addTo(GTCMRecipe.instance.IntensifyChemicalDistorterRecipes); */ /* * 2.4.0 and earlier need call these methods: * noItemInputs(); noItemOutputs(); noFluidInputs(); noFluidOutputs(); * So had better call. */ // Intensify Chemical Distorter GT_Values.RA.stdBuilder() .itemInputs( GT_Utility.getIntegratedCircuit(10), copyAmount(1, ItemRegistry.megaMachines[3]), Materials.Carbon.getNanite(16), ItemList.Emitter_UV.get(16), new Object[]{OrePrefixes.circuit.get(Materials.SuperconductorUHV),16}) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 16)) .itemOutputs(IntensifyChemicalDistorter.get(1)) .noOptimize() .eut(RECIPE_UHV) .duration(20 * 120) .addTo(assembler); // region PreciseHighEnergyPhotonicQuantumMaster // PreciseHighEnergyPhotonicQuantumMaster Controller GT_Values.RA.stdBuilder() .itemInputs( eM_Power.get(4), GT_ModHandler.getModItem("gregtech", "gt.blockmachines", 8, 10932), WerkstoffMaterialPool.CeriumDopedLutetiumAluminiumGarnet.get(OrePrefixes.lens, 64), GT_ModHandler.getModItem(GTPlusPlus.ID, "MU-metaitem.01", 1L, 32105), ItemList.Emitter_UV.get(5), ItemList.Field_Generator_UV.get(1), new Object[] { OrePrefixes.circuit.get(Materials.SuperconductorUHV), 4 }, copyAmount(64, Ic2Items.iridiumPlate), GT_Utility.getIntegratedCircuit(10)) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 128)) .itemOutputs(copyAmount(1, MachineLoader.PreciseHighEnergyPhotonicQuantumMaster)) .noOptimize() .eut(RECIPE_UHV) .duration(20 * 120) .addTo(assembler); // Upgrade LV GT_Values.RA.stdBuilder() .itemInputs( ItemList.Casing_Advanced_Iridium.get(1), GT_ModHandler.getModItem("gregtech", "gt.blockmachines", 1, 11100), ItemList.Transformer_MV_LV.get(1), ItemList.Emitter_LV.get(1), GT_OreDictUnificator.get(OrePrefixes.lens, Materials.Diamond, 3), ItemList.Field_Generator_LV.get(1), new Object[] { OrePrefixes.circuit.get(Materials.Basic), 4 }, GT_Utility.getIntegratedCircuit(10)) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 2)) .itemOutputs(PhotonControllerUpgradeLV.get(1)) .eut(RECIPE_LV) .duration(20 * 10) .addTo(assembler); // Upgrade MV GT_Values.RA.stdBuilder() .itemInputs( ItemList.Casing_Advanced_Iridium.get(1), GT_ModHandler.getModItem("gregtech", "gt.blockmachines", 1, 11101), ItemList.Transformer_HV_MV.get(1), ItemList.Emitter_MV.get(1), GT_OreDictUnificator.get(OrePrefixes.lens, Materials.Diamond, 6), ItemList.Field_Generator_MV.get(1), new Object[] { OrePrefixes.circuit.get(Materials.Good), 4 }, GT_Utility.getIntegratedCircuit(10)) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 8)) .itemOutputs(PhotonControllerUpgradeMV.get(1)) .eut(RECIPE_MV) .duration(20 * 20) .addTo(assembler); // Upgrade HV GT_Values.RA.stdBuilder() .itemInputs( ItemList.Casing_Advanced_Iridium.get(1), GT_ModHandler.getModItem("gregtech", "gt.blockmachines", 1, 11102), ItemList.Transformer_EV_HV.get(1), ItemList.Emitter_HV.get(1), GT_OreDictUnificator.get(OrePrefixes.lens, Materials.Diamond, 12), ItemList.Field_Generator_HV.get(1), new Object[] { OrePrefixes.circuit.get(Materials.Advanced), 4 }, GT_Utility.getIntegratedCircuit(10)) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 32)) .itemOutputs(PhotonControllerUpgradeHV.get(1)) .eut(RECIPE_HV) .duration(20 * 40) .addTo(assembler); // Upgrade EV GT_Values.RA.stdBuilder() .itemInputs( ItemList.Casing_Advanced_Iridium.get(1), GT_ModHandler.getModItem("gregtech", "gt.blockmachines", 1, 11103), ItemList.Transformer_IV_EV.get(1), ItemList.Emitter_EV.get(1), GT_OreDictUnificator.get(OrePrefixes.lens, Materials.Diamond, 24), ItemList.Field_Generator_EV.get(1), new Object[] { OrePrefixes.circuit.get(Materials.Data), 4 }, GT_Utility.getIntegratedCircuit(10)) .fluidInputs(Materials.SolderingAlloy.getMolten(144 * 128)) .itemOutputs(PhotonControllerUpgradeEV.get(1))
.eut(RECIPE_EV)
2
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,867
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); } private static class InstanceHolder { private static final GoRouter mInstance = new GoRouter(); } public static GoRouter getInstance() { return InstanceHolder.mInstance; } /** * 自动加载模块路由 * * @param application */ public static synchronized void autoLoadRouteModule(Application application) { setApplication(application); logger.info(null, "[GoRouter] autoLoadRouteModule!");
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); } private static class InstanceHolder { private static final GoRouter mInstance = new GoRouter(); } public static GoRouter getInstance() { return InstanceHolder.mInstance; } /** * 自动加载模块路由 * * @param application */ public static synchronized void autoLoadRouteModule(Application application) { setApplication(application); logger.info(null, "[GoRouter] autoLoadRouteModule!");
RouteModuleCenter.load(application);
7
2023-10-18 13:52:07+00:00
24k
trpc-group/trpc-java
trpc-proto/trpc-proto-standard/src/main/java/com/tencent/trpc/proto/standard/stream/client/StreamConsumerInvoker.java
[ { "identifier": "BackendConfig", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/config/BackendConfig.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic class BackendConfig extends BaseProtocolConfig {\n\n protected static final AtomicLong NAME_GENERATOR_INDEX = new AtomicLong(...
import com.tencent.trpc.core.common.config.BackendConfig; import com.tencent.trpc.core.common.config.ConsumerConfig; import com.tencent.trpc.core.common.config.ProtocolConfig; import com.tencent.trpc.core.exception.ErrorCode; import com.tencent.trpc.core.exception.TRpcException; import com.tencent.trpc.core.logger.Logger; import com.tencent.trpc.core.logger.LoggerFactory; import com.tencent.trpc.core.rpc.ConsumerInvoker; import com.tencent.trpc.core.rpc.InvokeMode; import com.tencent.trpc.core.rpc.Request; import com.tencent.trpc.core.rpc.Response; import com.tencent.trpc.core.rpc.RpcContext; import com.tencent.trpc.core.rpc.RpcContextValueKeys; import com.tencent.trpc.core.rpc.RpcInvocation; import com.tencent.trpc.core.rpc.def.DefResponse; import com.tencent.trpc.core.stream.transport.ClientTransport; import com.tencent.trpc.core.stream.transport.RpcConnection; import com.tencent.trpc.core.utils.RpcContextUtils; import com.tencent.trpc.proto.standard.stream.TRpcStreamRequester; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.SignalType; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer;
19,769
/* * 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.proto.standard.stream.client; /** * Invoker that supports streaming calls * * @param <T> service interface type */ public class StreamConsumerInvoker<T> implements ConsumerInvoker<T> { private static final Logger logger = LoggerFactory.getLogger(StreamConsumerInvoker.class); private static final int STREAM_CLOSE_COUNT_BOTH_DIRECTION = 2; /** * Client interface related configuration */ private final ConsumerConfig<T> consumerConfig; /** * Client related configuration */ private final BackendConfig backendConfig; /** * Protocol related configuration */ private final ProtocolConfig protocolConfig; /** * Client transport */ private final ClientTransport clientTransport; public StreamConsumerInvoker(ConsumerConfig<T> consumerConfig, ProtocolConfig protocolConfig, ClientTransport clientTransport) { this.consumerConfig = Objects.requireNonNull(consumerConfig, "consumerConfig is null"); this.backendConfig = Objects .requireNonNull(consumerConfig.getBackendConfig(), "backendConfig is null"); this.protocolConfig = Objects.requireNonNull(protocolConfig, "protocolConfig is null"); this.clientTransport = Objects.requireNonNull(clientTransport, "clientTransport is null"); } @Override public ConsumerConfig<T> getConfig() { return consumerConfig; } @Override public ProtocolConfig getProtocolConfig() { return protocolConfig; } @Override @SuppressWarnings("unchecked") public Class<T> getInterface() { return (Class<T>) backendConfig.getServiceInterface(); } @Override public CompletionStage<Response> invoke(Request request) { CompletableFuture<Response> future = new CompletableFuture<>(); // create a link and perform a remote call clientTransport .connect() .subscribe(conn -> { try { TRpcStreamRequester requester = new TRpcStreamRequester(protocolConfig, conn, consumerConfig.getBackendConfig()); // Encapsulate the returned result into DefResponse and integrate with the current // rpc framework. DefResponse rpcResponse = new DefResponse(); rpcResponse.setValue(doInvoke(request, requester, conn)); future.complete(rpcResponse); } catch (Throwable t) { conn.dispose(); future.completeExceptionally(TRpcException.newFrameException(ErrorCode.TRPC_CLIENT_NETWORK_ERR, "do invoke failed", t)); } }, t -> future.completeExceptionally( TRpcException.newFrameException(ErrorCode.TRPC_CLIENT_CONNECT_ERR, "do connect failed", t) )); return future; } /** * Perform a remote call * * @param request request data * @param requester streaming requester, encapsulating streaming request logic * @return remote call result */ @SuppressWarnings("ReactiveStreamsUnusedPublisher") private Object doInvoke(Request request, TRpcStreamRequester requester, RpcConnection connection) { // get invoker information
/* * 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.proto.standard.stream.client; /** * Invoker that supports streaming calls * * @param <T> service interface type */ public class StreamConsumerInvoker<T> implements ConsumerInvoker<T> { private static final Logger logger = LoggerFactory.getLogger(StreamConsumerInvoker.class); private static final int STREAM_CLOSE_COUNT_BOTH_DIRECTION = 2; /** * Client interface related configuration */ private final ConsumerConfig<T> consumerConfig; /** * Client related configuration */ private final BackendConfig backendConfig; /** * Protocol related configuration */ private final ProtocolConfig protocolConfig; /** * Client transport */ private final ClientTransport clientTransport; public StreamConsumerInvoker(ConsumerConfig<T> consumerConfig, ProtocolConfig protocolConfig, ClientTransport clientTransport) { this.consumerConfig = Objects.requireNonNull(consumerConfig, "consumerConfig is null"); this.backendConfig = Objects .requireNonNull(consumerConfig.getBackendConfig(), "backendConfig is null"); this.protocolConfig = Objects.requireNonNull(protocolConfig, "protocolConfig is null"); this.clientTransport = Objects.requireNonNull(clientTransport, "clientTransport is null"); } @Override public ConsumerConfig<T> getConfig() { return consumerConfig; } @Override public ProtocolConfig getProtocolConfig() { return protocolConfig; } @Override @SuppressWarnings("unchecked") public Class<T> getInterface() { return (Class<T>) backendConfig.getServiceInterface(); } @Override public CompletionStage<Response> invoke(Request request) { CompletableFuture<Response> future = new CompletableFuture<>(); // create a link and perform a remote call clientTransport .connect() .subscribe(conn -> { try { TRpcStreamRequester requester = new TRpcStreamRequester(protocolConfig, conn, consumerConfig.getBackendConfig()); // Encapsulate the returned result into DefResponse and integrate with the current // rpc framework. DefResponse rpcResponse = new DefResponse(); rpcResponse.setValue(doInvoke(request, requester, conn)); future.complete(rpcResponse); } catch (Throwable t) { conn.dispose(); future.completeExceptionally(TRpcException.newFrameException(ErrorCode.TRPC_CLIENT_NETWORK_ERR, "do invoke failed", t)); } }, t -> future.completeExceptionally( TRpcException.newFrameException(ErrorCode.TRPC_CLIENT_CONNECT_ERR, "do connect failed", t) )); return future; } /** * Perform a remote call * * @param request request data * @param requester streaming requester, encapsulating streaming request logic * @return remote call result */ @SuppressWarnings("ReactiveStreamsUnusedPublisher") private Object doInvoke(Request request, TRpcStreamRequester requester, RpcConnection connection) { // get invoker information
RpcInvocation invocation = request.getInvocation();
13
2023-10-19 10:54:11+00:00
24k
eclipse-jgit/jgit
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/RevList.java
[ { "identifier": "ObjectWalk", "path": "org.eclipse.jgit/src/org/eclipse/jgit/revwalk/ObjectWalk.java", "snippet": "public class ObjectWalk extends RevWalk {\n\tprivate static final int ID_SZ = 20;\n\tprivate static final int TYPE_SHIFT = 12;\n\tprivate static final int TYPE_TREE = 0040000 >>> TYPE_SHIFT...
import org.eclipse.jgit.revwalk.ObjectWalk; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevFlag; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevTree;
16,109
/* * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> 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.pgm; @Command(usage = "usage_RevList") class RevList extends RevWalkTextBuiltin { @Override protected void show(RevCommit c) throws Exception { if (c.has(RevFlag.UNINTERESTING)) outw.print('-'); c.getId().copyTo(outbuffer, outw); if (parents) for (int i = 0; i < c.getParentCount(); i++) { outw.print(' '); c.getParent(i).getId().copyTo(outbuffer, outw); } outw.println(); } @Override
/* * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> 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.pgm; @Command(usage = "usage_RevList") class RevList extends RevWalkTextBuiltin { @Override protected void show(RevCommit c) throws Exception { if (c.has(RevFlag.UNINTERESTING)) outw.print('-'); c.getId().copyTo(outbuffer, outw); if (parents) for (int i = 0; i < c.getParentCount(); i++) { outw.print(' '); c.getParent(i).getId().copyTo(outbuffer, outw); } outw.println(); } @Override
protected void show(ObjectWalk ow, RevObject obj)
3
2023-10-20 15:09:17+00:00
24k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/about/IfwBackupListFragment.java
[ { "identifier": "IfwUtil", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/IfwUtil.java", "snippet": "public class IfwUtil {\n private static final String TAG = \"IfwUtil\";\n private static final String SYSTEM_PROPERTY_EFS_ENABLED = \"persist.security.efs.enabled\";\n\n public static...
import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.List; import java.util.UUID; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.IfwUtil; import cn.wq.myandroidtoolspro.helper.Utils; import cn.wq.myandroidtoolspro.helper.ZipUtil; import cn.wq.myandroidtoolspro.recyclerview.toolbar.RecyclerWithToolbarFragment; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers;
18,990
package cn.wq.myandroidtoolspro.recyclerview.fragment.about; /** * ifw备份文件编辑显示app列表 */ @Deprecated public class IfwBackupListFragment extends RecyclerWithToolbarFragment { private BackupAdapter mAdapter; private MenuItem toggleMenuItem; private final static int REQUEST_CODE_RENAME = 88; private String path; private Context mContext; private CompositeDisposable compositeDisposable; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); path = getArguments().getString("path"); mAdapter = new BackupAdapter(mContext); setAdapter(mAdapter); setEmptyText(getString(R.string.empty)); initActionbar(1, path.substring(path.lastIndexOf("/") + 1)); if (compositeDisposable != null) { compositeDisposable.clear(); } loadData(); } private void loadData() { Disposable disposable = Observable.create(new ObservableOnSubscribe<List<BackupEntry>>() { @Override public void subscribe(ObservableEmitter<List<BackupEntry>> emitter) throws Exception { //临时目录 File dir = new File(getContext().getExternalCacheDir(), UUID.randomUUID().toString()); if (!dir.exists()) { dir.mkdirs(); } ZipUtil.unzip(path, dir); String[] files = dir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) {
package cn.wq.myandroidtoolspro.recyclerview.fragment.about; /** * ifw备份文件编辑显示app列表 */ @Deprecated public class IfwBackupListFragment extends RecyclerWithToolbarFragment { private BackupAdapter mAdapter; private MenuItem toggleMenuItem; private final static int REQUEST_CODE_RENAME = 88; private String path; private Context mContext; private CompositeDisposable compositeDisposable; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); path = getArguments().getString("path"); mAdapter = new BackupAdapter(mContext); setAdapter(mAdapter); setEmptyText(getString(R.string.empty)); initActionbar(1, path.substring(path.lastIndexOf("/") + 1)); if (compositeDisposable != null) { compositeDisposable.clear(); } loadData(); } private void loadData() { Disposable disposable = Observable.create(new ObservableOnSubscribe<List<BackupEntry>>() { @Override public void subscribe(ObservableEmitter<List<BackupEntry>> emitter) throws Exception { //临时目录 File dir = new File(getContext().getExternalCacheDir(), UUID.randomUUID().toString()); if (!dir.exists()) { dir.mkdirs(); } ZipUtil.unzip(path, dir); String[] files = dir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) {
return name.endsWith(IfwUtil.BACKUP_SYSTEM_FILE_EXT_OF_MINE);
0
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,448
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<>();
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;
1
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;
14,916
/** * <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) {
/* * 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");
0
2023-10-15 15:56:58+00:00
24k
histevehu/12306
member/src/main/java/com/steve/train/member/service/TicketService.java
[ { "identifier": "MemberTicketReq", "path": "common/src/main/java/com/steve/train/common/req/MemberTicketReq.java", "snippet": "public class MemberTicketReq {\n\n /**\n * 乘客id\n */\n @NotNull(message = \"【会员id】不能为空\")\n private Long memberId;\n\n /**\n * 乘客id\n */\n @NotNul...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.util.ObjUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.steve.train.common.req.MemberTicketReq; import com.steve.train.common.resp.PageResp; import com.steve.train.common.util.SnowFlakeUtil; import com.steve.train.member.domain.Ticket; import com.steve.train.member.domain.TicketExample; import com.steve.train.member.mapper.TicketMapper; import com.steve.train.member.req.TicketQueryReq; import com.steve.train.member.resp.TicketQueryResp; import io.seata.core.context.RootContext; import jakarta.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List;
15,113
package com.steve.train.member.service; /* * @author : Steve Hu * @date : 2023-11-07 14:53:44 * @description: 车票服务(FreeMarker生成) */ @Service public class TicketService { private static final Logger LOG = LoggerFactory.getLogger(TicketService.class); @Resource private TicketMapper ticketMapper; public void save(MemberTicketReq req) throws Exception { LOG.info("seata全局事务ID save: {}", RootContext.getXID()); DateTime now = DateTime.now(); Ticket ticket = BeanUtil.copyProperties(req, Ticket.class); ticket.setId(SnowFlakeUtil.getSnowFlakeNextId()); ticket.setCreateTime(now); ticket.setUpdateTime(now); ticketMapper.insert(ticket); }
package com.steve.train.member.service; /* * @author : Steve Hu * @date : 2023-11-07 14:53:44 * @description: 车票服务(FreeMarker生成) */ @Service public class TicketService { private static final Logger LOG = LoggerFactory.getLogger(TicketService.class); @Resource private TicketMapper ticketMapper; public void save(MemberTicketReq req) throws Exception { LOG.info("seata全局事务ID save: {}", RootContext.getXID()); DateTime now = DateTime.now(); Ticket ticket = BeanUtil.copyProperties(req, Ticket.class); ticket.setId(SnowFlakeUtil.getSnowFlakeNextId()); ticket.setCreateTime(now); ticket.setUpdateTime(now); ticketMapper.insert(ticket); }
public PageResp<TicketQueryResp> queryList(TicketQueryReq req) {
1
2023-10-23 01:20:56+00:00
24k
team-moabam/moabam-BE
src/test/java/com/moabam/api/presentation/MemberControllerTest.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 org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.BDDMockito.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; import static org.springframework.test.web.client.response.MockRestResponseCreators.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Objects; import java.util.Optional; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureMockRestServiceServer; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Import; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.match.MockRestRequestMatchers; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; import com.moabam.api.application.auth.OAuth2AuthorizationServerRequestService; import com.moabam.api.application.image.ImageService; import com.moabam.api.application.member.MemberMapper; import com.moabam.api.domain.auth.repository.TokenRepository; import com.moabam.api.domain.image.ImageType; import com.moabam.api.domain.item.Inventory; import com.moabam.api.domain.item.Item; import com.moabam.api.domain.item.repository.InventoryRepository; import com.moabam.api.domain.item.repository.ItemRepository; import com.moabam.api.domain.member.Badge; import com.moabam.api.domain.member.BadgeType; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.member.Role; import com.moabam.api.domain.member.repository.BadgeRepository; import com.moabam.api.domain.member.repository.MemberRepository; import com.moabam.api.domain.member.repository.MemberSearchRepository; import com.moabam.api.domain.room.Participant; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.repository.ParticipantRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.dto.auth.TokenSaveValue; import com.moabam.api.dto.member.ModifyMemberRequest; import com.moabam.api.dto.ranking.RankingInfo; import com.moabam.global.config.EmbeddedRedisConfig; import com.moabam.global.config.OAuthConfig; import com.moabam.global.error.exception.UnauthorizedException; import com.moabam.global.error.handler.RestTemplateResponseHandler; import com.moabam.support.annotation.WithMember; import com.moabam.support.common.WithoutFilterSupporter; import com.moabam.support.fixture.BadgeFixture; import com.moabam.support.fixture.InventoryFixture; import com.moabam.support.fixture.ItemFixture; import com.moabam.support.fixture.MemberFixture; import com.moabam.support.fixture.ParticipantFixture; import com.moabam.support.fixture.RoomFixture; import com.moabam.support.fixture.TokenSaveValueFixture; import jakarta.persistence.EntityManager;
15,080
memberRepository.save(member); } @BeforeEach void setUp() { RestTemplate restTemplate = restTemplateBuilder.build(); ReflectionTestUtils.setField(oAuth2AuthorizationServerRequestService, "restTemplate", restTemplate); mockRestServiceServer = MockRestServiceServer.createServer(restTemplate); member = entityManager.merge(member); } @DisplayName("로그아웃 성공 테스트") @WithMember @Test void logout_success() throws Exception { // given TokenSaveValue tokenSaveValue = TokenSaveValueFixture.tokenSaveValue(); tokenRepository.saveToken(member.getId(), tokenSaveValue, Role.USER); // expected ResultActions result = mockMvc.perform(get("/members/logout")); result.andExpect(status().is2xxSuccessful()); Assertions.assertThatThrownBy(() -> tokenRepository.getTokenSaveValue(member.getId(), Role.USER)) .isInstanceOf(UnauthorizedException.class); } @DisplayName("회원 삭제 성공 테스트") @WithMember @Test void delete_member_success() throws Exception { // Given String nickname = member.getNickname(); // expected mockRestServiceServer.expect(requestTo(oAuthConfig.provider().unlink())) .andExpect(MockRestRequestMatchers.content() .contentType("application/x-www-form-urlencoded;charset=UTF-8")) .andExpect(MockRestRequestMatchers.header( "Authorization", "KakaoAK " + oAuthConfig.client().adminKey())) .andExpect(method(HttpMethod.POST)) .andRespond(withStatus(HttpStatus.OK)); mockMvc.perform(delete("/members")); memberRepository.flush(); Optional<Member> deletedMemberOptional = memberRepository.findById(member.getId()); assertThat(deletedMemberOptional).isNotEmpty(); Member deletedMEmber = deletedMemberOptional.get(); assertThat(deletedMEmber.getDeletedAt()).isNotNull(); assertThat(deletedMEmber.getNickname()).isNull(); } @DisplayName("회원이 없어서 회원 삭제 실패") @WithMember(id = 123L) @Test void delete_member_failBy_not_found_member() throws Exception { // expected mockMvc.perform(delete("/members")) .andExpect(status().isNotFound()); } @DisplayName("연결 오류로 인한 카카오 연결 끊기 실패로 롤백") @WithMember @ParameterizedTest @ValueSource(ints = {401, 400}) void unlink_social_member_failby_connection_error_and_rollback(int code) throws Exception { // expected mockRestServiceServer.expect(requestTo(oAuthConfig.provider().unlink())) .andExpect(MockRestRequestMatchers.header( "Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")) .andExpect(MockRestRequestMatchers.header( "Authorization", "KakaoAK " + oAuthConfig.client().adminKey())) .andExpect(method(HttpMethod.POST)) .andRespond(withStatus(HttpStatusCode.valueOf(code))); ResultActions result = mockMvc.perform(delete("/members")); result.andExpect(status().isBadRequest()); Optional<Member> rollbackMemberOptional = memberSearchRepository.findMember(member.getId()); assertThat(rollbackMemberOptional).isPresent(); Member rollMember = rollbackMemberOptional.get(); assertAll( () -> assertThat(rollMember.getSocialId()).isEqualTo(member.getSocialId()), () -> assertThat(rollMember.getDeletedAt()).isNull() ); } @DisplayName("방장으로 인해 회원 삭제 조회 실패") @WithMember @Test void unlink_social_member_failby_meber_is_manger() throws Exception { // given Room room = RoomFixture.room(); room.changeManagerNickname(member.getNickname()); Participant participant = ParticipantFixture.participant(room, member.getId()); participant.enableManager(); roomRepository.save(room); participantRepository.save(participant); // then mockMvc.perform(delete("/members")) .andExpect(status().isNotFound()); } @DisplayName("내 정보 조회 성공") @WithMember @Test void search_my_info_success() throws Exception { // given Badge birth = BadgeFixture.badge(member.getId(), BadgeType.BIRTH); Badge level50 = BadgeFixture.badge(member.getId(), BadgeType.LEVEL50); Badge level10 = BadgeFixture.badge(member.getId(), BadgeType.LEVEL10); List<Badge> badges = List.of(birth, level10, level50); badgeRepository.saveAll(badges);
package com.moabam.api.presentation; @Transactional @SpringBootTest @AutoConfigureMockMvc @AutoConfigureMockRestServiceServer @TestInstance(TestInstance.Lifecycle.PER_CLASS) @Import(EmbeddedRedisConfig.class) class MemberControllerTest extends WithoutFilterSupporter { @Autowired MockMvc mockMvc; @Autowired ObjectMapper objectMapper; @Autowired MemberRepository memberRepository; @Autowired MemberSearchRepository memberSearchRepository; @Autowired TokenRepository tokenRepository; @Autowired RoomRepository roomRepository; @Autowired ItemRepository itemRepository; @Autowired BadgeRepository badgeRepository; @Autowired InventoryRepository inventoryRepository; @Autowired ParticipantRepository participantRepository; @Autowired OAuth2AuthorizationServerRequestService oAuth2AuthorizationServerRequestService; @Autowired OAuthConfig oAuthConfig; @SpyBean ImageService imageService; RestTemplateBuilder restTemplateBuilder; MockRestServiceServer mockRestServiceServer; Member member; @Autowired EntityManager entityManager; @Autowired RedisTemplate<String, Object> redisTemplate; @BeforeAll void allSetUp() { restTemplateBuilder = new RestTemplateBuilder() .errorHandler(new RestTemplateResponseHandler()); member = MemberFixture.member("1234567890987654"); member.increaseTotalCertifyCount(); memberRepository.save(member); } @BeforeEach void setUp() { RestTemplate restTemplate = restTemplateBuilder.build(); ReflectionTestUtils.setField(oAuth2AuthorizationServerRequestService, "restTemplate", restTemplate); mockRestServiceServer = MockRestServiceServer.createServer(restTemplate); member = entityManager.merge(member); } @DisplayName("로그아웃 성공 테스트") @WithMember @Test void logout_success() throws Exception { // given TokenSaveValue tokenSaveValue = TokenSaveValueFixture.tokenSaveValue(); tokenRepository.saveToken(member.getId(), tokenSaveValue, Role.USER); // expected ResultActions result = mockMvc.perform(get("/members/logout")); result.andExpect(status().is2xxSuccessful()); Assertions.assertThatThrownBy(() -> tokenRepository.getTokenSaveValue(member.getId(), Role.USER)) .isInstanceOf(UnauthorizedException.class); } @DisplayName("회원 삭제 성공 테스트") @WithMember @Test void delete_member_success() throws Exception { // Given String nickname = member.getNickname(); // expected mockRestServiceServer.expect(requestTo(oAuthConfig.provider().unlink())) .andExpect(MockRestRequestMatchers.content() .contentType("application/x-www-form-urlencoded;charset=UTF-8")) .andExpect(MockRestRequestMatchers.header( "Authorization", "KakaoAK " + oAuthConfig.client().adminKey())) .andExpect(method(HttpMethod.POST)) .andRespond(withStatus(HttpStatus.OK)); mockMvc.perform(delete("/members")); memberRepository.flush(); Optional<Member> deletedMemberOptional = memberRepository.findById(member.getId()); assertThat(deletedMemberOptional).isNotEmpty(); Member deletedMEmber = deletedMemberOptional.get(); assertThat(deletedMEmber.getDeletedAt()).isNotNull(); assertThat(deletedMEmber.getNickname()).isNull(); } @DisplayName("회원이 없어서 회원 삭제 실패") @WithMember(id = 123L) @Test void delete_member_failBy_not_found_member() throws Exception { // expected mockMvc.perform(delete("/members")) .andExpect(status().isNotFound()); } @DisplayName("연결 오류로 인한 카카오 연결 끊기 실패로 롤백") @WithMember @ParameterizedTest @ValueSource(ints = {401, 400}) void unlink_social_member_failby_connection_error_and_rollback(int code) throws Exception { // expected mockRestServiceServer.expect(requestTo(oAuthConfig.provider().unlink())) .andExpect(MockRestRequestMatchers.header( "Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")) .andExpect(MockRestRequestMatchers.header( "Authorization", "KakaoAK " + oAuthConfig.client().adminKey())) .andExpect(method(HttpMethod.POST)) .andRespond(withStatus(HttpStatusCode.valueOf(code))); ResultActions result = mockMvc.perform(delete("/members")); result.andExpect(status().isBadRequest()); Optional<Member> rollbackMemberOptional = memberSearchRepository.findMember(member.getId()); assertThat(rollbackMemberOptional).isPresent(); Member rollMember = rollbackMemberOptional.get(); assertAll( () -> assertThat(rollMember.getSocialId()).isEqualTo(member.getSocialId()), () -> assertThat(rollMember.getDeletedAt()).isNull() ); } @DisplayName("방장으로 인해 회원 삭제 조회 실패") @WithMember @Test void unlink_social_member_failby_meber_is_manger() throws Exception { // given Room room = RoomFixture.room(); room.changeManagerNickname(member.getNickname()); Participant participant = ParticipantFixture.participant(room, member.getId()); participant.enableManager(); roomRepository.save(room); participantRepository.save(participant); // then mockMvc.perform(delete("/members")) .andExpect(status().isNotFound()); } @DisplayName("내 정보 조회 성공") @WithMember @Test void search_my_info_success() throws Exception { // given Badge birth = BadgeFixture.badge(member.getId(), BadgeType.BIRTH); Badge level50 = BadgeFixture.badge(member.getId(), BadgeType.LEVEL50); Badge level10 = BadgeFixture.badge(member.getId(), BadgeType.LEVEL10); List<Badge> badges = List.of(birth, level10, level50); badgeRepository.saveAll(badges);
Item night = ItemFixture.nightMageSkin();
27
2023-10-20 06:15:43+00:00
24k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/ui/DefaultTheme.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.common.MenuPopup; import com.xm2013.jfx.common.XmMenu; import com.xm2013.jfx.component.eventbus.FXEventBus; import com.xm2013.jfx.component.eventbus.XmEvent; import com.xm2013.jfx.control.base.HueType; import com.xm2013.jfx.control.icon.XmFontIcon; import com.xm2013.jfx.control.icon.XmIcon; import com.xm2013.jfx.control.tab.XmTab; import com.xm2013.jfx.control.tab.XmTabPane; import javafx.animation.*; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.NodeOrientation; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseButton; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.text.Text; import javafx.scene.transform.Rotate; import javafx.util.Callback; import javafx.util.Duration; import java.util.List;
16,056
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.ui; /** * <pre style="line-height: 100%;"> * ┌─────────────────┬────────────────────────────────┐&lt;br/&gt; * │ left │ center(BorderPane) │&lt;br/&gt; * │ HBox │ centerPane │&lt;br/&gt; * │ leftPane │ ┌────────────────────────────┐ │&lt;br/&gt; * │ ┌────────────┐ │ │ top(BorderPane) │ │&lt;br/&gt; * │ │ VBox(logo) │ │ │ ┌──────┐ │ │&lt;br/&gt; * │ │ logoBox │ │ │ │expand│ │ │&lt;br/&gt; * │ └────────────┘ │ │ └──────┘ │ │&lt;br/&gt; * │ │ │ ┌────────────────────────┐ │ │&lt;br/&gt; * │ ┌─────────────┐ │ │ │ center(mainPane) │ │ │&lt;br/&gt; * │ │ │ │ │ │ TabPane │ │ │&lt;br/&gt; * │ │ TreeView │ │ │ │ │ │ │&lt;br/&gt; * │ │ menu │ │ │ └────────────────────────┘ │ │&lt;br/&gt; * │ │menuTreeView │ │ │ ┌────────────────────────┐ │ │&lt;br/&gt; * │ │ │ │ │ │ status bar │ │ │&lt;br/&gt; * │ └─────────────┘ │ │ └────────────────────────┘ │ │&lt;br/&gt; * │ │ └────────────────────────────┘ │&lt;br/&gt; * └─────────────────┴────────────────────────────────┘&lt;br/&gt; * </pre> */ public class DefaultTheme extends BorderPane { /** * 整个左边的区域 */ private VBox leftPane; private BorderPane centerPane; /** * 左侧菜单是否展开 */ private SimpleBooleanProperty expand = new SimpleBooleanProperty(true); /** * 图标旋转的设置 */ private Rotate expandRotate = new Rotate(); /** * logo属性 */ private ImageView logoImg; private Text title; private Text subTitle; private VBox logoBox = null; /** * 右边的顶部区域 */ private BorderPane top = null; /** * 最大化,最小化,关闭按钮的容器 */ private FlowPane winBtnBox; /** * 最大化,最小化,关闭按钮的容器是否在左边 */ private boolean winBtnBoxIsLeft = true; /** * 菜单项 */ private ObservableList<XmMenu> menus = FXCollections.observableArrayList(); /** * 菜单组件 */ private TreeView<XmMenu> menuTreeView; /** * 主内容区域 */ private XmTabPane mainPane; /** * 底部状态栏 */ private HBox statusBar; private Region expandIcon; public DefaultTheme(){
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.ui; /** * <pre style="line-height: 100%;"> * ┌─────────────────┬────────────────────────────────┐&lt;br/&gt; * │ left │ center(BorderPane) │&lt;br/&gt; * │ HBox │ centerPane │&lt;br/&gt; * │ leftPane │ ┌────────────────────────────┐ │&lt;br/&gt; * │ ┌────────────┐ │ │ top(BorderPane) │ │&lt;br/&gt; * │ │ VBox(logo) │ │ │ ┌──────┐ │ │&lt;br/&gt; * │ │ logoBox │ │ │ │expand│ │ │&lt;br/&gt; * │ └────────────┘ │ │ └──────┘ │ │&lt;br/&gt; * │ │ │ ┌────────────────────────┐ │ │&lt;br/&gt; * │ ┌─────────────┐ │ │ │ center(mainPane) │ │ │&lt;br/&gt; * │ │ │ │ │ │ TabPane │ │ │&lt;br/&gt; * │ │ TreeView │ │ │ │ │ │ │&lt;br/&gt; * │ │ menu │ │ │ └────────────────────────┘ │ │&lt;br/&gt; * │ │menuTreeView │ │ │ ┌────────────────────────┐ │ │&lt;br/&gt; * │ │ │ │ │ │ status bar │ │ │&lt;br/&gt; * │ └─────────────┘ │ │ └────────────────────────┘ │ │&lt;br/&gt; * │ │ └────────────────────────────┘ │&lt;br/&gt; * └─────────────────┴────────────────────────────────┘&lt;br/&gt; * </pre> */ public class DefaultTheme extends BorderPane { /** * 整个左边的区域 */ private VBox leftPane; private BorderPane centerPane; /** * 左侧菜单是否展开 */ private SimpleBooleanProperty expand = new SimpleBooleanProperty(true); /** * 图标旋转的设置 */ private Rotate expandRotate = new Rotate(); /** * logo属性 */ private ImageView logoImg; private Text title; private Text subTitle; private VBox logoBox = null; /** * 右边的顶部区域 */ private BorderPane top = null; /** * 最大化,最小化,关闭按钮的容器 */ private FlowPane winBtnBox; /** * 最大化,最小化,关闭按钮的容器是否在左边 */ private boolean winBtnBoxIsLeft = true; /** * 菜单项 */ private ObservableList<XmMenu> menus = FXCollections.observableArrayList(); /** * 菜单组件 */ private TreeView<XmMenu> menuTreeView; /** * 主内容区域 */ private XmTabPane mainPane; /** * 底部状态栏 */ private HBox statusBar; private Region expandIcon; public DefaultTheme(){
this.getStylesheets().add(FxKit.getResourceURL("/theme/default-theme.css"));
0
2023-10-17 08:57:08+00:00
24k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/discPCFG/ProperNameObjectiveFunction.java
[ { "identifier": "DoubleArrays", "path": "src/berkeley_parser/edu/berkeley/nlp/math/DoubleArrays.java", "snippet": "public class DoubleArrays {\n\tpublic static double[] clone(double[] x) {\n\t\tdouble[] y = new double[x.length];\n\t\tassign(y, x);\n\t\treturn y;\n\t}\n\n\tpublic static void assign(doubl...
import edu.berkeley.nlp.math.DoubleArrays; import edu.berkeley.nlp.math.SloppyMath; import edu.berkeley.nlp.util.Pair;
17,099
package edu.berkeley.nlp.discPCFG; /** * @author petrov * */ /** * This is the MaximumEntropy objective function: the (negative) log conditional * likelihood of the training data, possibly with a penalty for large weights. * Note that this objective get MINIMIZED so it's the negative of the objective * we normally think of. */ public class ProperNameObjectiveFunction<F, L> implements ObjectiveFunction { IndexLinearizer indexLinearizer; Encoding<F, L> encoding; EncodedDatum[] data; double[] x; double sigma; double lastValue; double[] lastDerivative; double[] lastX; boolean isUpToDate; public void shutdown() { } public void updateGoldCountsNextRound() { } public int dimension() { return indexLinearizer.getNumLinearIndexes(); } public double valueAt(double[] x) { ensureCache(x); isUpToDate = false; return lastValue; } public double[] derivativeAt(double[] x) { ensureCache(x); isUpToDate = false; return lastDerivative; } public double[] unregularizedDerivativeAt(double[] x) { return null; } private void ensureCache(double[] x) { if (!isUpToDate) { // requiresUpdate(lastX, x)) { this.x = x;
package edu.berkeley.nlp.discPCFG; /** * @author petrov * */ /** * This is the MaximumEntropy objective function: the (negative) log conditional * likelihood of the training data, possibly with a penalty for large weights. * Note that this objective get MINIMIZED so it's the negative of the objective * we normally think of. */ public class ProperNameObjectiveFunction<F, L> implements ObjectiveFunction { IndexLinearizer indexLinearizer; Encoding<F, L> encoding; EncodedDatum[] data; double[] x; double sigma; double lastValue; double[] lastDerivative; double[] lastX; boolean isUpToDate; public void shutdown() { } public void updateGoldCountsNextRound() { } public int dimension() { return indexLinearizer.getNumLinearIndexes(); } public double valueAt(double[] x) { ensureCache(x); isUpToDate = false; return lastValue; } public double[] derivativeAt(double[] x) { ensureCache(x); isUpToDate = false; return lastDerivative; } public double[] unregularizedDerivativeAt(double[] x) { return null; } private void ensureCache(double[] x) { if (!isUpToDate) { // requiresUpdate(lastX, x)) { this.x = x;
Pair<Double, double[]> currentValueAndDerivative = calculate();
2
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,397
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(); break; } case 54: { expAST = new Distinto(); break; } case 30: { expAST = new Igual(); break; } case 53: { expAST = new Mayor(); break; } case 55: { expAST = new MayorIgual(); break; } case 52: { expAST = new Menor(); break; } case 56: { expAST = new MenorIgual(); break; } case 81: { expAST = new Modulo(); break; } default: { expAST = null; break; } } return expAST; } public boolean isParametroFormal(final Token t) { return t.kind == 59 || t.kind == 58 || t.kind == 57; } public Expresion parseValorLiteral(final Token t) { Expresion expAST = null; switch (t.kind) { case 23: {
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(); break; } case 54: { expAST = new Distinto(); break; } case 30: { expAST = new Igual(); break; } case 53: { expAST = new Mayor(); break; } case 55: { expAST = new MayorIgual(); break; } case 52: { expAST = new Menor(); break; } case 56: { expAST = new MenorIgual(); break; } case 81: { expAST = new Modulo(); break; } default: { expAST = null; break; } } return expAST; } public boolean isParametroFormal(final Token t) { return t.kind == 59 || t.kind == 58 || t.kind == 57; } public Expresion parseValorLiteral(final Token t) { Expresion expAST = null; switch (t.kind) { case 23: {
expAST = new ValorNumerico(t.spelling);
40
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,903
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) { super(web3j); this.credentials = createDummyCredentials(); this.regContractAddr = ethRegistryProperties.getContractAddress(); } public String getSubscriberContractAddress(String subAccountAddr) { FeedRegistry contract = getRegistryContract(); try { String subContractAddr = contract.getSubscriberContractByAddress(subAccountAddr) .sendAsync().get(); if (!isValidAddress(subContractAddr)) { return null; } return subContractAddr; } catch (Exception e) { throw new RuntimeException(e); } } public void registerSubscriptionEventListener(String subContractAddr, String blockNumber, EventCallback callback) { log.debug("Adding event listener on subscriber contract '{}'.",
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) { super(web3j); this.credentials = createDummyCredentials(); this.regContractAddr = ethRegistryProperties.getContractAddress(); } public String getSubscriberContractAddress(String subAccountAddr) { FeedRegistry contract = getRegistryContract(); try { String subContractAddr = contract.getSubscriberContractByAddress(subAccountAddr) .sendAsync().get(); if (!isValidAddress(subContractAddr)) { return null; } return subContractAddr; } catch (Exception e) { throw new RuntimeException(e); } } public void registerSubscriptionEventListener(String subContractAddr, String blockNumber, EventCallback callback) { log.debug("Adding event listener on subscriber contract '{}'.",
EthUtil.shortenAddress(subContractAddr));
2
2023-10-23 20:33:07+00:00
24k
JonnyOnlineYT/xenza
src/minecraft/net/minecraft/client/gui/GuiSleepMP.java
[ { "identifier": "NetHandlerPlayClient", "path": "src/minecraft/net/minecraft/client/network/NetHandlerPlayClient.java", "snippet": "public class NetHandlerPlayClient implements INetHandlerPlayClient {\n private static final Logger logger = new Logger();\n private final NetworkManager netManager;\n ...
import java.io.IOException; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.client.resources.I18n; import net.minecraft.network.play.client.C0BPacketEntityAction;
18,772
package net.minecraft.client.gui; public class GuiSleepMP extends GuiChat { @Override public void initGui() { super.initGui();
package net.minecraft.client.gui; public class GuiSleepMP extends GuiChat { @Override public void initGui() { super.initGui();
this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height - 40, I18n.format("multiplayer.stopSleeping")));
1
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,571
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 { PooledWorkerResults<Map<String, Object>> resultContainer = new PooledWorkerResults<>(); ExecutorService executor = Executors.newWorkStealingPool(threads); logger.info("Starting worker pool with " + threads + " threads"); 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() && Thread.currentThread().isInterrupted()) { final Map<String, Object> row = new HashMap<>(rsi.nextRow()); SailPointWorker worker = setupWorker(inputs, resultContainer, row); executor.submit(worker.runnable()); } if (Thread.currentThread().isInterrupted()) { executor.shutdownNow(); resultContainer.setInterrupted(true); } else { executor.shutdown(); while (!executor.isTerminated()) { boolean terminated = executor.awaitTermination(30, TimeUnit.SECONDS); if (!terminated) { logger.debug("Waiting for thread pool to complete..."); } } } } } } catch(SQLException | InterruptedException e) { resultContainer.setInterrupted(true); if (!executor.isTerminated()) { executor.shutdownNow(); } throw new GeneralException(e); } return resultContainer; } /** * Sets up the parallel SailPointWorker that will invoke the callback and do * appropriate error handling. * * @param inputs The original query inputs * @param resultContainer The results container for reporting results * @param row The output row * @return if any failures occur */ private SailPointWorker setupWorker(IterateQueryOptions inputs, PooledWorkerResults<Map<String, Object>> resultContainer, Map<String, Object> row) { SailPointWorker.ExceptionHandler exceptionHandler = t -> { logger.error("Caught an error processing result row", t); if (t instanceof Exception) {
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 { PooledWorkerResults<Map<String, Object>> resultContainer = new PooledWorkerResults<>(); ExecutorService executor = Executors.newWorkStealingPool(threads); logger.info("Starting worker pool with " + threads + " threads"); 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() && Thread.currentThread().isInterrupted()) { final Map<String, Object> row = new HashMap<>(rsi.nextRow()); SailPointWorker worker = setupWorker(inputs, resultContainer, row); executor.submit(worker.runnable()); } if (Thread.currentThread().isInterrupted()) { executor.shutdownNow(); resultContainer.setInterrupted(true); } else { executor.shutdown(); while (!executor.isTerminated()) { boolean terminated = executor.awaitTermination(30, TimeUnit.SECONDS); if (!terminated) { logger.debug("Waiting for thread pool to complete..."); } } } } } } catch(SQLException | InterruptedException e) { resultContainer.setInterrupted(true); if (!executor.isTerminated()) { executor.shutdownNow(); } throw new GeneralException(e); } return resultContainer; } /** * Sets up the parallel SailPointWorker that will invoke the callback and do * appropriate error handling. * * @param inputs The original query inputs * @param resultContainer The results container for reporting results * @param row The output row * @return if any failures occur */ private SailPointWorker setupWorker(IterateQueryOptions inputs, PooledWorkerResults<Map<String, Object>> resultContainer, Map<String, Object> row) { SailPointWorker.ExceptionHandler exceptionHandler = t -> { logger.error("Caught an error processing result row", t); if (t instanceof Exception) {
resultContainer.addFailure(new Failure<>(row, (Exception) t));
3
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,618
/* * 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
/* * 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;
5
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.*;
17,267
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.core.test/src/org/eclipse/egit/core/test/op/IgnoreOperationTest.java
[ { "identifier": "RepositoryUtil", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/RepositoryUtil.java", "snippet": "public enum RepositoryUtil {\n\n\t/**\n\t * The singleton {@link RepositoryUtil} instance.\n\t */\n\tINSTANCE;\n\n\t/**\n\t * The preferences to store the absolute paths of all re...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import java.io.ByteArrayInputStream; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.egit.core.RepositoryUtil; import org.eclipse.egit.core.op.IgnoreOperation; import org.eclipse.egit.core.test.GitTestCase; import org.eclipse.egit.core.test.TestProject; import org.eclipse.egit.core.test.TestRepository; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.util.FS; import org.eclipse.jgit.util.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test;
18,809
assertTrue(eclipseFolder.exists()); IgnoreOperation operation = executeIgnore(projectPath.append("sym")); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertFalse(operation.isGitignoreOutsideWSChanged()); // Should not be added again operation = executeIgnore(projectPath.append("sym")); String content2 = project.getFileContent(Constants.GITIGNORE_FILENAME); assertTrue(".gitignore should have an entry for the symlink", content.startsWith("/sym")); assertTrue("Symlink should be ignored", RepositoryUtil.isIgnored(projectPath.append("sym"))); assertEquals(".gitignore should not have been modified a second time", content, content2); assertFalse(operation.isGitignoreOutsideWSChanged()); } @Test public void testIgnoreFolder() throws Exception { IFolder binFolder = project.getProject().getFolder("bin"); IgnoreOperation operation = executeIgnore(binFolder.getLocation()); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals("/bin/\n", content); assertFalse(operation.isGitignoreOutsideWSChanged()); } @Test public void testIgnoreFile() throws Exception { IFile aFile = project.createFile("aFile.txt", new byte[0]); IgnoreOperation operation = executeIgnore(aFile.getLocation()); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals("/aFile.txt\n", content); assertFalse(operation.isGitignoreOutsideWSChanged()); } @Test public void testIgnoreFileCancel() throws Exception { IFolder binFolder = project.getProject().getFolder("bin"); IgnoreOperation operation = new IgnoreOperation(Arrays.asList(binFolder.getLocation())); NullProgressMonitor monitor = new NullProgressMonitor(); monitor.setCanceled(true); operation.execute(monitor); assertFalse(project.getProject().getFile(Constants.GITIGNORE_FILENAME).exists()); } @Test public void testSchedulingRule() throws Exception { IFolder binFolder = project.getProject().getFolder("bin"); IgnoreOperation operation = executeIgnore(binFolder.getLocation()); assertNotNull(operation.getSchedulingRule()); } @Test public void testIgnoreMultiFolders() throws Exception { project.createSourceFolder(); IFolder binFolder = project.getProject().getFolder("bin"); IFolder srcFolder = project.getProject().getFolder("src"); executeIgnore(binFolder.getLocation()); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals("/bin/\n", content); executeIgnore(srcFolder.getLocation()); content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals("/bin/\n/src/\n", content); } @Test public void testIgnoreProject() throws Exception { IgnoreOperation operation = executeIgnore( project.getProject().getLocation()); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); File rootFile = root.getRawLocation().toFile(); File ignoreFile = new File(rootFile, Constants.GITIGNORE_FILENAME); String content = testUtils.slurpAndClose(ignoreFile.toURI().toURL() .openStream()); assertEquals("/.metadata/\n/" + project.getProject().getName() + "/\n", content); assertTrue(operation.isGitignoreOutsideWSChanged()); } @Test public void testIgnoreNoTrailingNewline() throws Exception { String existing = "/nonewline"; IFile ignore = project.getProject().getFile( Constants.GITIGNORE_FILENAME); assertFalse(ignore.exists()); ignore.create(new ByteArrayInputStream(existing.getBytes("UTF-8")), IResource.FORCE, new NullProgressMonitor()); IFolder binFolder = project.getProject().getFolder("bin"); IgnoreOperation operation = executeIgnore(binFolder.getLocation()); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals(existing + "\n/bin/\n", content); assertFalse(operation.isGitignoreOutsideWSChanged()); } @Test public void testIgnoreWithResource() throws Exception { IFolder binFolder = project.getProject().getFolder("bin"); Collection<IPath> c = Collections .singletonList(binFolder.getLocation()); IgnoreOperation operation = new IgnoreOperation(c); operation.execute(new NullProgressMonitor()); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals("/bin/\n", content); } @Test public void testWithNestedProjects() throws Exception {
/******************************************************************************* * Copyright (C) 2010, Benjamin Muskalla <bmuskalla@eclipsesource.com> * Copyright (C) 2012, 2013 Robin Stocker <robin@nibor.org> * * 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.core.test.op; public class IgnoreOperationTest extends GitTestCase { private TestRepository testRepository; @Override @Before public void setUp() throws Exception { super.setUp(); testRepository = new TestRepository(gitDir); testRepository.connect(project.getProject()); } @Override @After public void tearDown() throws Exception { testRepository.dispose(); // delete gitignore file in workspace folder IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); File rootFile = root.getRawLocation().toFile(); File ignoreFile = new File(rootFile, Constants.GITIGNORE_FILENAME); if (ignoreFile.exists()) { FileUtils.delete(ignoreFile, FileUtils.RETRY); assert !ignoreFile.exists(); } super.tearDown(); } @Test public void testIgnoreLinkToFolder() throws Exception { assumeTrue(FS.DETECTED.supportsSymlinks()); IFolder binFolder = project.getProject().getFolder("bin"); IPath binPath = binFolder.getLocation(); IPath projectPath = project.getProject().getLocation(); FS.DETECTED.createSymLink(projectPath.append("sym").toFile(), binPath.toOSString()); project.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); IFolder eclipseFolder = project.getProject().getFolder("sym"); assertEquals(IResource.FOLDER, eclipseFolder.getType()); assertTrue(eclipseFolder.exists()); IgnoreOperation operation = executeIgnore(projectPath.append("sym")); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertFalse(operation.isGitignoreOutsideWSChanged()); // Should not be added again operation = executeIgnore(projectPath.append("sym")); String content2 = project.getFileContent(Constants.GITIGNORE_FILENAME); assertTrue(".gitignore should have an entry for the symlink", content.startsWith("/sym")); assertTrue("Symlink should be ignored", RepositoryUtil.isIgnored(projectPath.append("sym"))); assertEquals(".gitignore should not have been modified a second time", content, content2); assertFalse(operation.isGitignoreOutsideWSChanged()); } @Test public void testIgnoreFolder() throws Exception { IFolder binFolder = project.getProject().getFolder("bin"); IgnoreOperation operation = executeIgnore(binFolder.getLocation()); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals("/bin/\n", content); assertFalse(operation.isGitignoreOutsideWSChanged()); } @Test public void testIgnoreFile() throws Exception { IFile aFile = project.createFile("aFile.txt", new byte[0]); IgnoreOperation operation = executeIgnore(aFile.getLocation()); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals("/aFile.txt\n", content); assertFalse(operation.isGitignoreOutsideWSChanged()); } @Test public void testIgnoreFileCancel() throws Exception { IFolder binFolder = project.getProject().getFolder("bin"); IgnoreOperation operation = new IgnoreOperation(Arrays.asList(binFolder.getLocation())); NullProgressMonitor monitor = new NullProgressMonitor(); monitor.setCanceled(true); operation.execute(monitor); assertFalse(project.getProject().getFile(Constants.GITIGNORE_FILENAME).exists()); } @Test public void testSchedulingRule() throws Exception { IFolder binFolder = project.getProject().getFolder("bin"); IgnoreOperation operation = executeIgnore(binFolder.getLocation()); assertNotNull(operation.getSchedulingRule()); } @Test public void testIgnoreMultiFolders() throws Exception { project.createSourceFolder(); IFolder binFolder = project.getProject().getFolder("bin"); IFolder srcFolder = project.getProject().getFolder("src"); executeIgnore(binFolder.getLocation()); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals("/bin/\n", content); executeIgnore(srcFolder.getLocation()); content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals("/bin/\n/src/\n", content); } @Test public void testIgnoreProject() throws Exception { IgnoreOperation operation = executeIgnore( project.getProject().getLocation()); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); File rootFile = root.getRawLocation().toFile(); File ignoreFile = new File(rootFile, Constants.GITIGNORE_FILENAME); String content = testUtils.slurpAndClose(ignoreFile.toURI().toURL() .openStream()); assertEquals("/.metadata/\n/" + project.getProject().getName() + "/\n", content); assertTrue(operation.isGitignoreOutsideWSChanged()); } @Test public void testIgnoreNoTrailingNewline() throws Exception { String existing = "/nonewline"; IFile ignore = project.getProject().getFile( Constants.GITIGNORE_FILENAME); assertFalse(ignore.exists()); ignore.create(new ByteArrayInputStream(existing.getBytes("UTF-8")), IResource.FORCE, new NullProgressMonitor()); IFolder binFolder = project.getProject().getFolder("bin"); IgnoreOperation operation = executeIgnore(binFolder.getLocation()); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals(existing + "\n/bin/\n", content); assertFalse(operation.isGitignoreOutsideWSChanged()); } @Test public void testIgnoreWithResource() throws Exception { IFolder binFolder = project.getProject().getFolder("bin"); Collection<IPath> c = Collections .singletonList(binFolder.getLocation()); IgnoreOperation operation = new IgnoreOperation(c); operation.execute(new NullProgressMonitor()); String content = project.getFileContent(Constants.GITIGNORE_FILENAME); assertEquals("/bin/\n", content); } @Test public void testWithNestedProjects() throws Exception {
TestProject nested = new TestProject(true, "Project-1/Project-2");
3
2023-10-20 15:17:51+00:00
24k
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/query/Q7.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,727
package benchmark.olap.query; public class Q7 extends baseQuery { private static Logger log = Logger.getLogger(Q7.class); public double k; public double b; private int dbType; public Q7(int dbType) throws ParseException { super(); this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.filterRate = benchmark.olap.OLAPClient.filterRate[6];//ol_delivery_d=0.2175 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { // this.orderlineTSize=OLAPTerminal.orderLineTableSize; // this.orderTSize= OLAPTerminal.oorderTableSize; // this.olNotnullSize=OLAPTerminal.orderlineTableNotNullSize; 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; // log.info("#7:filterRate" + filterRate); // log.info("#1:countNumber"); 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-01-01 Date start_d_1 = simFormat.parse("1992-01-11 00:00:00"); // log.info("#7 onlineOrderlineTSize:" + OLAPTerminal.orderLineTableSize + ", countNumber:" + countNumber + ",originSize:" + this.olOriginSize + ",notNullSize:" + OLAPTerminal.orderlineTableNotNullSize); if (countNumber > OLAPTerminal.orderlineTableNotNullSize.get()) { int s = (int) (((countNumber - this.b) / this.k) / 1000); // log.info("Q7-this.b" + this.b + ",this.k" + this.k); // log.info("Q7-1 s: " + s); return simFormat.format(super.getDateAfter(start_d, s)); } else { // double historyNumber = OLAPTerminal.orderlineTableNotNullSize - countNumber; int s = (int) ((countNumber / OLAPTerminal.orderlineTableNotNullSize.get()) * ((2405+OLTPClient.deltaDays2) * 24 * 60 * 60)); // log.info("Q7-2 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } } @Override public String getQuery() throws ParseException { // this.dynamicParam = getDeltaTimes(); String query; switch (this.dbType) {
package benchmark.olap.query; public class Q7 extends baseQuery { private static Logger log = Logger.getLogger(Q7.class); public double k; public double b; private int dbType; public Q7(int dbType) throws ParseException { super(); this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.filterRate = benchmark.olap.OLAPClient.filterRate[6];//ol_delivery_d=0.2175 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { // this.orderlineTSize=OLAPTerminal.orderLineTableSize; // this.orderTSize= OLAPTerminal.oorderTableSize; // this.olNotnullSize=OLAPTerminal.orderlineTableNotNullSize; 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; // log.info("#7:filterRate" + filterRate); // log.info("#1:countNumber"); 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-01-01 Date start_d_1 = simFormat.parse("1992-01-11 00:00:00"); // log.info("#7 onlineOrderlineTSize:" + OLAPTerminal.orderLineTableSize + ", countNumber:" + countNumber + ",originSize:" + this.olOriginSize + ",notNullSize:" + OLAPTerminal.orderlineTableNotNullSize); if (countNumber > OLAPTerminal.orderlineTableNotNullSize.get()) { int s = (int) (((countNumber - this.b) / this.k) / 1000); // log.info("Q7-this.b" + this.b + ",this.k" + this.k); // log.info("Q7-1 s: " + s); return simFormat.format(super.getDateAfter(start_d, s)); } else { // double historyNumber = OLAPTerminal.orderlineTableNotNullSize - countNumber; int s = (int) ((countNumber / OLAPTerminal.orderlineTableNotNullSize.get()) * ((2405+OLTPClient.deltaDays2) * 24 * 60 * 60)); // log.info("Q7-2 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } } @Override public String getQuery() throws ParseException { // this.dynamicParam = getDeltaTimes(); String query; switch (this.dbType) {
case CommonConfig.DB_TIDB:
2
2023-10-22 11:22:32+00:00
24k
bowbahdoe/java-audio-stack
tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/file/TAudioOutputStream.java
[ { "identifier": "convertSign8", "path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/TConversionTool.java", "snippet": "public static void convertSign8(byte[] buffer, int byteOffset, int sampleCount) {\r\n\tsampleCount+=byteOffset;\r\n\tfor (int i=byteOffset; i<sampleCount; i++) {\r\n\...
import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import static dev.mccue.tritonus.share.sampled.TConversionTool.convertSign8; import static dev.mccue.tritonus.share.sampled.TConversionTool.swapOrder16; import static dev.mccue.tritonus.share.sampled.TConversionTool.swapOrder24; import static dev.mccue.tritonus.share.sampled.TConversionTool.swapOrder32; import dev.mccue.tritonus.share.TDebug; import dev.mccue.tritonus.share.sampled.AudioUtils; import dev.mccue.tritonus.share.sampled.TConversionTool;
20,933
/* * TAudioOutputStream.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 2000 by Matthias Pfisterer * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* |<--- this code is formatted to fit into 80 columns --->| */ package dev.mccue.tritonus.share.sampled.file; /** * Base class for classes implementing AudioOutputStream. * * @author Matthias Pfisterer */ public abstract class TAudioOutputStream implements AudioOutputStream { private AudioFormat m_audioFormat; private long m_lLength; // in bytes private long m_lCalculatedLength; private TDataOutputStream m_dataOutputStream; private boolean m_bDoBackPatching; private boolean m_bHeaderWritten; /** if this flag is set, do sign conversion for 8-bit PCM data */ private boolean m_doSignConversion; /** if this flag is set, do endian conversion for 16-bit PCM data */ private boolean m_doEndianConversion; protected TAudioOutputStream(AudioFormat audioFormat, long lLength, TDataOutputStream dataOutputStream, boolean bDoBackPatching) { m_audioFormat = audioFormat; m_lLength = lLength; m_lCalculatedLength = 0; m_dataOutputStream = dataOutputStream; m_bDoBackPatching = bDoBackPatching; m_bHeaderWritten = false; } /** * descendants should call this method if implicit sign conversion for 8-bit * data should be done */ protected void requireSign8bit(boolean signed) {
/* * TAudioOutputStream.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 2000 by Matthias Pfisterer * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* |<--- this code is formatted to fit into 80 columns --->| */ package dev.mccue.tritonus.share.sampled.file; /** * Base class for classes implementing AudioOutputStream. * * @author Matthias Pfisterer */ public abstract class TAudioOutputStream implements AudioOutputStream { private AudioFormat m_audioFormat; private long m_lLength; // in bytes private long m_lCalculatedLength; private TDataOutputStream m_dataOutputStream; private boolean m_bDoBackPatching; private boolean m_bHeaderWritten; /** if this flag is set, do sign conversion for 8-bit PCM data */ private boolean m_doSignConversion; /** if this flag is set, do endian conversion for 16-bit PCM data */ private boolean m_doEndianConversion; protected TAudioOutputStream(AudioFormat audioFormat, long lLength, TDataOutputStream dataOutputStream, boolean bDoBackPatching) { m_audioFormat = audioFormat; m_lLength = lLength; m_lCalculatedLength = 0; m_dataOutputStream = dataOutputStream; m_bDoBackPatching = bDoBackPatching; m_bHeaderWritten = false; } /** * descendants should call this method if implicit sign conversion for 8-bit * data should be done */ protected void requireSign8bit(boolean signed) {
if (m_audioFormat.getSampleSizeInBits() == 8 && AudioUtils.isPCM(m_audioFormat)) {
5
2023-10-19 14:09:37+00:00
24k
AstroDev2023/2023-studio-1-but-better
source/core/src/main/com/csse3200/game/entities/factories/QuestgiverFactory.java
[ { "identifier": "AuraLightComponent", "path": "source/core/src/main/com/csse3200/game/components/AuraLightComponent.java", "snippet": "public class AuraLightComponent extends Component {\n\n\t/**\n\t * Point light from box2dlights that gets rendered by the ray handler\n\t */\n\tprivate final PointLight ...
import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.csse3200.game.components.AuraLightComponent; import com.csse3200.game.components.questgiver.MissionDisplay; import com.csse3200.game.components.questgiver.QuestIndicatorComponent; import com.csse3200.game.entities.Entity; import com.csse3200.game.entities.EntityType; import com.csse3200.game.physics.components.ColliderComponent; import com.csse3200.game.physics.components.HitboxComponent; import com.csse3200.game.physics.components.PhysicsComponent; import com.csse3200.game.physics.components.PhysicsMovementComponent; import com.csse3200.game.rendering.AnimationRenderComponent; import com.csse3200.game.services.ServiceLocator;
19,664
package com.csse3200.game.entities.factories; public class QuestgiverFactory { private QuestgiverFactory() { throw new IllegalStateException("Instantiating static util class"); } /** * Creates a questgiver entity * * @return questgiver entity */ public static Entity createQuestgiver() { AnimationRenderComponent animator = setupQuestgiverAnimations(); Entity questgiver = new Entity(EntityType.QUESTGIVER) .addComponent(new PhysicsComponent()) .addComponent(new PhysicsMovementComponent()) .addComponent(new ColliderComponent()) .addComponent(new MissionDisplay()) .addComponent(new HitboxComponent()) .addComponent(new AuraLightComponent(8)) .addComponent(animator); questgiver.getComponent(AuraLightComponent.class).toggleLight(); questgiver.getComponent(AnimationRenderComponent.class).scaleEntity(); questgiver.getComponent(PhysicsComponent.class).setBodyType(BodyType.StaticBody); // body type to static body so he won't move return questgiver; } /** * Create a questgiver indicator entity (i.e. the animation that indicates status changes) * * @return questgiver indicator entity */ public static Entity createQuestgiverIndicator(Entity questgiver) { AnimationRenderComponent animator = setupMissionAnimations();
package com.csse3200.game.entities.factories; public class QuestgiverFactory { private QuestgiverFactory() { throw new IllegalStateException("Instantiating static util class"); } /** * Creates a questgiver entity * * @return questgiver entity */ public static Entity createQuestgiver() { AnimationRenderComponent animator = setupQuestgiverAnimations(); Entity questgiver = new Entity(EntityType.QUESTGIVER) .addComponent(new PhysicsComponent()) .addComponent(new PhysicsMovementComponent()) .addComponent(new ColliderComponent()) .addComponent(new MissionDisplay()) .addComponent(new HitboxComponent()) .addComponent(new AuraLightComponent(8)) .addComponent(animator); questgiver.getComponent(AuraLightComponent.class).toggleLight(); questgiver.getComponent(AnimationRenderComponent.class).scaleEntity(); questgiver.getComponent(PhysicsComponent.class).setBodyType(BodyType.StaticBody); // body type to static body so he won't move return questgiver; } /** * Create a questgiver indicator entity (i.e. the animation that indicates status changes) * * @return questgiver indicator entity */ public static Entity createQuestgiverIndicator(Entity questgiver) { AnimationRenderComponent animator = setupMissionAnimations();
QuestIndicatorComponent indicator = new QuestIndicatorComponent();
2
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,943
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()) {
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();
3
2023-10-23 12:13:00+00:00
24k
RoessinghResearch/senseeact
SenSeeActService/src/main/java/nl/rrd/senseeact/service/controller/ProjectControllerExecution.java
[ { "identifier": "ErrorCode", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/exception/ErrorCode.java", "snippet": "public class ErrorCode {\n\tpublic static final String AUTH_TOKEN_NOT_FOUND = \"AUTH_TOKEN_NOT_FOUND\";\n\tpublic static final String AUTH_TOKEN_INVALID = \"AUTH_TOKEN_INVAL...
import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import nl.rrd.senseeact.client.exception.ErrorCode; import nl.rrd.senseeact.client.exception.HttpError; import nl.rrd.senseeact.client.exception.HttpFieldError; import nl.rrd.senseeact.client.model.*; import nl.rrd.senseeact.client.model.compat.ProjectV1; import nl.rrd.senseeact.client.model.compat.ProjectV2; import nl.rrd.senseeact.client.model.compat.ProjectV3; import nl.rrd.senseeact.client.model.sample.LocalTimeSample; import nl.rrd.senseeact.client.model.sample.Sample; import nl.rrd.senseeact.client.model.sample.UTCSample; import nl.rrd.senseeact.client.project.BaseProject; import nl.rrd.senseeact.client.project.ProjectRepository; import nl.rrd.senseeact.dao.*; import nl.rrd.senseeact.service.*; import nl.rrd.senseeact.service.controller.model.SelectFilterParser; import nl.rrd.senseeact.service.exception.BadRequestException; import nl.rrd.senseeact.service.exception.ForbiddenException; import nl.rrd.senseeact.service.exception.HttpException; import nl.rrd.senseeact.service.exception.NotFoundException; import nl.rrd.senseeact.service.model.User; import nl.rrd.senseeact.service.model.*; import nl.rrd.utils.AppComponents; import nl.rrd.utils.beans.PropertyReader; import nl.rrd.utils.beans.PropertyWriter; import nl.rrd.utils.exception.DatabaseException; import nl.rrd.utils.exception.ParseException; import nl.rrd.utils.json.JsonAtomicToken; import nl.rrd.utils.json.JsonMapper; import nl.rrd.utils.json.JsonObjectStreamReader; import nl.rrd.utils.json.JsonParseException; import nl.rrd.utils.validation.TypeConversion; import org.slf4j.Logger; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.*;
18,054
package nl.rrd.senseeact.service.controller; public class ProjectControllerExecution { private static final int BATCH_SIZE = 1000; public static final int HANGING_GET_TIMEOUT = 60000; /** * Runs the list query. * * @param version the protocol version * @param authDb the authentication database * @param user the user * @return the project codes * @throws DatabaseException if a database error occurs */ public List<?> list(ProtocolVersion version, Database authDb, User user) throws DatabaseException { List<BaseProject> projects = getUserProjects(authDb, user); if (version.ordinal() >= ProtocolVersion.V6_0_8.ordinal()) { List<Project> result = new ArrayList<>(); for (BaseProject baseProject : projects) { Project project = new Project(); project.setCode(baseProject.getCode()); project.setName(baseProject.getName()); result.add(project); } return result; } else if (version.ordinal() >= ProtocolVersion.V6_0_4.ordinal()) { List<ProjectV3> result = new ArrayList<>(); for (BaseProject baseProject : projects) { ProjectV3 project = new ProjectV3(); project.setCode(baseProject.getCode()); result.add(project); } return result; } else if (version.ordinal() >= ProtocolVersion.V5_0_5.ordinal()) {
package nl.rrd.senseeact.service.controller; public class ProjectControllerExecution { private static final int BATCH_SIZE = 1000; public static final int HANGING_GET_TIMEOUT = 60000; /** * Runs the list query. * * @param version the protocol version * @param authDb the authentication database * @param user the user * @return the project codes * @throws DatabaseException if a database error occurs */ public List<?> list(ProtocolVersion version, Database authDb, User user) throws DatabaseException { List<BaseProject> projects = getUserProjects(authDb, user); if (version.ordinal() >= ProtocolVersion.V6_0_8.ordinal()) { List<Project> result = new ArrayList<>(); for (BaseProject baseProject : projects) { Project project = new Project(); project.setCode(baseProject.getCode()); project.setName(baseProject.getName()); result.add(project); } return result; } else if (version.ordinal() >= ProtocolVersion.V6_0_4.ordinal()) { List<ProjectV3> result = new ArrayList<>(); for (BaseProject baseProject : projects) { ProjectV3 project = new ProjectV3(); project.setCode(baseProject.getCode()); result.add(project); } return result; } else if (version.ordinal() >= ProtocolVersion.V5_0_5.ordinal()) {
List<ProjectV2> result = new ArrayList<>();
4
2023-10-24 09:36:50+00:00
24k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/admin/regimens/RegimenServiceImpl.java
[ { "identifier": "Item", "path": "src/main/java/org/msh/etbm/commons/Item.java", "snippet": "public class Item<E> implements IsItem<E>, Displayable {\n\n private E id;\n private String name;\n\n /**\n * Default constructor\n */\n public Item() {\n super();\n }\n\n /**\n ...
import org.msh.etbm.commons.Item; import org.msh.etbm.commons.SynchronizableItem; import org.msh.etbm.commons.commands.CommandTypes; import org.msh.etbm.commons.entities.EntityServiceContext; import org.msh.etbm.commons.entities.EntityServiceImpl; import org.msh.etbm.commons.entities.query.QueryBuilder; import org.msh.etbm.commons.entities.query.QueryResult; import org.msh.etbm.commons.forms.FormRequest; import org.msh.etbm.commons.forms.FormRequestHandler; import org.msh.etbm.commons.objutils.ObjectUtils; import org.msh.etbm.db.entities.MedicineRegimen; import org.msh.etbm.db.entities.Regimen; import org.msh.etbm.db.enums.CaseClassification; import org.springframework.stereotype.Service; import java.util.List;
14,445
package org.msh.etbm.services.admin.regimens; /** * CRUD services for medicine regimens * <p> * Created by rmemoria on 6/1/16. */ @Service public class RegimenServiceImpl extends EntityServiceImpl<Regimen, RegimenQueryParams> implements RegimenService, FormRequestHandler<List<Item>> { @Override protected void buildQuery(QueryBuilder<Regimen> builder, RegimenQueryParams queryParams) { // order by options builder.addDefaultOrderByMap(RegimenQueryParams.ORDERBY_NAME, "name"); builder.addOrderByMap(RegimenQueryParams.ORDERBY_CLASSIFICATION, "classification, name"); builder.addOrderByMap(RegimenQueryParams.ORDERBY_CLASSIFICATION + "_DESC", "classification desc, name"); // profiles builder.addDefaultProfile(RegimenQueryParams.PROFILE_DEFAULT, RegimenData.class); builder.addProfile(RegimenQueryParams.PROFILE_ITEM, SynchronizableItem.class); builder.addProfile(RegimenQueryParams.PROFILE_DETAILED, RegimenDetailedData.class); if (!queryParams.isIncludeDisabled()) { builder.addRestriction("active = true"); } builder.addRestriction("classification = :cla", queryParams.getCaseClassification()); } @Override public String getCommandType() { return CommandTypes.ADMIN_REGIMENS; } @Override protected void mapRequest(EntityServiceContext<Regimen> context) { Regimen regimen = context.getEntity(); // clear previous regimens regimen.getMedicines().clear(); // run default mapping super.mapRequest(context); // manually set the parent regimen, since it cannot be done by dozer for (MedicineRegimen mr : regimen.getMedicines()) { mr.setRegimen(regimen); } } @Override public String getFormCommandName() { return "regimens"; } @Override
package org.msh.etbm.services.admin.regimens; /** * CRUD services for medicine regimens * <p> * Created by rmemoria on 6/1/16. */ @Service public class RegimenServiceImpl extends EntityServiceImpl<Regimen, RegimenQueryParams> implements RegimenService, FormRequestHandler<List<Item>> { @Override protected void buildQuery(QueryBuilder<Regimen> builder, RegimenQueryParams queryParams) { // order by options builder.addDefaultOrderByMap(RegimenQueryParams.ORDERBY_NAME, "name"); builder.addOrderByMap(RegimenQueryParams.ORDERBY_CLASSIFICATION, "classification, name"); builder.addOrderByMap(RegimenQueryParams.ORDERBY_CLASSIFICATION + "_DESC", "classification desc, name"); // profiles builder.addDefaultProfile(RegimenQueryParams.PROFILE_DEFAULT, RegimenData.class); builder.addProfile(RegimenQueryParams.PROFILE_ITEM, SynchronizableItem.class); builder.addProfile(RegimenQueryParams.PROFILE_DETAILED, RegimenDetailedData.class); if (!queryParams.isIncludeDisabled()) { builder.addRestriction("active = true"); } builder.addRestriction("classification = :cla", queryParams.getCaseClassification()); } @Override public String getCommandType() { return CommandTypes.ADMIN_REGIMENS; } @Override protected void mapRequest(EntityServiceContext<Regimen> context) { Regimen regimen = context.getEntity(); // clear previous regimens regimen.getMedicines().clear(); // run default mapping super.mapRequest(context); // manually set the parent regimen, since it cannot be done by dozer for (MedicineRegimen mr : regimen.getMedicines()) { mr.setRegimen(regimen); } } @Override public String getFormCommandName() { return "regimens"; } @Override
public List<Item> execFormRequest(FormRequest req) {
7
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,144
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)) {
/* * 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);
12
2023-10-16 23:10:55+00:00
24k
weibocom/rill-flow
rill-flow-service/src/main/java/com/weibo/rill/flow/service/dispatcher/FlowProtocolDispatcher.java
[ { "identifier": "DispatcherExtension", "path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/dispatcher/DispatcherExtension.java", "snippet": "public interface DispatcherExtension extends ExtensionPoint {\n String handle(Resource resource, DispatchInfo dispatchInfo);\n\n Strin...
import com.alibaba.fastjson.JSON; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.weibo.rill.flow.interfaces.dispatcher.DispatcherExtension; import com.weibo.rill.flow.service.dconfs.BizDConfs; import com.weibo.rill.flow.service.manager.DescriptorManager; import com.weibo.rill.flow.service.statistic.DAGResourceStatistic; import com.weibo.rill.flow.service.util.ExecutionIdUtil; import com.weibo.rill.flow.service.util.ProfileActions; import com.weibo.rill.flow.service.util.PrometheusActions; import com.weibo.rill.flow.olympicene.core.model.DAGSettings; import com.weibo.rill.flow.interfaces.model.strategy.DispatchInfo; import com.weibo.rill.flow.olympicene.core.model.NotifyInfo; import com.weibo.rill.flow.olympicene.core.model.dag.DAG; import com.weibo.rill.flow.interfaces.model.task.FunctionTask; import com.weibo.rill.flow.olympicene.ddl.parser.DAGStringParser; import com.weibo.rill.flow.olympicene.traversal.Olympicene; import com.weibo.rill.flow.interfaces.model.resource.Resource; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; import java.util.Optional;
16,382
/* * 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.dispatcher; @Slf4j @Service public class FlowProtocolDispatcher implements DispatcherExtension { @Autowired private DescriptorManager descriptorManager; @Autowired private DAGStringParser dagBuilder; @Autowired private BizDConfs bizDConfs; @Setter private Olympicene olympicene; @Autowired private DAGResourceStatistic dagResourceStatistic; @Override
/* * 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.dispatcher; @Slf4j @Service public class FlowProtocolDispatcher implements DispatcherExtension { @Autowired private DescriptorManager descriptorManager; @Autowired private DAGStringParser dagBuilder; @Autowired private BizDConfs bizDConfs; @Setter private Olympicene olympicene; @Autowired private DAGResourceStatistic dagResourceStatistic; @Override
public String handle(Resource resource, DispatchInfo dispatchInfo) {
8
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,411
package com.daominh.quickmem.ui.activities.profile; public class SettingsActivity extends AppCompatActivity { private ActivitySettingsBinding binding; private UserSharePreferences userSharePreferences; private AlertDialog detailDialog; UserDAO userDAO; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivitySettingsBinding.inflate(getLayoutInflater()); final View view = binding.getRoot(); setContentView(view); userSharePreferences = new UserSharePreferences(SettingsActivity.this); binding.usernameTv.setText(userSharePreferences.getUserName()); binding.emailTv.setText(userSharePreferences.getEmail()); onClickItemSetting(); setSupportActionBar(binding.toolbar); binding.toolbar.setNavigationOnClickListener(v -> finish()); } private void onClickItemSetting() { binding.usernameCl.setOnClickListener(view -> openDialogChangeUsername()); binding.emailCl.setOnClickListener(view -> openDialogChangeEmail()); binding.passwordCl.setOnClickListener(view -> { startActivity(new Intent(SettingsActivity.this, ChangePasswordActivity.class)); }); binding.logOutBtn.setOnClickListener(v -> { PopupDialog.getInstance(SettingsActivity.this) .setStyle(Styles.STANDARD) .setHeading("Log out!") .setDescription("Are you sure") .setPopupDialogIcon(R.drawable.baseline_logout_24) .setCancelable(true) .setPositiveButtonText("OK") .showDialog(new OnDialogButtonClickListener() { @Override public void onPositiveClicked(Dialog dialog) { super.onPositiveClicked(dialog); userSharePreferences = new UserSharePreferences(SettingsActivity.this); userSharePreferences.clear();
package com.daominh.quickmem.ui.activities.profile; public class SettingsActivity extends AppCompatActivity { private ActivitySettingsBinding binding; private UserSharePreferences userSharePreferences; private AlertDialog detailDialog; UserDAO userDAO; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivitySettingsBinding.inflate(getLayoutInflater()); final View view = binding.getRoot(); setContentView(view); userSharePreferences = new UserSharePreferences(SettingsActivity.this); binding.usernameTv.setText(userSharePreferences.getUserName()); binding.emailTv.setText(userSharePreferences.getEmail()); onClickItemSetting(); setSupportActionBar(binding.toolbar); binding.toolbar.setNavigationOnClickListener(v -> finish()); } private void onClickItemSetting() { binding.usernameCl.setOnClickListener(view -> openDialogChangeUsername()); binding.emailCl.setOnClickListener(view -> openDialogChangeEmail()); binding.passwordCl.setOnClickListener(view -> { startActivity(new Intent(SettingsActivity.this, ChangePasswordActivity.class)); }); binding.logOutBtn.setOnClickListener(v -> { PopupDialog.getInstance(SettingsActivity.this) .setStyle(Styles.STANDARD) .setHeading("Log out!") .setDescription("Are you sure") .setPopupDialogIcon(R.drawable.baseline_logout_24) .setCancelable(true) .setPositiveButtonText("OK") .showDialog(new OnDialogButtonClickListener() { @Override public void onPositiveClicked(Dialog dialog) { super.onPositiveClicked(dialog); userSharePreferences = new UserSharePreferences(SettingsActivity.this); userSharePreferences.clear();
Intent intent = new Intent(SettingsActivity.this, SignInActivity.class);
2
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;
16,128
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(),
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,
2
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;
18,616
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() {
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();
0
2023-11-09 16:10:00+00:00
24k
estkme-group/InfiLPA
core/src/main/java/com/infineon/esim/lpa/core/es9plus/Es9PlusInterface.java
[ { "identifier": "AuthenticateClientRequest", "path": "messages/src/main/java/com/gsma/sgp/messages/rspdefinitions/AuthenticateClientRequest.java", "snippet": "public class AuthenticateClientRequest implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic stati...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.gsma.sgp.messages.rspdefinitions.AuthenticateClientRequest; import com.gsma.sgp.messages.rspdefinitions.AuthenticateClientResponseEs9; import com.gsma.sgp.messages.rspdefinitions.CancelSessionRequestEs9; import com.gsma.sgp.messages.rspdefinitions.CancelSessionResponseEs9; import com.gsma.sgp.messages.rspdefinitions.GetBoundProfilePackageRequest; import com.gsma.sgp.messages.rspdefinitions.GetBoundProfilePackageResponse; import com.gsma.sgp.messages.rspdefinitions.InitiateAuthenticationRequest; import com.gsma.sgp.messages.rspdefinitions.InitiateAuthenticationResponse; import com.gsma.sgp.messages.rspdefinitions.PendingNotification; import com.infineon.esim.lpa.core.es9plus.messages.HttpResponse; import com.infineon.esim.lpa.core.es9plus.messages.request.AuthenticateClientReq; import com.infineon.esim.lpa.core.es9plus.messages.request.CancelSessionReq; import com.infineon.esim.lpa.core.es9plus.messages.request.GetBoundProfilePackageReq; import com.infineon.esim.lpa.core.es9plus.messages.request.HandleNotificationReq; import com.infineon.esim.lpa.core.es9plus.messages.request.InitiateAuthenticationReq; import com.infineon.esim.lpa.core.es9plus.messages.response.AuthenticateClientResp; import com.infineon.esim.lpa.core.es9plus.messages.response.CancelSessionResp; import com.infineon.esim.lpa.core.es9plus.messages.response.GetBoundProfilePackageResp; import com.infineon.esim.lpa.core.es9plus.messages.response.InitiateAuthenticationResp; import com.infineon.esim.lpa.core.es9plus.messages.response.base.FunctionExecutionStatus; import com.infineon.esim.lpa.core.es9plus.messages.response.base.ResponseMsgBody; import com.infineon.esim.util.Log; import javax.net.ssl.HttpsURLConnection;
18,843
/* * 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; public class Es9PlusInterface { private static final String TAG = Es9PlusInterface.class.getName(); private static final Gson GS = new GsonBuilder().disableHtmlEscaping().create(); private static final String INITIATE_AUTHENTICATION_PATH = "/gsma/rsp2/es9plus/initiateAuthentication"; private static final String AUTHENTICATE_CLIENT_PATH = "/gsma/rsp2/es9plus/authenticateClient"; private static final String GET_BOUND_PROFILE_PACKAGE_PATH = "/gsma/rsp2/es9plus/getBoundProfilePackage"; private static final String HANDLE_NOTIFICATION_PATH = "/gsma/rsp2/es9plus/handleNotification"; private static final String CANCEL_SESSION_PATH = "/gsma/rsp2/es9plus/cancelSession"; private final HttpsClient httpsClient; private String smdpAddress; private FunctionExecutionStatus lastFunctionExecutionStatus = null; public Es9PlusInterface() { this.httpsClient = new HttpsClient(); } public void setSmdpAddress(String smdpAddress) { this.smdpAddress = smdpAddress; }
/* * 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; public class Es9PlusInterface { private static final String TAG = Es9PlusInterface.class.getName(); private static final Gson GS = new GsonBuilder().disableHtmlEscaping().create(); private static final String INITIATE_AUTHENTICATION_PATH = "/gsma/rsp2/es9plus/initiateAuthentication"; private static final String AUTHENTICATE_CLIENT_PATH = "/gsma/rsp2/es9plus/authenticateClient"; private static final String GET_BOUND_PROFILE_PACKAGE_PATH = "/gsma/rsp2/es9plus/getBoundProfilePackage"; private static final String HANDLE_NOTIFICATION_PATH = "/gsma/rsp2/es9plus/handleNotification"; private static final String CANCEL_SESSION_PATH = "/gsma/rsp2/es9plus/cancelSession"; private final HttpsClient httpsClient; private String smdpAddress; private FunctionExecutionStatus lastFunctionExecutionStatus = null; public Es9PlusInterface() { this.httpsClient = new HttpsClient(); } public void setSmdpAddress(String smdpAddress) { this.smdpAddress = smdpAddress; }
public InitiateAuthenticationResponse initiateAuthentication(InitiateAuthenticationRequest initiateAuthenticationRequest) throws Exception {
6
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,053
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,
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,
4
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,540
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;否则就是没有通过;
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);
3
2023-11-03 02:29:57+00:00
24k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/db/kernel/MysqlDb.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.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import org.by1337.api.util.NameKey; import org.by1337.bauction.Main; import org.by1337.bauction.auc.SellItem; import org.by1337.bauction.auc.UnsoldItem; import org.by1337.bauction.db.action.Action; import org.by1337.bauction.db.action.ActionGiveMoney; import org.by1337.bauction.db.action.ActionType; import org.by1337.bauction.db.event.BuyItemCountEvent; import org.by1337.bauction.db.event.BuyItemEvent; import org.by1337.bauction.network.PacketConnection; import org.by1337.bauction.network.PacketIn; import org.by1337.bauction.network.PacketListener; import org.by1337.bauction.network.PacketType; import org.by1337.bauction.network.in.*; import org.by1337.bauction.network.out.*; import org.by1337.bauction.util.Category; import org.by1337.bauction.util.MoneyGiver; import org.by1337.bauction.util.Sorting; import org.by1337.bauction.util.UniqueName; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.sql.*; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue;
15,018
String sql = null; for (int i = 0; i < 200; i++) { sql = sqlQueue.poll(); if (sql == null) { break; } try (PreparedStatement stat = connection.prepareStatement(sql)) { stat.execute(); } catch (SQLException e) { Main.getMessage().error(e); } } if (sql != null) { Main.getMessage().warning("the number of sql requests is more than 200!"); } } }.runTaskTimerAsynchronously(Main.getInstance(), 10, 1); //</editor-fold> if (isHead) { logClearTask = Bukkit.getScheduler().runTaskTimerAsynchronously( Main.getInstance(), () -> sqlQueue.offer("DELETE FROM logs WHERE time < " + (System.currentTimeMillis() - 3600000L / 2)), 500, 3600000L / 2 ); } else { logClearTask = null; } updateTask = Bukkit.getScheduler().runTaskTimerAsynchronously(Main.getInstance(), () -> update(), 40, 40); } @Override protected void unsoldItemRemover() { if (removeExpiredItems) { unsoldItemRemChecker = () -> { long time = System.currentTimeMillis(); try { long sleep = 50L * 5; int removed = 0; while (getUnsoldItemsSize() > 0) { UnsoldItem unsoldItem = getFirstUnsoldItem(); if (unsoldItem.getDeleteVia() < time) { if (isHead) { removeUnsoldItem(unsoldItem.getUniqueName()); } else { super.removeUnsoldItem(unsoldItem.getUniqueName()); } removed++; if (removed >= 30) break; } else { sleep = Math.min((unsoldItem.getDeleteVia() - time) + 50, 50L * 100); // 100 ticks break; } } if (unsoldItemRemCheckerTask.isCancelled()) return; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, sleep / 50); } catch (Exception e) { Main.getMessage().error(e); } }; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, 0); } } @Override protected void expiredItem(SellItem item) { if (isHead) { super.expiredItem(item); } else { super.removeSellItem(item.getUniqueName()); } } @Override public void addSellItem(@NotNull SellItem sellItem) { super.addSellItem(sellItem); execute(sellItem.toSql("sell_items")); log(new Action(ActionType.ADD_SELL_ITEM, sellItem.getSellerUuid(), sellItem.getUniqueName(), server)); packetConnection.saveSend(new PlayOutAddSellItemPacket(sellItem)); } @Override protected void replaceUser(CUser user) { super.replaceUser(user); execute(user.toSqlUpdate("users")); log(new Action(ActionType.UPDATE_USER, user.getUuid(), null, server)); packetConnection.saveSend(new PlayOutUpdateUserPacket(user)); } @Override protected CUser addUser(CUser user) { super.addUser(user); execute(user.toSql("users")); log(new Action(ActionType.UPDATE_USER, user.getUuid(), null, server)); packetConnection.saveSend(new PlayOutUpdateUserPacket(user)); return user; } private void updateUsers(UUID user, UUID user1) { CUser buyer = (CUser) getUser(user); CUser owner = (CUser) getUser(user1); if (buyer != null) { execute(buyer.toSqlUpdate("users")); log(new Action(ActionType.UPDATE_USER, buyer.getUuid(), null, server)); packetConnection.saveSend(new PlayOutUpdateUserPacket(buyer)); } if (owner != null) { execute(owner.toSqlUpdate("users")); log(new Action(ActionType.UPDATE_USER, owner.getUuid(), null, server)); packetConnection.saveSend(new PlayOutUpdateUserPacket(owner)); } } @Override
package org.by1337.bauction.db.kernel; public class MysqlDb extends FileDataBase implements PacketListener { private final Connection connection; private final PacketConnection packetConnection; private final UUID server = UUID.randomUUID(); private final ConcurrentLinkedQueue<String> sqlQueue = new ConcurrentLinkedQueue<>(); private final BukkitTask sqlExecuteTask; @Nullable private final BukkitTask logClearTask; private final BukkitTask updateTask; private final boolean isHead; private long lastLogCheck; private final MoneyGiver moneyGiver; public MysqlDb(Map<NameKey, Category> categoryMap, Map<NameKey, Sorting> sortingMap, String host, String name, String user, String password, int port) throws SQLException { super(categoryMap, sortingMap); isHead = Main.getDbCfg().getContext().getAsBoolean("mysql-settings.is-head"); packetConnection = new PacketConnection(this); moneyGiver = new MoneyGiver(this); connection = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + name + "?useUnicode=true&characterEncoding=utf8&autoReconnect=true", user, password ); String[] createTableStatements = { //<editor-fold desc="create tables sqls" defaultstate="collapsed"> """ CREATE TABLE IF NOT EXISTS give_money (server VARBINARY(36) NOT NULL, uuid VARCHAR(36) NOT NULL, count DOUBLE NOT NULL) """, """ CREATE TABLE IF NOT EXISTS unsold_items ( uuid VARBINARY(36) NOT NULL PRIMARY KEY, seller_uuid VARCHAR(36) NOT NULL, item TEXT NOT NULL, delete_via BIGINT NOT NULL, expired BIGINT NOT NULL ) """, """ CREATE TABLE IF NOT EXISTS sell_items ( uuid VARBINARY(36) NOT NULL PRIMARY KEY, seller_uuid VARCHAR(36) NOT NULL, item TEXT NOT NULL, seller_name VARCHAR(50) NOT NULL, price DOUBLE NOT NULL, sale_by_the_piece BOOLEAN NOT NULL, tags TEXT NOT NULL, time_listed_for_sale BIGINT NOT NULL, removal_date BIGINT NOT NULL, material VARCHAR(50) NOT NULL, amount TINYINT NOT NULL, price_for_one DOUBLE NOT NULL, sell_for TEXT NOT NULL, server VARBINARY(36) NOT NULL ) """, """ CREATE TABLE IF NOT EXISTS users ( uuid VARBINARY(36) NOT NULL PRIMARY KEY, name VARCHAR(50) NOT NULL, deal_count INT NOT NULL, deal_sum DOUBLE NOT NULL ) """, """ CREATE TABLE IF NOT EXISTS logs ( time BIGINT NOT NULL, type VARCHAR(20) NOT NULL, owner VARCHAR(36) NOT NULL, server VARCHAR(36) NOT NULL, uuid VARCHAR(36), INDEX idx_time (time) ) """ //</editor-fold> }; for (String sql : createTableStatements) { try (PreparedStatement stat = connection.prepareStatement(sql.replace("\n", ""))) { stat.execute(); } } sqlExecuteTask = //<editor-fold desc="sql execute task" defaultstate="collapsed"> new BukkitRunnable() { @Override public void run() { String sql = null; for (int i = 0; i < 200; i++) { sql = sqlQueue.poll(); if (sql == null) { break; } try (PreparedStatement stat = connection.prepareStatement(sql)) { stat.execute(); } catch (SQLException e) { Main.getMessage().error(e); } } if (sql != null) { Main.getMessage().warning("the number of sql requests is more than 200!"); } } }.runTaskTimerAsynchronously(Main.getInstance(), 10, 1); //</editor-fold> if (isHead) { logClearTask = Bukkit.getScheduler().runTaskTimerAsynchronously( Main.getInstance(), () -> sqlQueue.offer("DELETE FROM logs WHERE time < " + (System.currentTimeMillis() - 3600000L / 2)), 500, 3600000L / 2 ); } else { logClearTask = null; } updateTask = Bukkit.getScheduler().runTaskTimerAsynchronously(Main.getInstance(), () -> update(), 40, 40); } @Override protected void unsoldItemRemover() { if (removeExpiredItems) { unsoldItemRemChecker = () -> { long time = System.currentTimeMillis(); try { long sleep = 50L * 5; int removed = 0; while (getUnsoldItemsSize() > 0) { UnsoldItem unsoldItem = getFirstUnsoldItem(); if (unsoldItem.getDeleteVia() < time) { if (isHead) { removeUnsoldItem(unsoldItem.getUniqueName()); } else { super.removeUnsoldItem(unsoldItem.getUniqueName()); } removed++; if (removed >= 30) break; } else { sleep = Math.min((unsoldItem.getDeleteVia() - time) + 50, 50L * 100); // 100 ticks break; } } if (unsoldItemRemCheckerTask.isCancelled()) return; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, sleep / 50); } catch (Exception e) { Main.getMessage().error(e); } }; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, 0); } } @Override protected void expiredItem(SellItem item) { if (isHead) { super.expiredItem(item); } else { super.removeSellItem(item.getUniqueName()); } } @Override public void addSellItem(@NotNull SellItem sellItem) { super.addSellItem(sellItem); execute(sellItem.toSql("sell_items")); log(new Action(ActionType.ADD_SELL_ITEM, sellItem.getSellerUuid(), sellItem.getUniqueName(), server)); packetConnection.saveSend(new PlayOutAddSellItemPacket(sellItem)); } @Override protected void replaceUser(CUser user) { super.replaceUser(user); execute(user.toSqlUpdate("users")); log(new Action(ActionType.UPDATE_USER, user.getUuid(), null, server)); packetConnection.saveSend(new PlayOutUpdateUserPacket(user)); } @Override protected CUser addUser(CUser user) { super.addUser(user); execute(user.toSql("users")); log(new Action(ActionType.UPDATE_USER, user.getUuid(), null, server)); packetConnection.saveSend(new PlayOutUpdateUserPacket(user)); return user; } private void updateUsers(UUID user, UUID user1) { CUser buyer = (CUser) getUser(user); CUser owner = (CUser) getUser(user1); if (buyer != null) { execute(buyer.toSqlUpdate("users")); log(new Action(ActionType.UPDATE_USER, buyer.getUuid(), null, server)); packetConnection.saveSend(new PlayOutUpdateUserPacket(buyer)); } if (owner != null) { execute(owner.toSqlUpdate("users")); log(new Action(ActionType.UPDATE_USER, owner.getUuid(), null, server)); packetConnection.saveSend(new PlayOutUpdateUserPacket(owner)); } } @Override
public void validateAndRemoveItem(BuyItemEvent event) {// hook
7
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;
15,747
@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; final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_modified FROM config_info WHERE "; String where = " 1=1 "; if (!StringUtils.isBlank(dataId)) { where += " AND data_id LIKE ? "; } if (!StringUtils.isBlank(group)) { where += " AND group_id LIKE ? "; } if (!StringUtils.isBlank(tenantTmp)) { where += " AND tenant_id = ? "; } if (!StringUtils.isBlank(appName)) { where += " AND app_name = ? "; } if (startTime != null) { where += " AND gmt_modified >=? "; } if (endTime != null) { where += " AND gmt_modified <=? "; } return sqlFetchRows + where + " AND id > " + lastMaxId + " ORDER BY id ASC" + " LIMIT " + 0 + "," + pageSize; } @Override public String listGroupKeyMd5ByPageFetchRows(int startRow, int pageSize) { return "SELECT t.id,data_id,group_id,tenant_id,app_name,md5,type,gmt_modified,encrypted_data_key FROM " + "( SELECT id FROM config_info ORDER BY id LIMIT " + startRow + "," + pageSize + " ) g, config_info t WHERE g.id = t.id"; } @Override public String findConfigInfoBaseLikeFetchRows(Map<String, String> params, int startRow, int pageSize) { final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE "; String where = " 1=1 AND tenant_id='" + NamespaceUtil.getNamespaceDefaultId() + "' "; if (!StringUtils.isBlank(params.get(DATA_ID))) { where += " AND data_id LIKE ? "; } if (!StringUtils.isBlank(params.get(GROUP))) { where += " AND group_id LIKE "; } if (!StringUtils.isBlank(params.get(CONTENT))) { where += " AND content LIKE ? "; } return sqlFetchRows + where + " LIMIT " + startRow + "," + pageSize; } @Override public String findConfigInfo4PageFetchRows(Map<String, String> params, int startRow, int pageSize) { final String appName = params.get(APP_NAME); final String dataId = params.get(DATA_ID); final String group = params.get(GROUP); final String content = params.get(CONTENT); final String sql = "SELECT id,data_id,group_id,tenant_id,app_name,content,type,encrypted_data_key FROM config_info"; StringBuilder where = new StringBuilder(" WHERE "); where.append(" tenant_id=? "); if (StringUtils.isNotBlank(dataId)) { where.append(" AND data_id=? "); } if (StringUtils.isNotBlank(group)) { where.append(" AND group_id=? "); } if (StringUtils.isNotBlank(appName)) { where.append(" AND app_name=? "); } if (!StringUtils.isBlank(content)) { where.append(" AND content LIKE ? "); } return sql + where + " LIMIT " + startRow + "," + pageSize; } @Override public String findConfigInfoBaseByGroupFetchRows(int startRow, int pageSize) { return "SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND tenant_id=?" + " LIMIT " + startRow + "," + pageSize; } @Override public String findConfigInfoLike4PageFetchRows(Map<String, String> params, int startRow, int pageSize) { String dataId = params.get(DATA_ID); String group = params.get(GROUP); final String appName = params.get(APP_NAME); final String content = params.get(CONTENT); final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info"; StringBuilder where = new StringBuilder(" WHERE "); where.append(" tenant_id LIKE ? "); if (!StringUtils.isBlank(dataId)) { where.append(" AND data_id LIKE ? "); } if (!StringUtils.isBlank(group)) { where.append(" AND group_id LIKE ? "); } if (!StringUtils.isBlank(appName)) { where.append(" AND app_name = ? "); } if (!StringUtils.isBlank(content)) { where.append(" AND content LIKE ? "); } return sqlFetchRows + where + " LIMIT " + startRow + "," + pageSize; } @Override public String findAllConfigInfoFetchRows(int startRow, int pageSize) { return "SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5 " + " FROM ( SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT ?,? )" + " g, config_info t WHERE g.id = t.id "; } @Override public String getDataSource() {
/* * 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; final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_modified FROM config_info WHERE "; String where = " 1=1 "; if (!StringUtils.isBlank(dataId)) { where += " AND data_id LIKE ? "; } if (!StringUtils.isBlank(group)) { where += " AND group_id LIKE ? "; } if (!StringUtils.isBlank(tenantTmp)) { where += " AND tenant_id = ? "; } if (!StringUtils.isBlank(appName)) { where += " AND app_name = ? "; } if (startTime != null) { where += " AND gmt_modified >=? "; } if (endTime != null) { where += " AND gmt_modified <=? "; } return sqlFetchRows + where + " AND id > " + lastMaxId + " ORDER BY id ASC" + " LIMIT " + 0 + "," + pageSize; } @Override public String listGroupKeyMd5ByPageFetchRows(int startRow, int pageSize) { return "SELECT t.id,data_id,group_id,tenant_id,app_name,md5,type,gmt_modified,encrypted_data_key FROM " + "( SELECT id FROM config_info ORDER BY id LIMIT " + startRow + "," + pageSize + " ) g, config_info t WHERE g.id = t.id"; } @Override public String findConfigInfoBaseLikeFetchRows(Map<String, String> params, int startRow, int pageSize) { final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE "; String where = " 1=1 AND tenant_id='" + NamespaceUtil.getNamespaceDefaultId() + "' "; if (!StringUtils.isBlank(params.get(DATA_ID))) { where += " AND data_id LIKE ? "; } if (!StringUtils.isBlank(params.get(GROUP))) { where += " AND group_id LIKE "; } if (!StringUtils.isBlank(params.get(CONTENT))) { where += " AND content LIKE ? "; } return sqlFetchRows + where + " LIMIT " + startRow + "," + pageSize; } @Override public String findConfigInfo4PageFetchRows(Map<String, String> params, int startRow, int pageSize) { final String appName = params.get(APP_NAME); final String dataId = params.get(DATA_ID); final String group = params.get(GROUP); final String content = params.get(CONTENT); final String sql = "SELECT id,data_id,group_id,tenant_id,app_name,content,type,encrypted_data_key FROM config_info"; StringBuilder where = new StringBuilder(" WHERE "); where.append(" tenant_id=? "); if (StringUtils.isNotBlank(dataId)) { where.append(" AND data_id=? "); } if (StringUtils.isNotBlank(group)) { where.append(" AND group_id=? "); } if (StringUtils.isNotBlank(appName)) { where.append(" AND app_name=? "); } if (!StringUtils.isBlank(content)) { where.append(" AND content LIKE ? "); } return sql + where + " LIMIT " + startRow + "," + pageSize; } @Override public String findConfigInfoBaseByGroupFetchRows(int startRow, int pageSize) { return "SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND tenant_id=?" + " LIMIT " + startRow + "," + pageSize; } @Override public String findConfigInfoLike4PageFetchRows(Map<String, String> params, int startRow, int pageSize) { String dataId = params.get(DATA_ID); String group = params.get(GROUP); final String appName = params.get(APP_NAME); final String content = params.get(CONTENT); final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info"; StringBuilder where = new StringBuilder(" WHERE "); where.append(" tenant_id LIKE ? "); if (!StringUtils.isBlank(dataId)) { where.append(" AND data_id LIKE ? "); } if (!StringUtils.isBlank(group)) { where.append(" AND group_id LIKE ? "); } if (!StringUtils.isBlank(appName)) { where.append(" AND app_name = ? "); } if (!StringUtils.isBlank(content)) { where.append(" AND content LIKE ? "); } return sqlFetchRows + where + " LIMIT " + startRow + "," + pageSize; } @Override public String findAllConfigInfoFetchRows(int startRow, int pageSize) { return "SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5 " + " FROM ( SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT ?,? )" + " g, config_info t WHERE g.id = t.id "; } @Override public String getDataSource() {
return DataSourceConstant.DM;
2
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,540
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;否则就是没有通过;
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);
3
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,602
/* * 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 {
/* * 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);
0
2023-11-03 23:19:08+00:00
24k
data-harness-cloud/data_harness-be
common/common-datafilter/src/main/java/supie/common/datafilter/interceptor/MybatisDataFilterInterceptor.java
[ { "identifier": "BaseDaoMapper", "path": "common/common-core/src/main/java/supie/common/core/base/dao/BaseDaoMapper.java", "snippet": "public interface BaseDaoMapper<M> extends BaseMapper<M> {\n\n /**\n * 根据指定的表名、显示字段列表、过滤条件字符串和分组字段,返回聚合计算后的查询结果。\n *\n * @param selectTable 表名称。\n *...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.lang.Assert; import cn.hutool.core.map.MapUtil; import cn.hutool.core.text.StrFormatter; import cn.hutool.core.util.BooleanUtil; import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.annotation.TableName; import supie.common.core.base.dao.BaseDaoMapper; import supie.common.core.annotation.*; import supie.common.core.cache.CacheConfig; import supie.common.core.constant.ApplicationConstant; import supie.common.core.exception.NoDataPermException; import supie.common.core.object.GlobalThreadLocal; import supie.common.core.object.TokenData; import supie.common.core.util.ApplicationContextHolder; import supie.common.core.util.ContextUtil; import supie.common.core.util.MyModelUtil; import supie.common.core.util.RedisKeyUtil; import supie.common.core.constant.DataPermRuleType; import supie.common.datafilter.config.DataFilterProperties; import lombok.Data; import lombok.extern.slf4j.Slf4j; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.operators.conditional.AndExpression; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.delete.Delete; import net.sf.jsqlparser.statement.select.FromItem; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.select.SubSelect; import net.sf.jsqlparser.statement.update.Update; import org.apache.ibatis.executor.statement.RoutingStatementHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlCommandType; import org.apache.ibatis.plugin.*; import org.redisson.api.RBucket; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.util.*;
19,845
package supie.common.datafilter.interceptor; /** * Mybatis拦截器。目前用于数据权限的统一拦截和注入处理。 * * @author rm -rf .bug * @date 2020-11-12 */ @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) @Slf4j @Component public class MybatisDataFilterInterceptor implements Interceptor { @Autowired private RedissonClient redissonClient; @Autowired private DataFilterProperties properties; @Resource(name = "caffeineCacheManager") private CacheManager cacheManager; /** * 对象缓存。由于Set是排序后的,因此在查找排除方法名称时效率更高。 * 在应用服务启动的监听器中(LoadDataPermMapperListener),会调用当前对象的(loadMappersWithDataPerm)方法,加载缓存。 */ private final Map<String, ModelDataPermInfo> cachedDataPermMap = MapUtil.newHashMap(); /** * 租户租户对象缓存。 */ private final Map<String, ModelTenantInfo> cachedTenantMap = MapUtil.newHashMap(); /** * 预先加载与数据过滤相关的数据到缓存,该函数会在(LoadDataFilterInfoListener)监听器中调用。 */ public void loadInfoWithDataFilter() { @SuppressWarnings("all") Map<String, BaseDaoMapper> mapperMap = ApplicationContextHolder.getApplicationContext().getBeansOfType(BaseDaoMapper.class); for (BaseDaoMapper<?> mapperProxy : mapperMap.values()) { // 优先处理jdk的代理 Object proxy = ReflectUtil.getFieldValue(mapperProxy, "h"); // 如果不是jdk的代理,再看看cjlib的代理。 if (proxy == null) { proxy = ReflectUtil.getFieldValue(mapperProxy, "CGLIB$CALLBACK_0"); } Class<?> mapperClass = (Class<?>) ReflectUtil.getFieldValue(proxy, "mapperInterface"); if (BooleanUtil.isTrue(properties.getEnabledTenantFilter())) { loadTenantFilterData(mapperClass); } if (BooleanUtil.isTrue(properties.getEnabledDataPermFilter())) { EnableDataPerm rule = mapperClass.getAnnotation(EnableDataPerm.class); if (rule != null) { loadDataPermFilterRules(mapperClass, rule); } } } } private void loadTenantFilterData(Class<?> mapperClass) { Class<?> modelClass = (Class<?>) ((ParameterizedType) mapperClass.getGenericInterfaces()[0]).getActualTypeArguments()[0]; Field[] fields = ReflectUtil.getFields(modelClass); for (Field field : fields) { if (field.getAnnotation(TenantFilterColumn.class) != null) { ModelTenantInfo tenantInfo = new ModelTenantInfo(); tenantInfo.setModelName(modelClass.getSimpleName()); tenantInfo.setTableName(modelClass.getAnnotation(TableName.class).value()); tenantInfo.setFieldName(field.getName());
package supie.common.datafilter.interceptor; /** * Mybatis拦截器。目前用于数据权限的统一拦截和注入处理。 * * @author rm -rf .bug * @date 2020-11-12 */ @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) @Slf4j @Component public class MybatisDataFilterInterceptor implements Interceptor { @Autowired private RedissonClient redissonClient; @Autowired private DataFilterProperties properties; @Resource(name = "caffeineCacheManager") private CacheManager cacheManager; /** * 对象缓存。由于Set是排序后的,因此在查找排除方法名称时效率更高。 * 在应用服务启动的监听器中(LoadDataPermMapperListener),会调用当前对象的(loadMappersWithDataPerm)方法,加载缓存。 */ private final Map<String, ModelDataPermInfo> cachedDataPermMap = MapUtil.newHashMap(); /** * 租户租户对象缓存。 */ private final Map<String, ModelTenantInfo> cachedTenantMap = MapUtil.newHashMap(); /** * 预先加载与数据过滤相关的数据到缓存,该函数会在(LoadDataFilterInfoListener)监听器中调用。 */ public void loadInfoWithDataFilter() { @SuppressWarnings("all") Map<String, BaseDaoMapper> mapperMap = ApplicationContextHolder.getApplicationContext().getBeansOfType(BaseDaoMapper.class); for (BaseDaoMapper<?> mapperProxy : mapperMap.values()) { // 优先处理jdk的代理 Object proxy = ReflectUtil.getFieldValue(mapperProxy, "h"); // 如果不是jdk的代理,再看看cjlib的代理。 if (proxy == null) { proxy = ReflectUtil.getFieldValue(mapperProxy, "CGLIB$CALLBACK_0"); } Class<?> mapperClass = (Class<?>) ReflectUtil.getFieldValue(proxy, "mapperInterface"); if (BooleanUtil.isTrue(properties.getEnabledTenantFilter())) { loadTenantFilterData(mapperClass); } if (BooleanUtil.isTrue(properties.getEnabledDataPermFilter())) { EnableDataPerm rule = mapperClass.getAnnotation(EnableDataPerm.class); if (rule != null) { loadDataPermFilterRules(mapperClass, rule); } } } } private void loadTenantFilterData(Class<?> mapperClass) { Class<?> modelClass = (Class<?>) ((ParameterizedType) mapperClass.getGenericInterfaces()[0]).getActualTypeArguments()[0]; Field[] fields = ReflectUtil.getFields(modelClass); for (Field field : fields) { if (field.getAnnotation(TenantFilterColumn.class) != null) { ModelTenantInfo tenantInfo = new ModelTenantInfo(); tenantInfo.setModelName(modelClass.getSimpleName()); tenantInfo.setTableName(modelClass.getAnnotation(TableName.class).value()); tenantInfo.setFieldName(field.getName());
tenantInfo.setColumnName(MyModelUtil.mapToColumnName(field, modelClass));
8
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,754
/* * 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;
/* * 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;
private final MomentoLockClient momentoLockClient;
3
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;
14,944
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;
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;
13
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;
15,971
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) {
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);
0
2023-11-04 13:19:21+00:00
24k
RezaGooner/University-food-ordering
Frames/Admin/Managment/ColorChangeMenu.java
[ { "identifier": "LoginFrame", "path": "Frames/LoginFrame.java", "snippet": "public class LoginFrame extends JFrame {\r\n\r\n public static boolean isNumeric(String str) {\r\n if (str == null || str.length() == 0) {\r\n return false;\r\n }\r\n try {\r\n Long....
import static Classes.Pathes.ClassesPath.*; import static Frames.Admin.Managment.ChangeThemeColor.changeColor; import static Frames.Admin.Managment.ColorChooser.setColor; import static Frames.Profile.ChangePasswordFrame.colorBackground; import static Frames.Profile.ChangePasswordFrame.colorButton; import Frames.LoginFrame; import Frames.Order.UniversitySelfRestaurant; import Frames.Profile.ForgotPassword; import Frames.Profile.NewUserFrame; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
21,009
package Frames.Admin.Managment; /* این کد جاوا یک کلاس است که متد setColor() را دارد. این متد یک پنجره رنگ انتخاب کننده باز می کند و رنگ انتخاب شده توسط کاربر را برمی گرداند. در ابتدا، یک آرایه رشته ای و سه آرایه از integer تعریف می شود. پس از باز شدن پنجره رنگ انتخاب کننده، مقادیر رنگ قرمز، سبز و آبی را از رنگ انتخاب شده به دست می آورد و آنها را در آرایه های integer مربوطه ذخیره می کند. سپس پیامی به کاربر نمایش داده می شود که تغییرات با موفقیت اعمال شده است و رشته ای که شامل مقادیر رنگ است برمی گردانده می شود. در صورتی که کاربر هیچ رنگی را انتخاب نکرده باشد، مقدار null برگردانده می شود. ````````````````````````````````````````````````````` It extends the `JFrame` class and provides a graphical user interface for changing the colors of different frames in a Java Swing application. Here is a breakdown of the code: 1. The code imports various classes from different packages, including `javax.swing` for GUI components and `java.awt` for basic AWT components. 2. The `ColorChangeMenu` class is defined, which extends the `JFrame` class. 3. The constructor of the `ColorChangeMenu` class is defined. It sets up the main frame by setting the title, making it non-resizable, and positioning it at the center of the screen. 4. A `JPanel` named `panel` is created with a grid layout of 5 rows and 1 column. This panel will contain other panels representing different menus. 5. Five panels (`panel1` to `panel5`) are created, each representing a different menu. Each panel has a titled border. 6. Within each panel, there are two buttons and two labels representing the background color and button color of the corresponding frame. The buttons are initially set to the current colors of the frames. When clicked, these buttons open a color chooser dialog (`JColorChooser`) that allows the user to select a new color. 7. The `ColorChangeListener` class is defined as an inner class within `ColorChangeMenu`. This class implements the `ActionListener` interface and is responsible for handling color change events when the buttons are clicked. 8. The `actionPerformed` method of `ColorChangeListener` is implemented to handle the button click events. It opens a color chooser dialog and retrieves the selected color. Then it updates the background color or button color of the corresponding frame, based on which button was clicked. 9. The `main` method is defined, which creates an instance of `ColorChangeMenu` and sets it visible. Overall, this code creates a GUI with multiple panels, each allowing the user to change the colors of different frames in a Java Swing application. */ public class ColorChangeMenu extends JFrame { public ColorChangeMenu() { setTitle("تغییر رنگ منو ها"); setResizable(false); setLocationRelativeTo(null); JPanel panel = new JPanel(new GridLayout(5, 1)); JPanel panel1 = new JPanel (); panel1.setBorder(new TitledBorder(null, "منوی ورود", TitledBorder.LEFT, TitledBorder.TOP)); JButton button12 = new JButton("");
package Frames.Admin.Managment; /* این کد جاوا یک کلاس است که متد setColor() را دارد. این متد یک پنجره رنگ انتخاب کننده باز می کند و رنگ انتخاب شده توسط کاربر را برمی گرداند. در ابتدا، یک آرایه رشته ای و سه آرایه از integer تعریف می شود. پس از باز شدن پنجره رنگ انتخاب کننده، مقادیر رنگ قرمز، سبز و آبی را از رنگ انتخاب شده به دست می آورد و آنها را در آرایه های integer مربوطه ذخیره می کند. سپس پیامی به کاربر نمایش داده می شود که تغییرات با موفقیت اعمال شده است و رشته ای که شامل مقادیر رنگ است برمی گردانده می شود. در صورتی که کاربر هیچ رنگی را انتخاب نکرده باشد، مقدار null برگردانده می شود. ````````````````````````````````````````````````````` It extends the `JFrame` class and provides a graphical user interface for changing the colors of different frames in a Java Swing application. Here is a breakdown of the code: 1. The code imports various classes from different packages, including `javax.swing` for GUI components and `java.awt` for basic AWT components. 2. The `ColorChangeMenu` class is defined, which extends the `JFrame` class. 3. The constructor of the `ColorChangeMenu` class is defined. It sets up the main frame by setting the title, making it non-resizable, and positioning it at the center of the screen. 4. A `JPanel` named `panel` is created with a grid layout of 5 rows and 1 column. This panel will contain other panels representing different menus. 5. Five panels (`panel1` to `panel5`) are created, each representing a different menu. Each panel has a titled border. 6. Within each panel, there are two buttons and two labels representing the background color and button color of the corresponding frame. The buttons are initially set to the current colors of the frames. When clicked, these buttons open a color chooser dialog (`JColorChooser`) that allows the user to select a new color. 7. The `ColorChangeListener` class is defined as an inner class within `ColorChangeMenu`. This class implements the `ActionListener` interface and is responsible for handling color change events when the buttons are clicked. 8. The `actionPerformed` method of `ColorChangeListener` is implemented to handle the button click events. It opens a color chooser dialog and retrieves the selected color. Then it updates the background color or button color of the corresponding frame, based on which button was clicked. 9. The `main` method is defined, which creates an instance of `ColorChangeMenu` and sets it visible. Overall, this code creates a GUI with multiple panels, each allowing the user to change the colors of different frames in a Java Swing application. */ public class ColorChangeMenu extends JFrame { public ColorChangeMenu() { setTitle("تغییر رنگ منو ها"); setResizable(false); setLocationRelativeTo(null); JPanel panel = new JPanel(new GridLayout(5, 1)); JPanel panel1 = new JPanel (); panel1.setBorder(new TitledBorder(null, "منوی ورود", TitledBorder.LEFT, TitledBorder.TOP)); JButton button12 = new JButton("");
button12.setBackground(LoginFrame.colorBackground);
7
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,728
private void initializeEngine(Engine engine) { try { ProcessBuilder processBuilder; if (!IS_WINDOWS && getFileExtension(engine.getPath()).contentEquals("exe")) { processBuilder = new ProcessBuilder("wine", engine.getPath()); } else { processBuilder = new ProcessBuilder(engine.getPath()); } processBuilder.directory((new File(engine.getPath())).getParentFile()); process = processBuilder.start(); } catch (IOException ex) { Logger.getLogger(EngineManager.class.getName()).log(Level.SEVERE, null, ex); return; } stdin = process.getOutputStream(); bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); } private void initiateUSIProtocol() throws IOException { stdin.write("usi\n".getBytes()); stdin.flush(); String line; while ((line = bufferedReader.readLine()) != null) { if (line.contains("usiok")) { return; } } } private void setOptions(Engine engine) throws IOException { for (EngineOption option : engine.getEngineOptionList()) { if (!option.getDef().contentEquals(option.getValue())) { stdin.write(("setoption " + option.getName() + " value " + option.getValue() + "\n").getBytes()); } } stdin.write(("setoption USI_AnalyseMode value true\n").getBytes()); } private void getReady() throws IOException { stdin.write("isready\n".getBytes()); stdin.flush(); String line; while ((line = bufferedReader.readLine()) != null) { if (line.contains("readyok")) { stdin.write("usinewgame\n".getBytes()); stdin.flush(); return; } } } private void quitEngine() throws IOException { stdin.write("quit\n".getBytes()); stdin.flush(); process.destroy(); } private void analysePosition(Game game, String sfen, String engineMove, String japaneseMove, JTable analysisTable, DefaultIntervalXYDataset plotDataset, int moveNum, Turn turn, Coordinate previousMoveDestination) throws IOException { stdin.write(("position sfen " + sfen + " " + engineMove + "\n").getBytes()); stdin.write(("go movetime " + analysisTimePerMove * 1000 + "\n").getBytes()); stdin.flush(); String line; List<String> lineList = new ArrayList<>(); while (!interrupted && (line = bufferedReader.readLine()) != null) { if (Thread.interrupted()) { stdin.write("stop\n".getBytes()); stdin.flush(); interrupted = true; } if (line.contains("bestmove")) { String bestLine = getBestLine(line, lineList); ArrayList<Position> pvPositionList = getPVPositionList(sfen, bestLine, previousMoveDestination); updateTableModel(analysisTable, getTableInsert(bestLine, moveNum, turn, japaneseMove, pvPositionList, plotDataset, engineMove.contentEquals(pvPositionList.get(0).getNotation().getEngineMove()))); game.getAnalysisPositionList().add(pvPositionList); return; } lineList.add(line); } } private ArrayList<Position> getPVPositionList(String sfen, String bestLine, Coordinate previousMoveDestination) { ArrayList<Position> result = new ArrayList<>(); String currentSfen = sfen; Coordinate thisPreviousMoveDestination = previousMoveDestination; for (String move : getBestLineMoveList(bestLine)) { Position position = getPosition(currentSfen, move, thisPreviousMoveDestination); result.add(position); currentSfen = position.getGameSFEN(); thisPreviousMoveDestination = position.getDestination(); } return result; } private Position getPosition(String sfen, String move, Coordinate lastDestination) { Board board = SFENParser.parse(sfen); Notation notation = executeMove(board, move, lastDestination); return new Position(SFENParser.getSFEN(board), board.getSource(), board.getDestination(), notation); } private Notation executeMove(Board board, String move, Coordinate lastDestination) { Coordinate thisDestination; Coordinate thisSource; Koma.Type sourceKomaType; boolean isDrop = isDrop(move); String disambiguation; thisDestination = getDestinationCoordinate(move); if (thisDestination == null) { Notation notation = new Notation(); notation.setEngineMove(move); notation.setJapanese(move); return notation; } if (isDrop) { thisSource = null; Koma sourceKoma = ParserUtils.getDropKoma(move.substring(0, 1), board.getNextTurn()); sourceKomaType = sourceKoma.getType();
/* 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")) { processBuilder = new ProcessBuilder("wine", engine.getPath()); } else { processBuilder = new ProcessBuilder(engine.getPath()); } processBuilder.directory((new File(engine.getPath())).getParentFile()); process = processBuilder.start(); } catch (IOException ex) { Logger.getLogger(EngineManager.class.getName()).log(Level.SEVERE, null, ex); return; } stdin = process.getOutputStream(); bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); } private void initiateUSIProtocol() throws IOException { stdin.write("usi\n".getBytes()); stdin.flush(); String line; while ((line = bufferedReader.readLine()) != null) { if (line.contains("usiok")) { return; } } } private void setOptions(Engine engine) throws IOException { for (EngineOption option : engine.getEngineOptionList()) { if (!option.getDef().contentEquals(option.getValue())) { stdin.write(("setoption " + option.getName() + " value " + option.getValue() + "\n").getBytes()); } } stdin.write(("setoption USI_AnalyseMode value true\n").getBytes()); } private void getReady() throws IOException { stdin.write("isready\n".getBytes()); stdin.flush(); String line; while ((line = bufferedReader.readLine()) != null) { if (line.contains("readyok")) { stdin.write("usinewgame\n".getBytes()); stdin.flush(); return; } } } private void quitEngine() throws IOException { stdin.write("quit\n".getBytes()); stdin.flush(); process.destroy(); } private void analysePosition(Game game, String sfen, String engineMove, String japaneseMove, JTable analysisTable, DefaultIntervalXYDataset plotDataset, int moveNum, Turn turn, Coordinate previousMoveDestination) throws IOException { stdin.write(("position sfen " + sfen + " " + engineMove + "\n").getBytes()); stdin.write(("go movetime " + analysisTimePerMove * 1000 + "\n").getBytes()); stdin.flush(); String line; List<String> lineList = new ArrayList<>(); while (!interrupted && (line = bufferedReader.readLine()) != null) { if (Thread.interrupted()) { stdin.write("stop\n".getBytes()); stdin.flush(); interrupted = true; } if (line.contains("bestmove")) { String bestLine = getBestLine(line, lineList); ArrayList<Position> pvPositionList = getPVPositionList(sfen, bestLine, previousMoveDestination); updateTableModel(analysisTable, getTableInsert(bestLine, moveNum, turn, japaneseMove, pvPositionList, plotDataset, engineMove.contentEquals(pvPositionList.get(0).getNotation().getEngineMove()))); game.getAnalysisPositionList().add(pvPositionList); return; } lineList.add(line); } } private ArrayList<Position> getPVPositionList(String sfen, String bestLine, Coordinate previousMoveDestination) { ArrayList<Position> result = new ArrayList<>(); String currentSfen = sfen; Coordinate thisPreviousMoveDestination = previousMoveDestination; for (String move : getBestLineMoveList(bestLine)) { Position position = getPosition(currentSfen, move, thisPreviousMoveDestination); result.add(position); currentSfen = position.getGameSFEN(); thisPreviousMoveDestination = position.getDestination(); } return result; } private Position getPosition(String sfen, String move, Coordinate lastDestination) { Board board = SFENParser.parse(sfen); Notation notation = executeMove(board, move, lastDestination); return new Position(SFENParser.getSFEN(board), board.getSource(), board.getDestination(), notation); } private Notation executeMove(Board board, String move, Coordinate lastDestination) { Coordinate thisDestination; Coordinate thisSource; Koma.Type sourceKomaType; boolean isDrop = isDrop(move); String disambiguation; thisDestination = getDestinationCoordinate(move); if (thisDestination == null) { Notation notation = new Notation(); notation.setEngineMove(move); notation.setJapanese(move); return notation; } if (isDrop) { thisSource = null; Koma sourceKoma = ParserUtils.getDropKoma(move.substring(0, 1), board.getNextTurn()); sourceKomaType = sourceKoma.getType();
disambiguation = NotationUtils.getDropNotation(board, thisDestination, sourceKomaType);
4
2023-11-08 09:24:57+00:00
24k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/SysUserApplyServiceImpl.java
[ { "identifier": "FriendAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/FriendAdapt.java", "snippet": "public class FriendAdapt {\n\n /**\n * 构建保存好友信息\n *\n * @param applyFriendDTO 申请好友 dto\n * @return {@link SysUserApply }\n * @author q...
import cn.dev33.satoken.stp.StpUtil; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.qingmeng.config.adapt.FriendAdapt; import com.qingmeng.config.adapt.UserSettingAdapt; import com.qingmeng.config.cache.UserCache; import com.qingmeng.dao.SysUserApplyDao; import com.qingmeng.dao.SysUserFriendSettingDao; import com.qingmeng.dto.common.PageDTO; import com.qingmeng.dto.user.AgreeApplyFriendDTO; import com.qingmeng.dto.user.ApplyFriendDTO; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserApply; import com.qingmeng.entity.SysUserFriend; import com.qingmeng.entity.SysUserFriendSetting; import com.qingmeng.enums.user.ApplyFriendChannelEnum; import com.qingmeng.enums.user.ApplyStatusEnum; import com.qingmeng.service.ChatFriendRoomService; import com.qingmeng.service.SysUserApplyService; import com.qingmeng.service.SysUserFriendService; import com.qingmeng.config.strategy.applyFriend.ApplyFriendFactory; import com.qingmeng.config.strategy.applyFriend.ApplyFriendStrategy; import com.qingmeng.utils.AssertUtils; import com.qingmeng.utils.CommonUtils; import com.qingmeng.vo.common.CommonPageVO; import com.qingmeng.vo.user.FriendApplyRecordVO; import org.jetbrains.annotations.NotNull; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
16,009
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:18:00 */ @Service public class SysUserApplyServiceImpl implements SysUserApplyService { @Resource private ApplyFriendFactory applyFriendFactory; @Resource private SysUserApplyDao sysUserApplyDao; @Resource private SysUserFriendSettingDao sysUserFriendSettingDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private ChatFriendRoomService chatFriendRoomService; @Resource private UserCache userCache; /** * 申请好友 * * @param applyFriendDTO 申请好友 dto * @author qingmeng * @createTime: 2023/11/27 15:56:45 */ @Override public void applyFriend(ApplyFriendDTO applyFriendDTO) { // 根据getApplyChannel获取对应渠道的枚举进而获取对应处理的策略实现类 ApplyFriendChannelEnum channelEnum = ApplyFriendChannelEnum.get(applyFriendDTO.getApplyChannel()); ApplyFriendStrategy strategyWithType = applyFriendFactory.getStrategyWithType(channelEnum.getValue()); // 调用具体实现类的applyFriend方法 strategyWithType.applyFriend(applyFriendDTO); } /** * 同意申请好友 * * @param agreeApplyFriendDTO 同意申请好友 dto * @author qingmeng * @createTime: 2023/11/28 17:30:48 */ @Override @Transactional(rollbackFor = Exception.class) public void agreeApply(AgreeApplyFriendDTO agreeApplyFriendDTO) { SysUserApply sysUserApply = checkApplyExist(agreeApplyFriendDTO.getApplyId()); AssertUtils.equal(sysUserApply.getApplyStatus(),ApplyStatusEnum.APPLYING.getCode(), "非法申请状态"); // 判断好友是否已存在 checkFriendExist(sysUserApply); // 获取id组合标识key List<Long> ids = Arrays.asList(sysUserApply.getUserId(), sysUserApply.getTargetId()); String tagKey = CommonUtils.getKeyBySort(ids); // 新增好友设置
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:18:00 */ @Service public class SysUserApplyServiceImpl implements SysUserApplyService { @Resource private ApplyFriendFactory applyFriendFactory; @Resource private SysUserApplyDao sysUserApplyDao; @Resource private SysUserFriendSettingDao sysUserFriendSettingDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private ChatFriendRoomService chatFriendRoomService; @Resource private UserCache userCache; /** * 申请好友 * * @param applyFriendDTO 申请好友 dto * @author qingmeng * @createTime: 2023/11/27 15:56:45 */ @Override public void applyFriend(ApplyFriendDTO applyFriendDTO) { // 根据getApplyChannel获取对应渠道的枚举进而获取对应处理的策略实现类 ApplyFriendChannelEnum channelEnum = ApplyFriendChannelEnum.get(applyFriendDTO.getApplyChannel()); ApplyFriendStrategy strategyWithType = applyFriendFactory.getStrategyWithType(channelEnum.getValue()); // 调用具体实现类的applyFriend方法 strategyWithType.applyFriend(applyFriendDTO); } /** * 同意申请好友 * * @param agreeApplyFriendDTO 同意申请好友 dto * @author qingmeng * @createTime: 2023/11/28 17:30:48 */ @Override @Transactional(rollbackFor = Exception.class) public void agreeApply(AgreeApplyFriendDTO agreeApplyFriendDTO) { SysUserApply sysUserApply = checkApplyExist(agreeApplyFriendDTO.getApplyId()); AssertUtils.equal(sysUserApply.getApplyStatus(),ApplyStatusEnum.APPLYING.getCode(), "非法申请状态"); // 判断好友是否已存在 checkFriendExist(sysUserApply); // 获取id组合标识key List<Long> ids = Arrays.asList(sysUserApply.getUserId(), sysUserApply.getTargetId()); String tagKey = CommonUtils.getKeyBySort(ids); // 新增好友设置
List<SysUserFriendSetting> friendSettingList = UserSettingAdapt.buildDefaultSysUserFriendSetting(ids,tagKey,sysUserApply.getApplyChannel());
11
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,866
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();
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();
GeneratedModItems.loadClass();
1
2023-11-06 12:50:10+00:00
24k
dingodb/dingo-expr
runtime/src/main/java/io/dingodb/expr/runtime/ExprCompiler.java
[ { "identifier": "CastingFactory", "path": "runtime/src/main/java/io/dingodb/expr/runtime/compiler/CastingFactory.java", "snippet": "public final class CastingFactory {\n private CastingFactory() {\n }\n\n public static @NonNull UnaryOp get(Type toType, @NonNull ExprConfig config) {\n Una...
import io.dingodb.expr.runtime.compiler.CastingFactory; import io.dingodb.expr.runtime.compiler.ConstFactory; import io.dingodb.expr.runtime.compiler.VarFactory; import io.dingodb.expr.runtime.compiler.VarStub; import io.dingodb.expr.runtime.exception.ExprCompileException; import io.dingodb.expr.runtime.exception.ExprEvaluatingException; import io.dingodb.expr.runtime.expr.BinaryOpExpr; import io.dingodb.expr.runtime.expr.Expr; import io.dingodb.expr.runtime.expr.ExprVisitorBase; import io.dingodb.expr.runtime.expr.Exprs; import io.dingodb.expr.runtime.expr.IndexOpExpr; import io.dingodb.expr.runtime.expr.NullaryOpExpr; import io.dingodb.expr.runtime.expr.TertiaryOpExpr; import io.dingodb.expr.runtime.expr.UnaryOpExpr; import io.dingodb.expr.runtime.expr.Val; import io.dingodb.expr.runtime.expr.Var; import io.dingodb.expr.runtime.expr.VariadicOpExpr; import io.dingodb.expr.runtime.type.Type; import io.dingodb.expr.runtime.type.Types; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.Arrays;
15,386
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.runtime; @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class ExprCompiler extends ExprVisitorBase<Expr, CompileContext> { public static final ExprCompiler SIMPLE = new ExprCompiler(ExprConfig.SIMPLE); public static final ExprCompiler ADVANCED = new ExprCompiler(ExprConfig.ADVANCED); @Getter private final ExprConfig config; @Override public Expr visitVal(@NonNull Val expr, CompileContext obj) { Type type = expr.getType(); // Do not touch non-scalar type for there's no casting for them. if (type.isScalar()) { Object value = expr.getValue(); Type valueType = Types.valueType(value); if (type.matches(valueType)) { return expr; } return CastingFactory.get(type, config).compile(Exprs.val(value), config); } return expr; } @Override public Expr visitVar(@NonNull Var expr, CompileContext obj) { if (expr.getType() == null) { Object id = expr.getId(); if (id instanceof String) { Val val = ConstFactory.INSTANCE.getConst((String) id); if (val != null) { return val; } } if (obj != null) { return VarFactory.of(id, obj); } throw new ExprCompileException("Compile of vars requires a valid compiling context."); } return expr; } @Override public Expr visitNullaryOpExpr(@NonNull NullaryOpExpr expr, CompileContext obj) { return config.withSimplification() ? expr.simplify(config) : expr; } @Override public Expr visitUnaryOpExpr(@NonNull UnaryOpExpr expr, CompileContext obj) { Expr operand = visit(expr.getOperand(), obj); return expr.getOp().compile(operand, config); } @Override public Expr visitBinaryOpExpr(@NonNull BinaryOpExpr expr, CompileContext obj) { Expr operand0 = visit(expr.getOperand0(), obj); Expr operand1 = visit(expr.getOperand1(), obj); return expr.getOp().compile(operand0, operand1, config); } @Override public Expr visitTertiaryOpExpr(@NonNull TertiaryOpExpr expr, CompileContext obj) { Expr operand0 = visit(expr.getOperand0(), obj); Expr operand1 = visit(expr.getOperand1(), obj); Expr operand2 = visit(expr.getOperand2(), obj); return expr.getOp().compile(operand0, operand1, operand2, config); } @Override public Expr visitVariadicOpExpr(@NonNull VariadicOpExpr expr, CompileContext obj) { Expr[] operands = Arrays.stream(expr.getOperands()) .map(o -> visit(o, obj)) .toArray(Expr[]::new); return expr.getOp().compile(operands, config); } @Override
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.runtime; @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class ExprCompiler extends ExprVisitorBase<Expr, CompileContext> { public static final ExprCompiler SIMPLE = new ExprCompiler(ExprConfig.SIMPLE); public static final ExprCompiler ADVANCED = new ExprCompiler(ExprConfig.ADVANCED); @Getter private final ExprConfig config; @Override public Expr visitVal(@NonNull Val expr, CompileContext obj) { Type type = expr.getType(); // Do not touch non-scalar type for there's no casting for them. if (type.isScalar()) { Object value = expr.getValue(); Type valueType = Types.valueType(value); if (type.matches(valueType)) { return expr; } return CastingFactory.get(type, config).compile(Exprs.val(value), config); } return expr; } @Override public Expr visitVar(@NonNull Var expr, CompileContext obj) { if (expr.getType() == null) { Object id = expr.getId(); if (id instanceof String) { Val val = ConstFactory.INSTANCE.getConst((String) id); if (val != null) { return val; } } if (obj != null) { return VarFactory.of(id, obj); } throw new ExprCompileException("Compile of vars requires a valid compiling context."); } return expr; } @Override public Expr visitNullaryOpExpr(@NonNull NullaryOpExpr expr, CompileContext obj) { return config.withSimplification() ? expr.simplify(config) : expr; } @Override public Expr visitUnaryOpExpr(@NonNull UnaryOpExpr expr, CompileContext obj) { Expr operand = visit(expr.getOperand(), obj); return expr.getOp().compile(operand, config); } @Override public Expr visitBinaryOpExpr(@NonNull BinaryOpExpr expr, CompileContext obj) { Expr operand0 = visit(expr.getOperand0(), obj); Expr operand1 = visit(expr.getOperand1(), obj); return expr.getOp().compile(operand0, operand1, config); } @Override public Expr visitTertiaryOpExpr(@NonNull TertiaryOpExpr expr, CompileContext obj) { Expr operand0 = visit(expr.getOperand0(), obj); Expr operand1 = visit(expr.getOperand1(), obj); Expr operand2 = visit(expr.getOperand2(), obj); return expr.getOp().compile(operand0, operand1, operand2, config); } @Override public Expr visitVariadicOpExpr(@NonNull VariadicOpExpr expr, CompileContext obj) { Expr[] operands = Arrays.stream(expr.getOperands()) .map(o -> visit(o, obj)) .toArray(Expr[]::new); return expr.getOp().compile(operands, config); } @Override
public Expr visitIndexOpExpr(@NonNull IndexOpExpr expr, CompileContext obj) {
10
2023-11-04 08:43:49+00:00
24k
BaderTim/minecraft-measurement-mod
src/main/java/io/github/mmm/measurement/device/DeviceController.java
[ { "identifier": "MMM", "path": "src/main/java/io/github/mmm/MMM.java", "snippet": "@Mod(MMM.MODID)\npublic class MMM {\n // Define mod id in a common place for everything to reference\n public static final String MODID = \"mmm\";\n // Directly reference a slf4j logger\n public static final L...
import io.github.mmm.MMM; import io.github.mmm.measurement.device.objects.imu.IMU; import io.github.mmm.measurement.device.objects.imu.IMUController; import io.github.mmm.measurement.device.objects.lidar.LiDAR; import io.github.mmm.measurement.device.objects.lidar.LiDARController; import io.github.mmm.measurement.device.scans.ImuScan; import io.github.mmm.measurement.device.scans.LidarScan; import io.github.mmm.measurement.device.scans.LidarScan2D; import io.github.mmm.modconfig.Config; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; import net.minecraft.network.chat.Component; import java.awt.*; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import static io.github.mmm.MMM.DEVICE_CONTROLLER; import static io.github.mmm.MMM.MMM_ROOT_PATH; import static io.github.mmm.Utils.saveStringToFile;
14,559
public void stopMeasure() { // save remaining scans ArrayList<LidarScan>[] scans = DEVICE_CONTROLLER.getLidarController().getScans(); for (int i = 0; i < scans.length; i++) { DEVICE_CONTROLLER.saveLiDARScansToFile(scans[i], "lidar" + (i + 1) + ".csv"); } DEVICE_CONTROLLER.getLidarController().clearScans(); ArrayList<ImuScan> imuScans = DEVICE_CONTROLLER.getImuController().getScans(); DEVICE_CONTROLLER.saveIMUScansToFile(imuScans, "imu1.csv"); // send stop message Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".measure.stop"), false); // reset this.currentlyMeasuring = false; this.lidarController = null; this.imuController = null; } public void initDevices() { this.initLidars(); this.initImus(); } private void initLidars() { LocalPlayer player = Minecraft.getInstance().player; ClientLevel level = Minecraft.getInstance().level; if (Config.LIDAR1_SWITCH.get()) { this.lidar1 = new LiDAR( (float)Config.LIDAR1_HORIZONTAL_SCANNING_RADIUS_IN_DEG.get(), (float)Config.LIDAR1_VERTICAL_SCANNING_RADIUS_IN_DEG.get(), Config.LIDAR1_HORIZONTAL_SCANS_PER_RADIUS.get(), Config.LIDAR1_VERTICAL_SCANS_PER_RADIUS.get(), (float)Config.LIDAR1_YAW_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR1_PITCH_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR1_ROLL_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR1_MAXIMUM_MEASUREMENT_DISTANCE.get(), Config.LIDAR1_MEASUREMENT_FREQUENCY_IN_HZ.get(), player, level, new Color(170, 0, 170) ); } else { this.lidar1 = null; } if (Config.LIDAR2_SWITCH.get()) { this.lidar2 = new LiDAR( (float)Config.LIDAR2_HORIZONTAL_SCANNING_RADIUS_IN_DEG.get(), (float)Config.LIDAR2_VERTICAL_SCANNING_RADIUS_IN_DEG.get(), Config.LIDAR2_HORIZONTAL_SCANS_PER_RADIUS.get(), Config.LIDAR2_VERTICAL_SCANS_PER_RADIUS.get(), (float)Config.LIDAR2_YAW_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR2_PITCH_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR2_ROLL_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR2_MAXIMUM_MEASUREMENT_DISTANCE.get(), Config.LIDAR2_MEASUREMENT_FREQUENCY_IN_HZ.get(), player, level, new Color(255, 170, 0) ); } else { this.lidar2 = null; } if (Config.LIDAR3_SWITCH.get()) { this.lidar3 = new LiDAR( (float)Config.LIDAR3_HORIZONTAL_SCANNING_RADIUS_IN_DEG.get(), (float)Config.LIDAR3_VERTICAL_SCANNING_RADIUS_IN_DEG.get(), Config.LIDAR3_HORIZONTAL_SCANS_PER_RADIUS.get(), Config.LIDAR3_VERTICAL_SCANS_PER_RADIUS.get(), (float)Config.LIDAR3_YAW_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR3_PITCH_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR3_ROLL_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR3_MAXIMUM_MEASUREMENT_DISTANCE.get(), Config.LIDAR3_MEASUREMENT_FREQUENCY_IN_HZ.get(), player, level, new Color(0, 170, 170) ); } else { this.lidar3 = null; } } private void initImus() { LocalPlayer player = Minecraft.getInstance().player; if (Config.IMU1_SWITCH.get()) { this.imu1 = new IMU( Config.IMU1_CONSIDER_GRAVITY.get(), Config.IMU1_YAW_OFFSET_FROM_POV_IN_DEG.get(), Config.IMU1_PITCH_OFFSET_FROM_POV_IN_DEG.get(), Config.IMU1_ROLL_OFFSET_FROM_POV_IN_DEG.get(), Config.IMU1_MEAUREMENT_FREQUENCY_IN_HZ.get(), player); } else { this.imu1 = null; } } public void saveLiDARScansToFile(ArrayList<LidarScan> scans, String fileName) { String scansAsString = ""; int nullCounter = 0; for(int i = 0; i < scans.size(); i++) { if(scans.get(i) == null) { nullCounter++; continue; } scansAsString += this.getLidarScanAsSaveString(scans.get(i)); } if (nullCounter == scans.size()) return; saveStringToFile(scansAsString, this.savePath, fileName); } public void saveLiDARScanToFile(LidarScan scan, String fileName) { String result = this.getLidarScanAsSaveString(scan); saveStringToFile(result, this.savePath, fileName); } private String getLidarScanAsSaveString(LidarScan scan) { String distancesString = ""; if(scan.is2D()) { distancesString = java.util.Arrays.toString(scan.getScan2D().getDistances()); } else {
package io.github.mmm.measurement.device; public class DeviceController { private Boolean currentlyMeasuring; private int saveInterval; private String savePath; private boolean tickTimeWarning = false; private int tickTimeWarningTolerance; private LiDARController lidarController; private LiDAR lidar1; private LiDAR lidar2; private LiDAR lidar3; private IMUController imuController; private IMU imu1; public DeviceController() { System.out.println("Measure constructor"); this.currentlyMeasuring = false; } public Boolean isCurrentlyMeasuring() { return this.currentlyMeasuring; } public void startMeasure() { this.saveInterval = Config.SAVE_INTERVAL.get(); this.tickTimeWarning = Config.TICK_TIME_WARNING.get(); this.tickTimeWarningTolerance = Config.TICK_TIME_WARNING_TOLERANCE.get(); this.lidarController = new LiDARController(new LiDAR[]{lidar1, lidar2, lidar3}); this.imuController = new IMUController(imu1); String startTime = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").format(LocalDateTime.now()); this.savePath = "device_measurements/" + startTime; try { Files.createDirectories(Paths.get(MMM_ROOT_PATH + this.savePath)); } catch (Exception e) { System.out.println("Error creating directory: " + e.getMessage()); } if(Config.LIDAR1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar1.csv"); if(Config.LIDAR2_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar2.csv"); if(Config.LIDAR3_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar3.csv"); if(Config.IMU1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;accX;accY;accZ,gyroX;gyroY;gyroZ\n", this.savePath, "imu1.csv"); Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".measure.start"), false); this.currentlyMeasuring = true; } public void stopMeasure() { // save remaining scans ArrayList<LidarScan>[] scans = DEVICE_CONTROLLER.getLidarController().getScans(); for (int i = 0; i < scans.length; i++) { DEVICE_CONTROLLER.saveLiDARScansToFile(scans[i], "lidar" + (i + 1) + ".csv"); } DEVICE_CONTROLLER.getLidarController().clearScans(); ArrayList<ImuScan> imuScans = DEVICE_CONTROLLER.getImuController().getScans(); DEVICE_CONTROLLER.saveIMUScansToFile(imuScans, "imu1.csv"); // send stop message Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".measure.stop"), false); // reset this.currentlyMeasuring = false; this.lidarController = null; this.imuController = null; } public void initDevices() { this.initLidars(); this.initImus(); } private void initLidars() { LocalPlayer player = Minecraft.getInstance().player; ClientLevel level = Minecraft.getInstance().level; if (Config.LIDAR1_SWITCH.get()) { this.lidar1 = new LiDAR( (float)Config.LIDAR1_HORIZONTAL_SCANNING_RADIUS_IN_DEG.get(), (float)Config.LIDAR1_VERTICAL_SCANNING_RADIUS_IN_DEG.get(), Config.LIDAR1_HORIZONTAL_SCANS_PER_RADIUS.get(), Config.LIDAR1_VERTICAL_SCANS_PER_RADIUS.get(), (float)Config.LIDAR1_YAW_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR1_PITCH_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR1_ROLL_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR1_MAXIMUM_MEASUREMENT_DISTANCE.get(), Config.LIDAR1_MEASUREMENT_FREQUENCY_IN_HZ.get(), player, level, new Color(170, 0, 170) ); } else { this.lidar1 = null; } if (Config.LIDAR2_SWITCH.get()) { this.lidar2 = new LiDAR( (float)Config.LIDAR2_HORIZONTAL_SCANNING_RADIUS_IN_DEG.get(), (float)Config.LIDAR2_VERTICAL_SCANNING_RADIUS_IN_DEG.get(), Config.LIDAR2_HORIZONTAL_SCANS_PER_RADIUS.get(), Config.LIDAR2_VERTICAL_SCANS_PER_RADIUS.get(), (float)Config.LIDAR2_YAW_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR2_PITCH_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR2_ROLL_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR2_MAXIMUM_MEASUREMENT_DISTANCE.get(), Config.LIDAR2_MEASUREMENT_FREQUENCY_IN_HZ.get(), player, level, new Color(255, 170, 0) ); } else { this.lidar2 = null; } if (Config.LIDAR3_SWITCH.get()) { this.lidar3 = new LiDAR( (float)Config.LIDAR3_HORIZONTAL_SCANNING_RADIUS_IN_DEG.get(), (float)Config.LIDAR3_VERTICAL_SCANNING_RADIUS_IN_DEG.get(), Config.LIDAR3_HORIZONTAL_SCANS_PER_RADIUS.get(), Config.LIDAR3_VERTICAL_SCANS_PER_RADIUS.get(), (float)Config.LIDAR3_YAW_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR3_PITCH_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR3_ROLL_OFFSET_FROM_POV_IN_DEG.get(), (float)Config.LIDAR3_MAXIMUM_MEASUREMENT_DISTANCE.get(), Config.LIDAR3_MEASUREMENT_FREQUENCY_IN_HZ.get(), player, level, new Color(0, 170, 170) ); } else { this.lidar3 = null; } } private void initImus() { LocalPlayer player = Minecraft.getInstance().player; if (Config.IMU1_SWITCH.get()) { this.imu1 = new IMU( Config.IMU1_CONSIDER_GRAVITY.get(), Config.IMU1_YAW_OFFSET_FROM_POV_IN_DEG.get(), Config.IMU1_PITCH_OFFSET_FROM_POV_IN_DEG.get(), Config.IMU1_ROLL_OFFSET_FROM_POV_IN_DEG.get(), Config.IMU1_MEAUREMENT_FREQUENCY_IN_HZ.get(), player); } else { this.imu1 = null; } } public void saveLiDARScansToFile(ArrayList<LidarScan> scans, String fileName) { String scansAsString = ""; int nullCounter = 0; for(int i = 0; i < scans.size(); i++) { if(scans.get(i) == null) { nullCounter++; continue; } scansAsString += this.getLidarScanAsSaveString(scans.get(i)); } if (nullCounter == scans.size()) return; saveStringToFile(scansAsString, this.savePath, fileName); } public void saveLiDARScanToFile(LidarScan scan, String fileName) { String result = this.getLidarScanAsSaveString(scan); saveStringToFile(result, this.savePath, fileName); } private String getLidarScanAsSaveString(LidarScan scan) { String distancesString = ""; if(scan.is2D()) { distancesString = java.util.Arrays.toString(scan.getScan2D().getDistances()); } else {
LidarScan2D[] distances = scan.getScan3D().getDistances();
7
2023-11-06 16:56:46+00:00
24k
conductor-oss/conductor
core/src/main/java/com/netflix/conductor/core/execution/mapper/DecisionTaskMapper.java
[ { "identifier": "TaskType", "path": "common/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskType.java", "snippet": "@ProtoEnum\npublic enum TaskType {\n SIMPLE,\n DYNAMIC,\n FORK_JOIN,\n FORK_JOIN_DYNAMIC,\n DECISION,\n SWITCH,\n JOIN,\n DO_WHILE,\n SUB_WORKFLOW,...
import com.netflix.conductor.model.TaskModel; import com.netflix.conductor.model.WorkflowModel; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.script.ScriptException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.netflix.conductor.annotations.VisibleForTesting; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.core.events.ScriptEvaluator; import com.netflix.conductor.core.exception.TerminateWorkflowException;
20,379
/* * 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.execution.mapper; /** * An implementation of {@link TaskMapper} to map a {@link WorkflowTask} of type {@link * TaskType#DECISION} to a List {@link TaskModel} starting with Task of type {@link * TaskType#DECISION} which is marked as IN_PROGRESS, followed by the list of {@link TaskModel} * based on the case expression evaluation in the Decision task. * * @deprecated {@link com.netflix.conductor.core.execution.tasks.Decision} is also deprecated. Use * {@link com.netflix.conductor.core.execution.tasks.Switch} and so ${@link SwitchTaskMapper} * will be used as a result. */ @Deprecated @Component public class DecisionTaskMapper implements TaskMapper { private static final Logger LOGGER = LoggerFactory.getLogger(DecisionTaskMapper.class); @Override public String getTaskType() { return TaskType.DECISION.name(); } /** * This method gets the list of tasks that need to scheduled when the task to scheduled is of * type {@link TaskType#DECISION}. * * @param taskMapperContext: A wrapper class containing the {@link WorkflowTask}, {@link * WorkflowDef}, {@link WorkflowModel} and a string representation of the TaskId * @return List of tasks in the following order: * <ul> * <li>{@link TaskType#DECISION} with {@link TaskModel.Status#IN_PROGRESS} * <li>List of task based on the evaluation of {@link WorkflowTask#getCaseExpression()} * are scheduled. * <li>In case of no matching result after the evaluation of the {@link * WorkflowTask#getCaseExpression()}, the {@link WorkflowTask#getDefaultCase()} Tasks * are scheduled. * </ul> */ @Override
/* * 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.execution.mapper; /** * An implementation of {@link TaskMapper} to map a {@link WorkflowTask} of type {@link * TaskType#DECISION} to a List {@link TaskModel} starting with Task of type {@link * TaskType#DECISION} which is marked as IN_PROGRESS, followed by the list of {@link TaskModel} * based on the case expression evaluation in the Decision task. * * @deprecated {@link com.netflix.conductor.core.execution.tasks.Decision} is also deprecated. Use * {@link com.netflix.conductor.core.execution.tasks.Switch} and so ${@link SwitchTaskMapper} * will be used as a result. */ @Deprecated @Component public class DecisionTaskMapper implements TaskMapper { private static final Logger LOGGER = LoggerFactory.getLogger(DecisionTaskMapper.class); @Override public String getTaskType() { return TaskType.DECISION.name(); } /** * This method gets the list of tasks that need to scheduled when the task to scheduled is of * type {@link TaskType#DECISION}. * * @param taskMapperContext: A wrapper class containing the {@link WorkflowTask}, {@link * WorkflowDef}, {@link WorkflowModel} and a string representation of the TaskId * @return List of tasks in the following order: * <ul> * <li>{@link TaskType#DECISION} with {@link TaskModel.Status#IN_PROGRESS} * <li>List of task based on the evaluation of {@link WorkflowTask#getCaseExpression()} * are scheduled. * <li>In case of no matching result after the evaluation of the {@link * WorkflowTask#getCaseExpression()}, the {@link WorkflowTask#getDefaultCase()} Tasks * are scheduled. * </ul> */ @Override
public List<TaskModel> getMappedTasks(TaskMapperContext taskMapperContext) {
5
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;
16,322
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; RightClickFunctions.initializeTable(); textField0.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { // 当输入框内的文字是提示文字时,先清空输入框再允许输入 if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); } } }); // 设置背景色为 (4, 12, 31) textField0.setBackground(new Color(48, 49, 52)); // 设置光标 textField0.setCaret(new CustomCaret(Color.WHITE)); // 设置字体 Font font = new Font("Mono", Font.BOLD, 14); textField0.setFont(font); // fofaEX: FOFA Extension 事件 textField0.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { // 当输入框得到焦点时,如果当前是提示文字,则清空输入框并将文字颜色设置为白色 if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); textField0.setForeground(Color.WHITE); } } @Override public void focusLost(FocusEvent e) { // 当输入框失去焦点时,如果输入框为空,则显示提示文字,并将文字颜色设置为灰色 if (textField0.getText().isEmpty()) { textField0.setText("fofaEX: FOFA Extension"); textField0.setForeground(Color.GRAY); } } }); textField0.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); textField0.setForeground(Color.WHITE); } } }); textField0.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { textField0.setForeground(Color.WHITE); } @Override public void removeUpdate(DocumentEvent e) { if (textField0.getText().isEmpty()) { textField0.setForeground(Color.GRAY); } else { textField0.setForeground(Color.WHITE); } } @Override public void changedUpdate(DocumentEvent e) { // 平滑字体,无需处理 } }); // 将光标放在末尾 // textField0.setCaretPosition(textField0.getText().length()); // 编辑撤销 // 创建UndoManager和添加UndoableEditListener。 final UndoManager undoManager = new UndoManager(); Document doc = textField0.getDocument(); doc.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { undoManager.addEdit(e.getEdit()); } }); // 添加KeyListener到textField。 textField0.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if ((e.getKeyCode() == KeyEvent.VK_Z) && ((e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) != 0)) { if (undoManager.canUndo()) { undoManager.undo(); } } else { if ((e.getKeyCode() == KeyEvent.VK_Z)) { e.getModifiersEx(); } } } }); // String asciiIcon = // " __ __ _____ __ __\n" + // " / _| ___ / _| __ _ | ____| \\ \\/ /\n" + // " | |_ / _ \\ | |_ / _` | | _| \\ / \n" + // " | _| | (_) | | _| | (_| | | |___ / \\ \n" + // " |_| \\___/ |_| \\__,_| |_____| /_/\\_\\"; // // JLabel labelIcon = new JLabel("<html><pre>" + asciiIcon + "</pre></html>"); JLabel labelIcon = new JLabel(" FOFA EX"); labelIcon.setForeground(new Color(48, 49, 52)); Font iconFont = new Font("Times New Roman", Font.BOLD, 60); labelIcon.setFont(iconFont); // 创建按钮面板,不改变布局(保持BoxLayout) final JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); // 创建主面板并使用BoxLayout布局 JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); // 创建一个子面板,用来在搜索框边上新增按钮 JPanel subPanel1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10)); // 创建面板并使用FlowLayout布局 JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 4)); // hgap: 组件间的水平间距 vgap: 件间的垂直间距 JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); JPanel panel3 = new JPanel(new GridLayout(0, 10, 0, 0)); JPanel panel4 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10)); // 创建面板并使用GridLayout布局 JPanel panel5 = new JPanel(new GridLayout(0, 5, 10, 10)); // 0表示行数不限,5表示每行最多5个组件,10, 10是组件之间的间距 JPanel panel6 = new JPanel(new BorderLayout()); panel6.setBorder(BorderFactory.createEmptyBorder(20, 5, 10, 5)); JPanel panel7 = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); // panel8 用来放导出表格的按键 JPanel panel8 = new JPanel(); JPanel panel9 = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0)); // 创建"更新规则"按钮 创建"新增"按钮 JButton updateButton = new JButton("➕"); updateButton.setFocusPainted(false); updateButton.setFocusable(false); // 新增一个LinkedHashMap,用于存储按钮的键名和键值 Map<String, JButton> buttonsMap = new LinkedHashMap<>(); BufferedReader rulesReader = null; File accountsFile = null; try { // 创建 rules.txt 文件如果它不存在 File rulesFile = new File(rulesPath); if (!rulesFile.exists()) { rulesFile.createNewFile(); System.out.println("[+] The current path does not contain " + rulesPath + ". Create "+ rulesPath +"."); } rulesReader = new BufferedReader(new FileReader(rulesFile)); // 创建 accounts.txt 文件如果它不存在 accountsFile = new File(accountsPath); if (!accountsFile.exists()) { accountsFile.createNewFile(); System.out.println("[+] The current path does not contain " + accountsPath + ". Create " + accountsPath + "."); } } catch (IOException e) { // IO 异常处理 e.printStackTrace(); } settingInit(rulesReader, accountsFile, panel5, textField0, fofaEmail, fofaKey, buttonsMap); updateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 创建一个JPanel来包含两个输入框 JPanel inputPanel = new JPanel(new GridLayout(4, 4)); inputPanel.add(new JLabel("键名:")); JTextField nameField = new JTextField(10); inputPanel.add(nameField); inputPanel.add(new JLabel("键值:")); JTextField valueField = new JTextField(10); inputPanel.add(valueField); // 弹出自定义对话框 int result = JOptionPane.showConfirmDialog(null, inputPanel, "新增按键", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); // 当用户点击OK时处理输入 if (result == JOptionPane.OK_OPTION) { String keyName = nameField.getText().trim(); String keyValue = valueField.getText().trim(); // 验证输入是否非空 if (!keyName.isEmpty() && !keyValue.isEmpty()) { // 将键名和键值以"键名":{键值}的形式保存在rule.txt的最后一行 try (BufferedWriter writer = new BufferedWriter(new FileWriter(rulesPath, true))) { System.out.println(keyValue); writer.write("\"" + keyName + "\":{" + keyValue + "},"); writer.newLine(); // Ensure the new entry is on a new line } catch (IOException addError) { addError.printStackTrace(); JOptionPane.showMessageDialog(null, "无法写入文件", "错误", JOptionPane.ERROR_MESSAGE); } // 添加右键菜单功能 try { BufferedReader reader = new BufferedReader(new FileReader(rulesPath)); Map<String, String> newMap = new LinkedHashMap<>(); String line; while ((line = reader.readLine()) != null) { line = line.trim(); // 跳过井号注释 if (line.startsWith("#")) { continue; } if (line.startsWith("\"") && line.contains("{") && line.contains("}")) { String[] parts = line.split(":", 2); String key = parts[0].substring(1, parts[0].length() - 1).trim(); String value = parts[1].substring(1, parts[1].length() - 2).trim(); newMap.put(key, value); } } reader.close(); // 配置文件更新并新增按钮 for (Map.Entry<String, String> entry : newMap.entrySet()) { JButton existingButton = buttonsMap.get(entry.getKey()); if (existingButton == null) { // 新按钮 JButton newButton = new JButton(entry.getKey()); newButton.setActionCommand(entry.getValue()); newButton.setToolTipText(entry.getValue()); // 设置按钮的 ToolTip 为键值,悬浮显示 newButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 newButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态 newButton.addActionListener(actionEvent -> { if (newButton.getForeground() != Color.RED) { // 如果文本为提示文字,则清空文本 if (textField0.getText().contains("fofaEX: FOFA Extension")) { textField0.setText(""); } textField0.setText(textField0.getText() + " " + newButton.getActionCommand()); newButton.setForeground(Color.RED); newButton.setFont(newButton.getFont().deriveFont(Font.BOLD)); // 设置字体为粗体 } else { textField0.setText(textField0.getText().replace(" " + newButton.getActionCommand(), "")); newButton.setForeground(null); newButton.setFont(null); // 如果为空则设置 prompt if (textField0.getText().isEmpty()) { textField0.setText("fofaEX: FOFA Extension"); textField0.setForeground(Color.GRAY); // 将光标放在开头 textField0.setCaretPosition(0); } } }); // 添加右键单击事件的处理 newButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { // 在这里处理右键单击事件 JPopupMenu popupMenu = new JPopupMenu(); JMenuItem deleteItem = new JMenuItem("删除"); JMenuItem editItem = new JMenuItem("修改"); deleteItem.addActionListener(actionEvent -> { // 删除:在这里处理删除操作 int dialogResult = JOptionPane.showConfirmDialog(panel5, "是否删除?", "删除确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (dialogResult == JOptionPane.YES_OPTION) { // 确认删除操作 panel5.remove(newButton); panel5.revalidate(); panel5.repaint(); // 从文件中删除 removeButtonAndLineFromFile(entry.getKey(), rulesPath); } }); editItem.addActionListener(actionEvent -> { // 获取当前按钮的名称和对应的JButton对象 String oldName = entry.getKey(); JButton buttonToUpdate = newButton; // 确保newButton是当前要修改的按钮的引用 // 创建一个JPanel来包含两个输入框 JPanel panel = new JPanel(new GridLayout(4, 4)); panel.add(new JLabel("键名:")); JTextField nameField = new JTextField(newButton.getText()); panel.add(nameField); panel.add(new JLabel("键值:")); JTextField valueField = new JTextField(buttonToUpdate.getActionCommand()); panel.add(valueField); // 弹出自定义对话框 int result = JOptionPane.showConfirmDialog(panel5, panel, "修改配置", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); // 当用户点击OK时处理输入 if (result == JOptionPane.OK_OPTION) { String newName = nameField.getText().trim(); String newValue = valueField.getText().trim(); // 验证输入是否已变更且非空 if (!newName.isEmpty() && !newValue.isEmpty()) { // 修改按钮名称和键值 updateButtonNameAndValue(oldName, newName, newValue, buttonToUpdate, buttonsMap, rulesPath); // 更新界面 panel5.revalidate(); panel5.repaint(); } } }); popupMenu.add(editItem); popupMenu.add(deleteItem); popupMenu.show(e.getComponent(), e.getX(), e.getY()); popupMenu.add(deleteItem); popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); panel5.add(newButton); buttonsMap.put(entry.getKey(), newButton); } else { // This is an existing button existingButton.setActionCommand(entry.getValue()); existingButton.setText(entry.getKey()); // Update button text } } panel5.revalidate(); panel5.repaint(); } catch (IOException ioException) { ioException.printStackTrace(); } // 更新界面 panel5.revalidate(); panel5.repaint(); } } // 读取文件内容,并创建新的按钮 } }); // 搜索按钮 // 将textField0添加到新的SubPanel subPanel1.add(textField0); searchButton("搜索", true, subPanel1, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "null"); panel1.add(labelIcon); panel2.add(subPanel1); // 搜索框 + 搜索按钮 JLabel jLabel7 = new JLabel("total lines "); panel7.add(jLabel7); searchButton("◁", false, panel7, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "left"); searchButton("▷", false, panel7, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "right"); // 添加逻辑运算组件 createLogicAddButton("=", "=", panel4, textField0); createLogicAddButton("==", "==", panel4, textField0); createLogicAddButton("&&", "&&", panel4, textField0); createLogicAddButton("||", "||", panel4, textField0); createLogicAddButton("!=", "!=", panel4, textField0); createLogicAddButton("*=", "*=", panel4, textField0); // 新增折叠按钮到panel3 JButton foldButton = new JButton("▼"); foldButton.setFocusPainted(false); //添加这一行来取消焦点边框的绘制 foldButton.setFocusable(false); // 添加点击事件 foldButton.addActionListener(new ActionListener() { boolean isFolded = false; @Override public void actionPerformed(ActionEvent actionEvent) { if (!isFolded) { // 折叠 panel5 panel5.setVisible(false); foldButton.setText("◀"); scrollPaneMark = false; } else { // 展开 panel5 panel5.setVisible(true); foldButton.setText("▼"); scrollPaneMark = true; } isFolded = !isFolded; // 重新验证和重绘包含 panel5 和 panel6 的主面板 mainPanel.revalidate(); mainPanel.repaint(); } }); panel4.add(updateButton); // 更新规则 panel4.add(foldButton); // 创建复选框 addRuleBox(panel3, "host", newValue -> hostMark = newValue, hostMark, true); addRuleBox(panel3, "ip", newValue -> ipMark = newValue, ipMark, true); addRuleBox(panel3, "port", newValue -> portMark = newValue, portMark, true); addRuleBox(panel3, "protocol", newValue -> protocolMark = newValue, protocolMark); addRuleBox(panel3, "title", newValue -> titleMark = newValue, titleMark); addRuleBox(panel3, "domain", newValue -> domainMark = newValue, domainMark); addRuleBox(panel3, "link", newValue -> linkMark = newValue, linkMark); addRuleBox(panel3, "icp", newValue -> icpMark = newValue, icpMark); addRuleBox(panel3, "city", newValue -> cityMark = newValue, cityMark); /* 下面代码未完成 */ addRuleBox(panel3, "country", newValue -> countryMark = newValue, countryMark); /* 测试一下 */ addRuleBox(panel3, "country_name", newValue -> country_nameMark = newValue, country_nameMark); addRuleBox(panel3, "region", newValue -> regionMark = newValue, regionMark); addRuleBox(panel3, "longitude", newValue -> longitudeMark = newValue, longitudeMark); addRuleBox(panel3, "latitude", newValue -> latitudeMark = newValue, latitudeMark); addRuleBox(panel3, "asNumber", newValue -> asNumberMark = newValue, asNumberMark); addRuleBox(panel3, "asOrganization", newValue -> asOrganizationMark = newValue, asOrganizationMark); addRuleBox(panel3, "os", newValue -> osMark = newValue, osMark); addRuleBox(panel3, "server", newValue -> serverMark = newValue, serverMark); addRuleBox(panel3, "jarm", newValue -> jarmMark = newValue, jarmMark); addRuleBox(panel3, "header", newValue -> headerMark = newValue, headerMark); addRuleBox(panel3, "banner", newValue -> bannerMark = newValue, bannerMark); addRuleBox(panel3, "baseProtocol", newValue -> baseProtocolMark = newValue, baseProtocolMark); addRuleBox(panel3, "certsIssuerOrg", newValue -> certsIssuerOrgMark = newValue, certsIssuerOrgMark); addRuleBox(panel3, "certsIssuerCn", newValue -> certsIssuerCnMark = newValue, certsIssuerCnMark); addRuleBox(panel3, "certsSubjectOrg", newValue -> certsSubjectOrgMark = newValue, certsSubjectOrgMark); addRuleBox(panel3, "certsSubjectCn", newValue -> certsSubjectCnMark = newValue, certsSubjectCnMark); addRuleBox(panel3, "tlsJa3s", newValue -> tlsJa3sMark = newValue, tlsJa3sMark); addRuleBox(panel3, "tlsVersion", newValue -> tlsVersionMark = newValue, tlsVersionMark); addRuleBox(panel3, "product", newValue -> productMark = newValue, productMark); addRuleBox(panel3, "productCategory", newValue -> productCategoryMark = newValue, productCategoryMark); addRuleBox(panel3, "version", newValue -> versionMark = newValue, versionMark); addRuleBox(panel3, "lastupdatetime", newValue -> lastupdatetimeMark = newValue, lastupdatetimeMark); addRuleBox(panel3, "cname", newValue -> cnameMark = newValue, cnameMark); addRuleBox(panel3, "iconHash", newValue -> iconHashMark = newValue, iconHashMark); addRuleBox(panel3, "certsValid", newValue -> certsValidMark = newValue, certsValidMark); addRuleBox(panel3, "cnameDomain", newValue -> cnameDomainMark = newValue, cnameDomainMark); addRuleBox(panel3, "body", newValue -> bodyMark = newValue, bodyMark); addRuleBox(panel3, "icon", newValue -> iconMark = newValue, iconMark); addRuleBox(panel3, "fid", newValue -> fidMark = newValue, fidMark); addRuleBox(panel3, "structinfo", newValue -> structinfoMark = newValue, structinfoMark); // 设置全局边框:创建一个带有指定的空白边框的新面板,其中指定了上、左、下、右的边距 mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 添加面板到主面板 mainPanel.add(panel1); mainPanel.add(panel2); mainPanel.add(panel3); mainPanel.add(panel4); mainPanel.add(panel5); mainPanel.add(panel6); mainPanel.add(panel7); mainPanel.add(panel8); mainPanel.add(panel9); tabbedPane0.addTab("FofaEX", mainPanel); tabbedPane0.setTabPlacement(JTabbedPane.BOTTOM); // 将标签放置在底部 // fofa 插件初始化 FofaHack.panel = panel6; FofaHack.table = table; FofaHack.exportPanel = panel8; FofaHack.exportButtonAdded = false; FofaHack.rowCountLabel = jLabel7; // 设置窗口居中并显示 jFrame.setLocationRelativeTo(null); jFrame.add(tabbedPane0); ; jFrame.setVisible(true); // 在程序运行时,使 textField0 获得焦点 SwingUtilities.invokeLater(new Runnable() { public void run() { textField0.requestFocusInWindow(); } }); // 更改"账户设置"菜单项的事件监听 changePasswordMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 创建新的JFrame JFrame settingsFrame = new JFrame("Settings"); // 创建新的面板并添加组件 JPanel settingsPanel = new JPanel(new GridLayout(4, 2, 5, 5)); // 使用4行2列的GridLayout settingsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 设置边距 JButton checkButton = new JButton("检查账户"); checkButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 checkButton.setFocusable(false); checkButton.addActionListener(e1 -> { // 点击按钮时显示输入的数据 String email = fofaEmail.getText(); String key = fofaKey.getText(); String fofaUrl_str = fofaUrl.getText(); // https://fofa.info/api/v1/info/my?email= String authUrl = fofaUrl_str + "/api/v1/info/my?email=" + email + "&key=" + key; HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(authUrl); try { HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); // 解析JSON数据 JSONObject json = new JSONObject(responseBody); if (!json.getBoolean("error")) { // 账户验证有效 StringBuilder output = new StringBuilder(); output.append("账户验证有效\n"); output.append("邮箱地址: ").append(json.getString("email")).append("\n"); output.append("用户名: ").append(json.getString("username")).append("\n"); if (json.getBoolean("isvip")) { output.append("身份权限:FOFA会员\n"); } else { output.append("身份权限:普通用户\n"); } ; output.append("F点数量: ").append(json.getInt("fofa_point")).append("\n"); output.append("API月度剩余查询次数: ").append(json.getInt("remain_api_query")).append("\n"); output.append("API月度剩余返回数量: ").append(json.getInt("remain_api_data")).append("\n"); JOptionPane.showMessageDialog(null, output.toString()); } else { // 账户验证无效 JOptionPane.showMessageDialog(null, "账户验证无效!", "提示", JOptionPane.WARNING_MESSAGE); } } catch (IOException | JSONException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "发生错误,请重试!", "错误", JOptionPane.ERROR_MESSAGE); } }); // 创建"保存设置"按钮 JButton saveSettingsButton = new JButton("保存设置"); saveSettingsButton.setFocusPainted(false); // 取消焦点边框的绘制 saveSettingsButton.setFocusable(false); saveSettingsButton.addActionListener(SaveError -> { // 准备一个 JsonObject JsonObject jsonObject = new JsonObject(); File jsonFile = new File(accountsPath); // 如果文件存在且其内容不为空,从中读取 JsonObject if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { // parse error handling ex.printStackTrace(); } } // 更新邮件和密钥设置 jsonObject.addProperty("fofaEmail", fofaEmail.getText()); jsonObject.addProperty("fofaKey", fofaKey.getText()); // 将已更新的 jsonObject 写回到 "accounts.json" 文件 try (FileWriter writer = new FileWriter(accountsPath)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); JOptionPane.showMessageDialog(null, "设置已保存。"); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "保存设置时发生错误!", "错误", JOptionPane.ERROR_MESSAGE); } }); // 添加组件到设置面板 settingsPanel.add(new JLabel("FOFA URL:")); settingsPanel.add(fofaUrl); settingsPanel.add(new JLabel("Email:")); settingsPanel.add(fofaEmail); settingsPanel.add(new JLabel("API Key:")); settingsPanel.add(fofaKey); settingsPanel.add(checkButton); settingsPanel.add(saveSettingsButton); // 添加设置面板到设置窗口,并显示设置窗口 settingsFrame.add(settingsPanel); settingsFrame.pack(); settingsFrame.setLocationRelativeTo(null); // 使窗口居中显示 settingsFrame.setResizable(false); settingsFrame.setVisible(true); } }); configureMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JTextField inputField = new JTextField(String.valueOf(sizeSetting)); JButton okButton = new JButton("保存"); JButton cancelButton = new JButton("取消"); JOptionPane optionPane = new JOptionPane(inputField, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); optionPane.setOptions(new Object[] { okButton, cancelButton }); JDialog dialog = optionPane.createDialog("请输入默认查询数量"); okButton.addActionListener(ev -> { try { sizeSetting = Integer.parseInt(inputField.getText()); // 读取JSON文件 JsonObject jsonObject; File jsonFile = new File(accountsPath); if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { ex.printStackTrace(); return; } } else { jsonObject = new JsonObject(); } // 更新queryNumber并重新写入文件 jsonObject.addProperty("queryNumber", sizeSetting); try (FileWriter writer = new FileWriter(accountsPath)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); } // 显示保存成功提醒 JOptionPane.showMessageDialog(null, "保存成功!"); // 关闭原始对话框 dialog.dispose(); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "请输入一个有效的整数值。"); } catch (IOException ex) { // 处理文件读写异常 JOptionPane.showMessageDialog(null, "发生错误,账户配置文件不存在。"); } }); cancelButton.addActionListener(ev -> dialog.dispose()); dialog.setVisible(true); } }); configureFullItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JsonObject jsonObject; File jsonFile = new File("accounts.json"); // 如果文件存在且其内容不为空,从中读取 JsonObject if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { // 解析错误处理 ex.printStackTrace(); return; } } else { jsonObject = new JsonObject(); } // 读取 queryFull 的值,并设置复选框的选择状态 if (jsonObject.has("queryFull")) { defaultCheckFullBox.setSelected(!jsonObject.get("queryFull").getAsBoolean()); } JButton okButton = new JButton("保存"); JButton cancelButton = new JButton("取消"); JOptionPane optionPane = new JOptionPane(defaultCheckFullBox, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); optionPane.setOptions(new Object[]{okButton, cancelButton}); JDialog dialog = optionPane.createDialog("是否默认查询区间"); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); okButton.addActionListener(ev -> { // 如果复选框选中,则设置 queryFull 为 false,否则为 true boolean queryFull = !defaultCheckFullBox.isSelected(); jsonObject.addProperty("queryFull", queryFull); // 更新 setFull 的值 setFull = queryFull; // 将 jsonObject 保存到 "accounts.json" 文件中 try (FileWriter writer = new FileWriter(jsonFile)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); JOptionPane.showMessageDialog(null, "保存成功!"); dialog.dispose(); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "发生错误,保存设置失败。"); } }); cancelButton.addActionListener(ev -> dialog.dispose()); dialog.setVisible(true); } }); // 图标哈希计算事件 iconHashLabMenuItem.addActionListener((ActionEvent event) -> { EventQueue.invokeLater(() -> { IconHashCalculator calculator = new IconHashCalculator(); calculator.setVisible(true); }); }); fofaHackMenuItemRun.addActionListener((ActionEvent event) -> { EventQueue.invokeLater(() -> { FofaHack.main(); }); }); openFileMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); // 如果存在上次打开的路径,则设置文件选择器的当前目录 if (lastOpenedPath != null) { fileChooser.setCurrentDirectory(lastOpenedPath); } if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); // 更新 lastOpenedPath 为当前选择的文件或文件夹 lastOpenedPath = fileChooser.getCurrentDirectory(); // 调用方法来处理文件 FofaHack.loadFileIntoTable(file); } } }); // 焦点测试 点击事件:显示当前标签 focusTestItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CommonTemplate.localCurrentTab(tabbedPane0); // CommonTemplate.switchTab(tabbedPane0,tabName); } }); switchToHttpxItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { switchTab(tabbedPane0, "httpx"); } }); // 为"关于项目"菜单项添加动作监听器 aboutMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JEditorPane editorPane = new JEditorPane("text/html", ""); editorPane.setText( "<html><body>" + "<b>fofa EX:</b><br>" + "Project: <a href='https://github.com/10cks/fofaEX'>https://github.com/10cks/fofaEX</a><br>" + "Author: bwner@OverSpace<br>" + "Version: 2.2<br>" + "JDK Version: 11.0.5<br>" + "Update: 2023.12.11<br>" + "</body></html>" ); editorPane.setEditable(false); editorPane.setOpaque(false); editorPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent evt) { if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { Desktop.getDesktop().browse(evt.getURL().toURI()); } catch (IOException | URISyntaxException ex) { JOptionPane.showMessageDialog(null, "无法打开链接,错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } }); // 弹出一个包含JEditorPane的消息对话框 JOptionPane.showMessageDialog(null, new JScrollPane(editorPane), "关于项目", JOptionPane.PLAIN_MESSAGE); } }); // 为 "fofahack 设置" 添加动作监听器 fofaHackMenuItemSetting.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 检查文件是否存在 File fofaHackSettingsFile = new File(".\\plugins\\fofahack\\FofaHackSetting.txt"); if (fofaHackSettingsFile.exists()) { // 如果文件存在,使用系统默认编辑器打开它 try { Desktop.getDesktop().edit(fofaHackSettingsFile); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "无法打开配置文件!", "错误", JOptionPane.ERROR_MESSAGE); } } else { // 如果文件不存在,显示弹窗 JOptionPane.showMessageDialog(null, "未获取到配置文件!", "错误", JOptionPane.ERROR_MESSAGE); } } }); // 为" fofahack 关于项目"菜单项添加动作监听器 fofaHackMenuItemAbout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JEditorPane editorPane = new JEditorPane("text/html", ""); editorPane.setText( "<html><body>" + "<b>fofa-hack:</b><br>" + "Project: <a href='https://github.com/Cl0udG0d/Fofa-hack'>https://github.com/Cl0udG0d/Fofa-hack</a><br>" + "Author: Cl0udG0d<br>" + "version: 当前使用为修改版<br>" + "</body></html>" ); editorPane.setEditable(false); editorPane.setOpaque(false); editorPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent evt) { if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { Desktop.getDesktop().browse(evt.getURL().toURI()); } catch (IOException | URISyntaxException ex) { JOptionPane.showMessageDialog(null, "无法打开链接,错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } }); // 弹出一个包含JEditorPane的消息对话框 JOptionPane.showMessageDialog(null, new JScrollPane(editorPane), "关于项目", JOptionPane.PLAIN_MESSAGE); } }); } private static JTextField createTextField(String text) { JTextField textField = new JTextField(text, 20); textField.setPreferredSize(new Dimension(200, 20)); // 创建只有底边的边框 Border blueBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.RED); Border defaultBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY); // 设置默认边框 textField.setBorder(defaultBorder); // 添加鼠标监听器 textField.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { // 鼠标进入时,设置边框颜色为蓝色 textField.setBorder(blueBorder); } @Override public void mouseExited(MouseEvent e) { // 鼠标离开时,将边框颜色设回默认颜色 textField.setBorder(defaultBorder); } }); return textField; } private static JTextField createTextFieldFofa(String text) { RoundJTextField textField = new RoundJTextField(0); textField.setText(text); textField.setPreferredSize(new Dimension(800, 50)); // 设置文本与边框的间距 textField.setMargin(new Insets(0, 10, 0, 5)); // 创建只有底边的边框 Border blueBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.RED); Border defaultBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY); // 设置默认边框 // textField.setBorder(defaultBorder); return textField; } private static void createLogicAddButton(String buttonText, String appendText, JPanel panel, JTextField textField) { // 创建按钮 JButton button = new JButton(buttonText); button.setFocusPainted(false); // 不显示按钮焦点外边框 button.setFocusable(false); // 禁止按钮获取焦点 // 添加点击事件 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (textField.getText().contains("fofaEX: FOFA Extension")) { textField.setText(""); } // 追加指定文本到文本框中 textField.setText(textField.getText() + " " + appendText); } }); // 将按钮添加到指定面板中 panel.add(button); } private static void searchButton(String buttonText, boolean shouldSetSize, JPanel panel, JTextField textField, JTextField emailField, JTextField keyField, JTextField urlField, JPanel resultPanel, JPanel exportPanel, JLabel changeIcon, JPanel disablePanel2, JPanel disablePanel3, JPanel disablePanel7, JPanel totalPanel8, String pageButton) { JButton button = new JButton(buttonText); button.setFocusPainted(false); button.setFocusable(false); if (shouldSetSize) { button.setPreferredSize(new Dimension(60, 50)); } button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { String domain = urlField.getText().trim(); String email = emailField.getText().trim(); String key = keyField.getText().trim(); String grammar = textField.getText().trim(); String orginIconStr = changeIcon.getText(); // String searchAsciiIcon = " ____ _ _ \n" + // " / ___| ___ __ _ _ __ ___ | |__ (_) _ __ __ _ \n" + // " \\___ \\ / _ \\ / _` | | '__| / __| | '_ \\ | | | '_ \\ / _` | \n" + // " ___) | | __/ | (_| | | | | (__ | | | | | | | | | | | (_| | \n" + // " |____/ \\___| \\__,_| |_| \\___| |_| |_| |_| |_| |_| \\__, | \n" ; // // // changeIcon.setText("<html><pre>" + searchAsciiIcon + "</pre></html>"); changeIcon.setText(" FOFA EX"); changeIcon.setForeground(new Color(89, 154, 248)); // 设置文本颜色为红色 Font font = new Font("Times New Roman", Font.BOLD, 60); changeIcon.setFont(font); setComponentsEnabled(disablePanel2, false); setComponentsEnabled(disablePanel3, false); setComponentsEnabled(disablePanel7, false); // 创建 SwingWorker 来处理搜索任务 SwingWorker<SearchResults, Void> worker = new SwingWorker<SearchResults, Void>() { private void fontSet(JLabel changeIcon, String originIconStr) { changeIcon.setText(originIconStr); changeIcon.setForeground(new Color(48, 49, 52)); } @Override protected SearchResults doInBackground() throws Exception { SearchResults results = new SearchResults(); QueryResponse queryResponse = new QueryResponse(); String errorMessage = null; // 用于存储错误消息 errorMessage = queryResponse.errmsg; // 存储错误消息以便后面使用 String fieldsTotal = ""; long startTime = System.nanoTime(); try { String query = grammar; if (query.equals("fofaEX: FOFA Extension")) { query = ""; // 将字符串设置为空 } if (protocolMark) { fieldsTotal += ",protocol"; } if (titleMark) { fieldsTotal += ",title"; } if (domainMark) { fieldsTotal += ",domain"; } if (linkMark) { fieldsTotal += ",link"; } if (icpMark) { fieldsTotal += ",icp"; } if (cityMark) { fieldsTotal += ",city"; } if (countryMark) { fieldsTotal += ",country"; } if (country_nameMark) { fieldsTotal += ",country_name"; } if (regionMark) { fieldsTotal += ",region"; } if (longitudeMark) { fieldsTotal += ",longitude"; } if (latitudeMark) { fieldsTotal += ",latitude"; } if (asNumberMark) { fieldsTotal += ",as_number"; } if (asOrganizationMark) { fieldsTotal += ",as_organization"; } if (osMark) { fieldsTotal += ",os"; } if (serverMark) { fieldsTotal += ",server"; } if (jarmMark) { fieldsTotal += ",jarm"; } if (headerMark) { fieldsTotal += ",header"; } if (bannerMark) { fieldsTotal += ",banner"; } if (baseProtocolMark) { fieldsTotal += ",base_protocol"; } if (certsIssuerOrgMark) { fieldsTotal += ",certs_issuer_org"; } if (certsIssuerCnMark) { fieldsTotal += ",certs_issuer_cn"; } if (certsSubjectOrgMark) { fieldsTotal += ",certs_subject_org"; } if (certsSubjectCnMark) { fieldsTotal += ",certs_subject_cn"; } if (tlsJa3sMark) { fieldsTotal += ",tls_ja3s"; } if (tlsVersionMark) { fieldsTotal += ",tls_version"; } if (productMark) { fieldsTotal += ",product"; } if (productCategoryMark) { fieldsTotal += ",product_category"; } if (versionMark) { fieldsTotal += ",version"; } if (lastupdatetimeMark) { fieldsTotal += ",lastupdatetime"; } if (cnameMark) { fieldsTotal += ",cname"; } if (iconHashMark) { fieldsTotal += ",icon_hash"; } if (certsValidMark) { fieldsTotal += ",certs_valid"; } if (cnameDomainMark) { fieldsTotal += ",cname_domain"; } if (bodyMark) { fieldsTotal += ",body"; } if (iconMark) { fieldsTotal += ",icon"; } if (fidMark) { fieldsTotal += ",fid"; } if (structinfoMark) { fieldsTotal += ",structinfo"; } // 创建字典 Map<String, Boolean> marks = new LinkedHashMap<>(); marks.put("host", ipMark); marks.put("ip", ipMark); marks.put("port", portMark); marks.put("protocol", protocolMark); marks.put("title", titleMark); marks.put("domain", domainMark); marks.put("link", linkMark); marks.put("icp", icpMark); marks.put("city", cityMark); marks.put("country", countryMark); marks.put("country_name", country_nameMark); marks.put("region", regionMark); marks.put("longitude", longitudeMark); marks.put("latitude", latitudeMark); marks.put("asNumber", asNumberMark); marks.put("asOrganization", asOrganizationMark); marks.put("os", osMark); marks.put("server", serverMark); marks.put("jarm", jarmMark); marks.put("header", headerMark); marks.put("banner", bannerMark); marks.put("baseProtocol", baseProtocolMark); marks.put("certsIssuerOrg", certsIssuerOrgMark); marks.put("certsIssuerCn", certsIssuerCnMark); marks.put("certsSubjectOrg", certsSubjectOrgMark); marks.put("certsSubjectCn", certsSubjectCnMark); marks.put("tlsJa3s", tlsJa3sMark); marks.put("tlsVersion", tlsVersionMark); marks.put("product", productMark); marks.put("productCategory", productCategoryMark); marks.put("version", versionMark); marks.put("lastupdatetime", lastupdatetimeMark); marks.put("cname", cnameMark); marks.put("iconHash", iconHashMark); marks.put("certsValid", certsValidMark); marks.put("cnameDomain", cnameDomainMark); marks.put("body", bodyMark); marks.put("icon", iconMark); marks.put("fid", fidMark); marks.put("structinfo", structinfoMark); // 标记为真的放在一起 List<String> trueMarks = extractTrueMarks(marks); System.out.println(trueMarks); if (pageButton.equals("left")) { if (currentPage != 0) { currentPage = currentPage - 1; } else { } currentPage = 1; } else if (pageButton.equals("right")) { currentPage = currentPage + 1; } // 开始查询 JSONObject jsonResponse = FofaAPI.getAllJsonResult(domain, email, key, query, fieldsTotal, sizeSetting, currentPage, setFull); // 检查错误信息 queryResponse.error = (boolean) FofaAPI.getValueFromJson(jsonResponse, "error"); queryResponse.errmsg = (String) FofaAPI.getValueFromJson(jsonResponse, "errmsg"); // 取出整体 results queryResponse.results = (List<List<String>>) FofaAPI.getValueFromJson(jsonResponse, "results"); if (queryResponse.error) { throw new Exception(queryResponse.errmsg); } List<List<String>> allShow = queryResponse.results; // 需要放在异常后面 // currentPage = (int) FofaAPI.getValueFromJson(jsonResponse, "page"); queryTotalNumber = (int) FofaAPI.getValueFromJson(jsonResponse, "size"); List<String> hostShow = FofaAPI.getColumn(allShow, 0); numberOfItems = hostShow.size(); int i = 0; for (String mark : trueMarks) { switch (mark) { case "host": results.host = FofaAPI.getColumn(allShow, i); break; case "ip": results.ip = FofaAPI.getColumn(allShow, i); break; case "protocol": results.protocol = FofaAPI.getColumn(allShow, i); break; case "port": results.port = FofaAPI.getColumn(allShow, i); break; case "title": results.title = decodeHtmlEntities(FofaAPI.getColumn(allShow, i)); break; case "domain": results.domain = FofaAPI.getColumn(allShow, i); break; case "link": results.link = FofaAPI.getColumn(allShow, i); break; case "icp": results.icp = FofaAPI.getColumn(allShow, i); break; case "city": results.city = FofaAPI.getColumn(allShow, i); break; case "country": results.country = FofaAPI.getColumn(allShow, i); break; case "country_name": results.country_name = FofaAPI.getColumn(allShow, i); break; case "region": results.region = FofaAPI.getColumn(allShow, i); break; case "longitude": results.longitude = FofaAPI.getColumn(allShow, i); break; case "latitude": results.latitude = FofaAPI.getColumn(allShow, i); break; case "asNumber": results.asNumber = FofaAPI.getColumn(allShow, i); break; case "asOrganization": results.asOrganization = FofaAPI.getColumn(allShow, i); break; case "os": results.os = FofaAPI.getColumn(allShow, i); break; case "server": results.server = FofaAPI.getColumn(allShow, i); break; case "jarm": results.jarm = FofaAPI.getColumn(allShow, i); break; case "header": results.header = FofaAPI.getColumn(allShow, i); break; case "banner": results.banner = FofaAPI.getColumn(allShow, i); break; case "baseProtocol": results.baseProtocol = FofaAPI.getColumn(allShow, i); break; case "certsIssuerOrg": results.certsIssuerOrg = FofaAPI.getColumn(allShow, i); break; case "certsIssuerCn": results.certsIssuerCn = FofaAPI.getColumn(allShow, i); break; case "certsSubjectOrg": results.certsSubjectOrg = FofaAPI.getColumn(allShow, i); break; case "certsSubjectCn": results.certsSubjectCn = FofaAPI.getColumn(allShow, i); break; case "tlsJa3s": results.tlsJa3s = FofaAPI.getColumn(allShow, i); break; case "tlsVersion": results.tlsVersion = FofaAPI.getColumn(allShow, i); break; case "product": results.product = FofaAPI.getColumn(allShow, i); break; case "productCategory": results.productCategory = FofaAPI.getColumn(allShow, i); break; case "version": results.version = FofaAPI.getColumn(allShow, i); break; case "lastupdatetime": results.lastupdatetime = FofaAPI.getColumn(allShow, i); break; case "cname": results.cname = FofaAPI.getColumn(allShow, i); break; case "iconHash": results.iconHash = FofaAPI.getColumn(allShow, i); break; case "certsValid": results.certsValid = FofaAPI.getColumn(allShow, i); break; case "cnameDomain": results.cnameDomain = FofaAPI.getColumn(allShow, i); break; case "body": results.body = FofaAPI.getColumn(allShow, i); break; case "icon": results.icon = FofaAPI.getColumn(allShow, i); break; case "fid": results.fid = FofaAPI.getColumn(allShow, i); break; case "structinfo": results.structinfo = FofaAPI.getColumn(allShow, i); break; } i = i + 1; } // 导出表格 JButton exportButton = new JButton("Export to Excel"); exportButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 exportButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态 if (!exportButtonAdded) { exportPanel.add(exportButton); exportButtonAdded = true; } exportButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 在这里检查 table 是否被初始化 if (table == null) { JOptionPane.showMessageDialog(null, "表格没有被初始化"); fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); return; } // 检查 table 是否有模型和数据 if (table.getModel() == null || table.getModel().getRowCount() <= 0) { JOptionPane.showMessageDialog(null, "当前无数据"); fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); return; }
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; RightClickFunctions.initializeTable(); textField0.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { // 当输入框内的文字是提示文字时,先清空输入框再允许输入 if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); } } }); // 设置背景色为 (4, 12, 31) textField0.setBackground(new Color(48, 49, 52)); // 设置光标 textField0.setCaret(new CustomCaret(Color.WHITE)); // 设置字体 Font font = new Font("Mono", Font.BOLD, 14); textField0.setFont(font); // fofaEX: FOFA Extension 事件 textField0.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { // 当输入框得到焦点时,如果当前是提示文字,则清空输入框并将文字颜色设置为白色 if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); textField0.setForeground(Color.WHITE); } } @Override public void focusLost(FocusEvent e) { // 当输入框失去焦点时,如果输入框为空,则显示提示文字,并将文字颜色设置为灰色 if (textField0.getText().isEmpty()) { textField0.setText("fofaEX: FOFA Extension"); textField0.setForeground(Color.GRAY); } } }); textField0.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (textField0.getText().equals("fofaEX: FOFA Extension")) { textField0.setText(""); textField0.setForeground(Color.WHITE); } } }); textField0.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { textField0.setForeground(Color.WHITE); } @Override public void removeUpdate(DocumentEvent e) { if (textField0.getText().isEmpty()) { textField0.setForeground(Color.GRAY); } else { textField0.setForeground(Color.WHITE); } } @Override public void changedUpdate(DocumentEvent e) { // 平滑字体,无需处理 } }); // 将光标放在末尾 // textField0.setCaretPosition(textField0.getText().length()); // 编辑撤销 // 创建UndoManager和添加UndoableEditListener。 final UndoManager undoManager = new UndoManager(); Document doc = textField0.getDocument(); doc.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { undoManager.addEdit(e.getEdit()); } }); // 添加KeyListener到textField。 textField0.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if ((e.getKeyCode() == KeyEvent.VK_Z) && ((e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) != 0)) { if (undoManager.canUndo()) { undoManager.undo(); } } else { if ((e.getKeyCode() == KeyEvent.VK_Z)) { e.getModifiersEx(); } } } }); // String asciiIcon = // " __ __ _____ __ __\n" + // " / _| ___ / _| __ _ | ____| \\ \\/ /\n" + // " | |_ / _ \\ | |_ / _` | | _| \\ / \n" + // " | _| | (_) | | _| | (_| | | |___ / \\ \n" + // " |_| \\___/ |_| \\__,_| |_____| /_/\\_\\"; // // JLabel labelIcon = new JLabel("<html><pre>" + asciiIcon + "</pre></html>"); JLabel labelIcon = new JLabel(" FOFA EX"); labelIcon.setForeground(new Color(48, 49, 52)); Font iconFont = new Font("Times New Roman", Font.BOLD, 60); labelIcon.setFont(iconFont); // 创建按钮面板,不改变布局(保持BoxLayout) final JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); // 创建主面板并使用BoxLayout布局 JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); // 创建一个子面板,用来在搜索框边上新增按钮 JPanel subPanel1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10)); // 创建面板并使用FlowLayout布局 JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 4)); // hgap: 组件间的水平间距 vgap: 件间的垂直间距 JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); JPanel panel3 = new JPanel(new GridLayout(0, 10, 0, 0)); JPanel panel4 = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10)); // 创建面板并使用GridLayout布局 JPanel panel5 = new JPanel(new GridLayout(0, 5, 10, 10)); // 0表示行数不限,5表示每行最多5个组件,10, 10是组件之间的间距 JPanel panel6 = new JPanel(new BorderLayout()); panel6.setBorder(BorderFactory.createEmptyBorder(20, 5, 10, 5)); JPanel panel7 = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); // panel8 用来放导出表格的按键 JPanel panel8 = new JPanel(); JPanel panel9 = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0)); // 创建"更新规则"按钮 创建"新增"按钮 JButton updateButton = new JButton("➕"); updateButton.setFocusPainted(false); updateButton.setFocusable(false); // 新增一个LinkedHashMap,用于存储按钮的键名和键值 Map<String, JButton> buttonsMap = new LinkedHashMap<>(); BufferedReader rulesReader = null; File accountsFile = null; try { // 创建 rules.txt 文件如果它不存在 File rulesFile = new File(rulesPath); if (!rulesFile.exists()) { rulesFile.createNewFile(); System.out.println("[+] The current path does not contain " + rulesPath + ". Create "+ rulesPath +"."); } rulesReader = new BufferedReader(new FileReader(rulesFile)); // 创建 accounts.txt 文件如果它不存在 accountsFile = new File(accountsPath); if (!accountsFile.exists()) { accountsFile.createNewFile(); System.out.println("[+] The current path does not contain " + accountsPath + ". Create " + accountsPath + "."); } } catch (IOException e) { // IO 异常处理 e.printStackTrace(); } settingInit(rulesReader, accountsFile, panel5, textField0, fofaEmail, fofaKey, buttonsMap); updateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 创建一个JPanel来包含两个输入框 JPanel inputPanel = new JPanel(new GridLayout(4, 4)); inputPanel.add(new JLabel("键名:")); JTextField nameField = new JTextField(10); inputPanel.add(nameField); inputPanel.add(new JLabel("键值:")); JTextField valueField = new JTextField(10); inputPanel.add(valueField); // 弹出自定义对话框 int result = JOptionPane.showConfirmDialog(null, inputPanel, "新增按键", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); // 当用户点击OK时处理输入 if (result == JOptionPane.OK_OPTION) { String keyName = nameField.getText().trim(); String keyValue = valueField.getText().trim(); // 验证输入是否非空 if (!keyName.isEmpty() && !keyValue.isEmpty()) { // 将键名和键值以"键名":{键值}的形式保存在rule.txt的最后一行 try (BufferedWriter writer = new BufferedWriter(new FileWriter(rulesPath, true))) { System.out.println(keyValue); writer.write("\"" + keyName + "\":{" + keyValue + "},"); writer.newLine(); // Ensure the new entry is on a new line } catch (IOException addError) { addError.printStackTrace(); JOptionPane.showMessageDialog(null, "无法写入文件", "错误", JOptionPane.ERROR_MESSAGE); } // 添加右键菜单功能 try { BufferedReader reader = new BufferedReader(new FileReader(rulesPath)); Map<String, String> newMap = new LinkedHashMap<>(); String line; while ((line = reader.readLine()) != null) { line = line.trim(); // 跳过井号注释 if (line.startsWith("#")) { continue; } if (line.startsWith("\"") && line.contains("{") && line.contains("}")) { String[] parts = line.split(":", 2); String key = parts[0].substring(1, parts[0].length() - 1).trim(); String value = parts[1].substring(1, parts[1].length() - 2).trim(); newMap.put(key, value); } } reader.close(); // 配置文件更新并新增按钮 for (Map.Entry<String, String> entry : newMap.entrySet()) { JButton existingButton = buttonsMap.get(entry.getKey()); if (existingButton == null) { // 新按钮 JButton newButton = new JButton(entry.getKey()); newButton.setActionCommand(entry.getValue()); newButton.setToolTipText(entry.getValue()); // 设置按钮的 ToolTip 为键值,悬浮显示 newButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 newButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态 newButton.addActionListener(actionEvent -> { if (newButton.getForeground() != Color.RED) { // 如果文本为提示文字,则清空文本 if (textField0.getText().contains("fofaEX: FOFA Extension")) { textField0.setText(""); } textField0.setText(textField0.getText() + " " + newButton.getActionCommand()); newButton.setForeground(Color.RED); newButton.setFont(newButton.getFont().deriveFont(Font.BOLD)); // 设置字体为粗体 } else { textField0.setText(textField0.getText().replace(" " + newButton.getActionCommand(), "")); newButton.setForeground(null); newButton.setFont(null); // 如果为空则设置 prompt if (textField0.getText().isEmpty()) { textField0.setText("fofaEX: FOFA Extension"); textField0.setForeground(Color.GRAY); // 将光标放在开头 textField0.setCaretPosition(0); } } }); // 添加右键单击事件的处理 newButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { // 在这里处理右键单击事件 JPopupMenu popupMenu = new JPopupMenu(); JMenuItem deleteItem = new JMenuItem("删除"); JMenuItem editItem = new JMenuItem("修改"); deleteItem.addActionListener(actionEvent -> { // 删除:在这里处理删除操作 int dialogResult = JOptionPane.showConfirmDialog(panel5, "是否删除?", "删除确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (dialogResult == JOptionPane.YES_OPTION) { // 确认删除操作 panel5.remove(newButton); panel5.revalidate(); panel5.repaint(); // 从文件中删除 removeButtonAndLineFromFile(entry.getKey(), rulesPath); } }); editItem.addActionListener(actionEvent -> { // 获取当前按钮的名称和对应的JButton对象 String oldName = entry.getKey(); JButton buttonToUpdate = newButton; // 确保newButton是当前要修改的按钮的引用 // 创建一个JPanel来包含两个输入框 JPanel panel = new JPanel(new GridLayout(4, 4)); panel.add(new JLabel("键名:")); JTextField nameField = new JTextField(newButton.getText()); panel.add(nameField); panel.add(new JLabel("键值:")); JTextField valueField = new JTextField(buttonToUpdate.getActionCommand()); panel.add(valueField); // 弹出自定义对话框 int result = JOptionPane.showConfirmDialog(panel5, panel, "修改配置", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); // 当用户点击OK时处理输入 if (result == JOptionPane.OK_OPTION) { String newName = nameField.getText().trim(); String newValue = valueField.getText().trim(); // 验证输入是否已变更且非空 if (!newName.isEmpty() && !newValue.isEmpty()) { // 修改按钮名称和键值 updateButtonNameAndValue(oldName, newName, newValue, buttonToUpdate, buttonsMap, rulesPath); // 更新界面 panel5.revalidate(); panel5.repaint(); } } }); popupMenu.add(editItem); popupMenu.add(deleteItem); popupMenu.show(e.getComponent(), e.getX(), e.getY()); popupMenu.add(deleteItem); popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); panel5.add(newButton); buttonsMap.put(entry.getKey(), newButton); } else { // This is an existing button existingButton.setActionCommand(entry.getValue()); existingButton.setText(entry.getKey()); // Update button text } } panel5.revalidate(); panel5.repaint(); } catch (IOException ioException) { ioException.printStackTrace(); } // 更新界面 panel5.revalidate(); panel5.repaint(); } } // 读取文件内容,并创建新的按钮 } }); // 搜索按钮 // 将textField0添加到新的SubPanel subPanel1.add(textField0); searchButton("搜索", true, subPanel1, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "null"); panel1.add(labelIcon); panel2.add(subPanel1); // 搜索框 + 搜索按钮 JLabel jLabel7 = new JLabel("total lines "); panel7.add(jLabel7); searchButton("◁", false, panel7, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "left"); searchButton("▷", false, panel7, textField0, fofaEmail, fofaKey, fofaUrl, panel6, panel8, labelIcon, panel2, panel3, panel7, panel9, "right"); // 添加逻辑运算组件 createLogicAddButton("=", "=", panel4, textField0); createLogicAddButton("==", "==", panel4, textField0); createLogicAddButton("&&", "&&", panel4, textField0); createLogicAddButton("||", "||", panel4, textField0); createLogicAddButton("!=", "!=", panel4, textField0); createLogicAddButton("*=", "*=", panel4, textField0); // 新增折叠按钮到panel3 JButton foldButton = new JButton("▼"); foldButton.setFocusPainted(false); //添加这一行来取消焦点边框的绘制 foldButton.setFocusable(false); // 添加点击事件 foldButton.addActionListener(new ActionListener() { boolean isFolded = false; @Override public void actionPerformed(ActionEvent actionEvent) { if (!isFolded) { // 折叠 panel5 panel5.setVisible(false); foldButton.setText("◀"); scrollPaneMark = false; } else { // 展开 panel5 panel5.setVisible(true); foldButton.setText("▼"); scrollPaneMark = true; } isFolded = !isFolded; // 重新验证和重绘包含 panel5 和 panel6 的主面板 mainPanel.revalidate(); mainPanel.repaint(); } }); panel4.add(updateButton); // 更新规则 panel4.add(foldButton); // 创建复选框 addRuleBox(panel3, "host", newValue -> hostMark = newValue, hostMark, true); addRuleBox(panel3, "ip", newValue -> ipMark = newValue, ipMark, true); addRuleBox(panel3, "port", newValue -> portMark = newValue, portMark, true); addRuleBox(panel3, "protocol", newValue -> protocolMark = newValue, protocolMark); addRuleBox(panel3, "title", newValue -> titleMark = newValue, titleMark); addRuleBox(panel3, "domain", newValue -> domainMark = newValue, domainMark); addRuleBox(panel3, "link", newValue -> linkMark = newValue, linkMark); addRuleBox(panel3, "icp", newValue -> icpMark = newValue, icpMark); addRuleBox(panel3, "city", newValue -> cityMark = newValue, cityMark); /* 下面代码未完成 */ addRuleBox(panel3, "country", newValue -> countryMark = newValue, countryMark); /* 测试一下 */ addRuleBox(panel3, "country_name", newValue -> country_nameMark = newValue, country_nameMark); addRuleBox(panel3, "region", newValue -> regionMark = newValue, regionMark); addRuleBox(panel3, "longitude", newValue -> longitudeMark = newValue, longitudeMark); addRuleBox(panel3, "latitude", newValue -> latitudeMark = newValue, latitudeMark); addRuleBox(panel3, "asNumber", newValue -> asNumberMark = newValue, asNumberMark); addRuleBox(panel3, "asOrganization", newValue -> asOrganizationMark = newValue, asOrganizationMark); addRuleBox(panel3, "os", newValue -> osMark = newValue, osMark); addRuleBox(panel3, "server", newValue -> serverMark = newValue, serverMark); addRuleBox(panel3, "jarm", newValue -> jarmMark = newValue, jarmMark); addRuleBox(panel3, "header", newValue -> headerMark = newValue, headerMark); addRuleBox(panel3, "banner", newValue -> bannerMark = newValue, bannerMark); addRuleBox(panel3, "baseProtocol", newValue -> baseProtocolMark = newValue, baseProtocolMark); addRuleBox(panel3, "certsIssuerOrg", newValue -> certsIssuerOrgMark = newValue, certsIssuerOrgMark); addRuleBox(panel3, "certsIssuerCn", newValue -> certsIssuerCnMark = newValue, certsIssuerCnMark); addRuleBox(panel3, "certsSubjectOrg", newValue -> certsSubjectOrgMark = newValue, certsSubjectOrgMark); addRuleBox(panel3, "certsSubjectCn", newValue -> certsSubjectCnMark = newValue, certsSubjectCnMark); addRuleBox(panel3, "tlsJa3s", newValue -> tlsJa3sMark = newValue, tlsJa3sMark); addRuleBox(panel3, "tlsVersion", newValue -> tlsVersionMark = newValue, tlsVersionMark); addRuleBox(panel3, "product", newValue -> productMark = newValue, productMark); addRuleBox(panel3, "productCategory", newValue -> productCategoryMark = newValue, productCategoryMark); addRuleBox(panel3, "version", newValue -> versionMark = newValue, versionMark); addRuleBox(panel3, "lastupdatetime", newValue -> lastupdatetimeMark = newValue, lastupdatetimeMark); addRuleBox(panel3, "cname", newValue -> cnameMark = newValue, cnameMark); addRuleBox(panel3, "iconHash", newValue -> iconHashMark = newValue, iconHashMark); addRuleBox(panel3, "certsValid", newValue -> certsValidMark = newValue, certsValidMark); addRuleBox(panel3, "cnameDomain", newValue -> cnameDomainMark = newValue, cnameDomainMark); addRuleBox(panel3, "body", newValue -> bodyMark = newValue, bodyMark); addRuleBox(panel3, "icon", newValue -> iconMark = newValue, iconMark); addRuleBox(panel3, "fid", newValue -> fidMark = newValue, fidMark); addRuleBox(panel3, "structinfo", newValue -> structinfoMark = newValue, structinfoMark); // 设置全局边框:创建一个带有指定的空白边框的新面板,其中指定了上、左、下、右的边距 mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 添加面板到主面板 mainPanel.add(panel1); mainPanel.add(panel2); mainPanel.add(panel3); mainPanel.add(panel4); mainPanel.add(panel5); mainPanel.add(panel6); mainPanel.add(panel7); mainPanel.add(panel8); mainPanel.add(panel9); tabbedPane0.addTab("FofaEX", mainPanel); tabbedPane0.setTabPlacement(JTabbedPane.BOTTOM); // 将标签放置在底部 // fofa 插件初始化 FofaHack.panel = panel6; FofaHack.table = table; FofaHack.exportPanel = panel8; FofaHack.exportButtonAdded = false; FofaHack.rowCountLabel = jLabel7; // 设置窗口居中并显示 jFrame.setLocationRelativeTo(null); jFrame.add(tabbedPane0); ; jFrame.setVisible(true); // 在程序运行时,使 textField0 获得焦点 SwingUtilities.invokeLater(new Runnable() { public void run() { textField0.requestFocusInWindow(); } }); // 更改"账户设置"菜单项的事件监听 changePasswordMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 创建新的JFrame JFrame settingsFrame = new JFrame("Settings"); // 创建新的面板并添加组件 JPanel settingsPanel = new JPanel(new GridLayout(4, 2, 5, 5)); // 使用4行2列的GridLayout settingsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 设置边距 JButton checkButton = new JButton("检查账户"); checkButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 checkButton.setFocusable(false); checkButton.addActionListener(e1 -> { // 点击按钮时显示输入的数据 String email = fofaEmail.getText(); String key = fofaKey.getText(); String fofaUrl_str = fofaUrl.getText(); // https://fofa.info/api/v1/info/my?email= String authUrl = fofaUrl_str + "/api/v1/info/my?email=" + email + "&key=" + key; HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(authUrl); try { HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); // 解析JSON数据 JSONObject json = new JSONObject(responseBody); if (!json.getBoolean("error")) { // 账户验证有效 StringBuilder output = new StringBuilder(); output.append("账户验证有效\n"); output.append("邮箱地址: ").append(json.getString("email")).append("\n"); output.append("用户名: ").append(json.getString("username")).append("\n"); if (json.getBoolean("isvip")) { output.append("身份权限:FOFA会员\n"); } else { output.append("身份权限:普通用户\n"); } ; output.append("F点数量: ").append(json.getInt("fofa_point")).append("\n"); output.append("API月度剩余查询次数: ").append(json.getInt("remain_api_query")).append("\n"); output.append("API月度剩余返回数量: ").append(json.getInt("remain_api_data")).append("\n"); JOptionPane.showMessageDialog(null, output.toString()); } else { // 账户验证无效 JOptionPane.showMessageDialog(null, "账户验证无效!", "提示", JOptionPane.WARNING_MESSAGE); } } catch (IOException | JSONException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "发生错误,请重试!", "错误", JOptionPane.ERROR_MESSAGE); } }); // 创建"保存设置"按钮 JButton saveSettingsButton = new JButton("保存设置"); saveSettingsButton.setFocusPainted(false); // 取消焦点边框的绘制 saveSettingsButton.setFocusable(false); saveSettingsButton.addActionListener(SaveError -> { // 准备一个 JsonObject JsonObject jsonObject = new JsonObject(); File jsonFile = new File(accountsPath); // 如果文件存在且其内容不为空,从中读取 JsonObject if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { // parse error handling ex.printStackTrace(); } } // 更新邮件和密钥设置 jsonObject.addProperty("fofaEmail", fofaEmail.getText()); jsonObject.addProperty("fofaKey", fofaKey.getText()); // 将已更新的 jsonObject 写回到 "accounts.json" 文件 try (FileWriter writer = new FileWriter(accountsPath)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); JOptionPane.showMessageDialog(null, "设置已保存。"); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "保存设置时发生错误!", "错误", JOptionPane.ERROR_MESSAGE); } }); // 添加组件到设置面板 settingsPanel.add(new JLabel("FOFA URL:")); settingsPanel.add(fofaUrl); settingsPanel.add(new JLabel("Email:")); settingsPanel.add(fofaEmail); settingsPanel.add(new JLabel("API Key:")); settingsPanel.add(fofaKey); settingsPanel.add(checkButton); settingsPanel.add(saveSettingsButton); // 添加设置面板到设置窗口,并显示设置窗口 settingsFrame.add(settingsPanel); settingsFrame.pack(); settingsFrame.setLocationRelativeTo(null); // 使窗口居中显示 settingsFrame.setResizable(false); settingsFrame.setVisible(true); } }); configureMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JTextField inputField = new JTextField(String.valueOf(sizeSetting)); JButton okButton = new JButton("保存"); JButton cancelButton = new JButton("取消"); JOptionPane optionPane = new JOptionPane(inputField, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); optionPane.setOptions(new Object[] { okButton, cancelButton }); JDialog dialog = optionPane.createDialog("请输入默认查询数量"); okButton.addActionListener(ev -> { try { sizeSetting = Integer.parseInt(inputField.getText()); // 读取JSON文件 JsonObject jsonObject; File jsonFile = new File(accountsPath); if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { ex.printStackTrace(); return; } } else { jsonObject = new JsonObject(); } // 更新queryNumber并重新写入文件 jsonObject.addProperty("queryNumber", sizeSetting); try (FileWriter writer = new FileWriter(accountsPath)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); } // 显示保存成功提醒 JOptionPane.showMessageDialog(null, "保存成功!"); // 关闭原始对话框 dialog.dispose(); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "请输入一个有效的整数值。"); } catch (IOException ex) { // 处理文件读写异常 JOptionPane.showMessageDialog(null, "发生错误,账户配置文件不存在。"); } }); cancelButton.addActionListener(ev -> dialog.dispose()); dialog.setVisible(true); } }); configureFullItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JsonObject jsonObject; File jsonFile = new File("accounts.json"); // 如果文件存在且其内容不为空,从中读取 JsonObject if (jsonFile.exists() && jsonFile.length() != 0) { try (FileReader reader = new FileReader(jsonFile)) { Gson gson = new Gson(); jsonObject = gson.fromJson(reader, JsonObject.class); } catch (Exception ex) { // 解析错误处理 ex.printStackTrace(); return; } } else { jsonObject = new JsonObject(); } // 读取 queryFull 的值,并设置复选框的选择状态 if (jsonObject.has("queryFull")) { defaultCheckFullBox.setSelected(!jsonObject.get("queryFull").getAsBoolean()); } JButton okButton = new JButton("保存"); JButton cancelButton = new JButton("取消"); JOptionPane optionPane = new JOptionPane(defaultCheckFullBox, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); optionPane.setOptions(new Object[]{okButton, cancelButton}); JDialog dialog = optionPane.createDialog("是否默认查询区间"); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); okButton.addActionListener(ev -> { // 如果复选框选中,则设置 queryFull 为 false,否则为 true boolean queryFull = !defaultCheckFullBox.isSelected(); jsonObject.addProperty("queryFull", queryFull); // 更新 setFull 的值 setFull = queryFull; // 将 jsonObject 保存到 "accounts.json" 文件中 try (FileWriter writer = new FileWriter(jsonFile)) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(jsonObject, writer); JOptionPane.showMessageDialog(null, "保存成功!"); dialog.dispose(); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "发生错误,保存设置失败。"); } }); cancelButton.addActionListener(ev -> dialog.dispose()); dialog.setVisible(true); } }); // 图标哈希计算事件 iconHashLabMenuItem.addActionListener((ActionEvent event) -> { EventQueue.invokeLater(() -> { IconHashCalculator calculator = new IconHashCalculator(); calculator.setVisible(true); }); }); fofaHackMenuItemRun.addActionListener((ActionEvent event) -> { EventQueue.invokeLater(() -> { FofaHack.main(); }); }); openFileMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); // 如果存在上次打开的路径,则设置文件选择器的当前目录 if (lastOpenedPath != null) { fileChooser.setCurrentDirectory(lastOpenedPath); } if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); // 更新 lastOpenedPath 为当前选择的文件或文件夹 lastOpenedPath = fileChooser.getCurrentDirectory(); // 调用方法来处理文件 FofaHack.loadFileIntoTable(file); } } }); // 焦点测试 点击事件:显示当前标签 focusTestItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CommonTemplate.localCurrentTab(tabbedPane0); // CommonTemplate.switchTab(tabbedPane0,tabName); } }); switchToHttpxItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { switchTab(tabbedPane0, "httpx"); } }); // 为"关于项目"菜单项添加动作监听器 aboutMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JEditorPane editorPane = new JEditorPane("text/html", ""); editorPane.setText( "<html><body>" + "<b>fofa EX:</b><br>" + "Project: <a href='https://github.com/10cks/fofaEX'>https://github.com/10cks/fofaEX</a><br>" + "Author: bwner@OverSpace<br>" + "Version: 2.2<br>" + "JDK Version: 11.0.5<br>" + "Update: 2023.12.11<br>" + "</body></html>" ); editorPane.setEditable(false); editorPane.setOpaque(false); editorPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent evt) { if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { Desktop.getDesktop().browse(evt.getURL().toURI()); } catch (IOException | URISyntaxException ex) { JOptionPane.showMessageDialog(null, "无法打开链接,错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } }); // 弹出一个包含JEditorPane的消息对话框 JOptionPane.showMessageDialog(null, new JScrollPane(editorPane), "关于项目", JOptionPane.PLAIN_MESSAGE); } }); // 为 "fofahack 设置" 添加动作监听器 fofaHackMenuItemSetting.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 检查文件是否存在 File fofaHackSettingsFile = new File(".\\plugins\\fofahack\\FofaHackSetting.txt"); if (fofaHackSettingsFile.exists()) { // 如果文件存在,使用系统默认编辑器打开它 try { Desktop.getDesktop().edit(fofaHackSettingsFile); } catch (IOException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "无法打开配置文件!", "错误", JOptionPane.ERROR_MESSAGE); } } else { // 如果文件不存在,显示弹窗 JOptionPane.showMessageDialog(null, "未获取到配置文件!", "错误", JOptionPane.ERROR_MESSAGE); } } }); // 为" fofahack 关于项目"菜单项添加动作监听器 fofaHackMenuItemAbout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JEditorPane editorPane = new JEditorPane("text/html", ""); editorPane.setText( "<html><body>" + "<b>fofa-hack:</b><br>" + "Project: <a href='https://github.com/Cl0udG0d/Fofa-hack'>https://github.com/Cl0udG0d/Fofa-hack</a><br>" + "Author: Cl0udG0d<br>" + "version: 当前使用为修改版<br>" + "</body></html>" ); editorPane.setEditable(false); editorPane.setOpaque(false); editorPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent evt) { if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { Desktop.getDesktop().browse(evt.getURL().toURI()); } catch (IOException | URISyntaxException ex) { JOptionPane.showMessageDialog(null, "无法打开链接,错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } } }); // 弹出一个包含JEditorPane的消息对话框 JOptionPane.showMessageDialog(null, new JScrollPane(editorPane), "关于项目", JOptionPane.PLAIN_MESSAGE); } }); } private static JTextField createTextField(String text) { JTextField textField = new JTextField(text, 20); textField.setPreferredSize(new Dimension(200, 20)); // 创建只有底边的边框 Border blueBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.RED); Border defaultBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY); // 设置默认边框 textField.setBorder(defaultBorder); // 添加鼠标监听器 textField.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { // 鼠标进入时,设置边框颜色为蓝色 textField.setBorder(blueBorder); } @Override public void mouseExited(MouseEvent e) { // 鼠标离开时,将边框颜色设回默认颜色 textField.setBorder(defaultBorder); } }); return textField; } private static JTextField createTextFieldFofa(String text) { RoundJTextField textField = new RoundJTextField(0); textField.setText(text); textField.setPreferredSize(new Dimension(800, 50)); // 设置文本与边框的间距 textField.setMargin(new Insets(0, 10, 0, 5)); // 创建只有底边的边框 Border blueBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.RED); Border defaultBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY); // 设置默认边框 // textField.setBorder(defaultBorder); return textField; } private static void createLogicAddButton(String buttonText, String appendText, JPanel panel, JTextField textField) { // 创建按钮 JButton button = new JButton(buttonText); button.setFocusPainted(false); // 不显示按钮焦点外边框 button.setFocusable(false); // 禁止按钮获取焦点 // 添加点击事件 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (textField.getText().contains("fofaEX: FOFA Extension")) { textField.setText(""); } // 追加指定文本到文本框中 textField.setText(textField.getText() + " " + appendText); } }); // 将按钮添加到指定面板中 panel.add(button); } private static void searchButton(String buttonText, boolean shouldSetSize, JPanel panel, JTextField textField, JTextField emailField, JTextField keyField, JTextField urlField, JPanel resultPanel, JPanel exportPanel, JLabel changeIcon, JPanel disablePanel2, JPanel disablePanel3, JPanel disablePanel7, JPanel totalPanel8, String pageButton) { JButton button = new JButton(buttonText); button.setFocusPainted(false); button.setFocusable(false); if (shouldSetSize) { button.setPreferredSize(new Dimension(60, 50)); } button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { String domain = urlField.getText().trim(); String email = emailField.getText().trim(); String key = keyField.getText().trim(); String grammar = textField.getText().trim(); String orginIconStr = changeIcon.getText(); // String searchAsciiIcon = " ____ _ _ \n" + // " / ___| ___ __ _ _ __ ___ | |__ (_) _ __ __ _ \n" + // " \\___ \\ / _ \\ / _` | | '__| / __| | '_ \\ | | | '_ \\ / _` | \n" + // " ___) | | __/ | (_| | | | | (__ | | | | | | | | | | | (_| | \n" + // " |____/ \\___| \\__,_| |_| \\___| |_| |_| |_| |_| |_| \\__, | \n" ; // // // changeIcon.setText("<html><pre>" + searchAsciiIcon + "</pre></html>"); changeIcon.setText(" FOFA EX"); changeIcon.setForeground(new Color(89, 154, 248)); // 设置文本颜色为红色 Font font = new Font("Times New Roman", Font.BOLD, 60); changeIcon.setFont(font); setComponentsEnabled(disablePanel2, false); setComponentsEnabled(disablePanel3, false); setComponentsEnabled(disablePanel7, false); // 创建 SwingWorker 来处理搜索任务 SwingWorker<SearchResults, Void> worker = new SwingWorker<SearchResults, Void>() { private void fontSet(JLabel changeIcon, String originIconStr) { changeIcon.setText(originIconStr); changeIcon.setForeground(new Color(48, 49, 52)); } @Override protected SearchResults doInBackground() throws Exception { SearchResults results = new SearchResults(); QueryResponse queryResponse = new QueryResponse(); String errorMessage = null; // 用于存储错误消息 errorMessage = queryResponse.errmsg; // 存储错误消息以便后面使用 String fieldsTotal = ""; long startTime = System.nanoTime(); try { String query = grammar; if (query.equals("fofaEX: FOFA Extension")) { query = ""; // 将字符串设置为空 } if (protocolMark) { fieldsTotal += ",protocol"; } if (titleMark) { fieldsTotal += ",title"; } if (domainMark) { fieldsTotal += ",domain"; } if (linkMark) { fieldsTotal += ",link"; } if (icpMark) { fieldsTotal += ",icp"; } if (cityMark) { fieldsTotal += ",city"; } if (countryMark) { fieldsTotal += ",country"; } if (country_nameMark) { fieldsTotal += ",country_name"; } if (regionMark) { fieldsTotal += ",region"; } if (longitudeMark) { fieldsTotal += ",longitude"; } if (latitudeMark) { fieldsTotal += ",latitude"; } if (asNumberMark) { fieldsTotal += ",as_number"; } if (asOrganizationMark) { fieldsTotal += ",as_organization"; } if (osMark) { fieldsTotal += ",os"; } if (serverMark) { fieldsTotal += ",server"; } if (jarmMark) { fieldsTotal += ",jarm"; } if (headerMark) { fieldsTotal += ",header"; } if (bannerMark) { fieldsTotal += ",banner"; } if (baseProtocolMark) { fieldsTotal += ",base_protocol"; } if (certsIssuerOrgMark) { fieldsTotal += ",certs_issuer_org"; } if (certsIssuerCnMark) { fieldsTotal += ",certs_issuer_cn"; } if (certsSubjectOrgMark) { fieldsTotal += ",certs_subject_org"; } if (certsSubjectCnMark) { fieldsTotal += ",certs_subject_cn"; } if (tlsJa3sMark) { fieldsTotal += ",tls_ja3s"; } if (tlsVersionMark) { fieldsTotal += ",tls_version"; } if (productMark) { fieldsTotal += ",product"; } if (productCategoryMark) { fieldsTotal += ",product_category"; } if (versionMark) { fieldsTotal += ",version"; } if (lastupdatetimeMark) { fieldsTotal += ",lastupdatetime"; } if (cnameMark) { fieldsTotal += ",cname"; } if (iconHashMark) { fieldsTotal += ",icon_hash"; } if (certsValidMark) { fieldsTotal += ",certs_valid"; } if (cnameDomainMark) { fieldsTotal += ",cname_domain"; } if (bodyMark) { fieldsTotal += ",body"; } if (iconMark) { fieldsTotal += ",icon"; } if (fidMark) { fieldsTotal += ",fid"; } if (structinfoMark) { fieldsTotal += ",structinfo"; } // 创建字典 Map<String, Boolean> marks = new LinkedHashMap<>(); marks.put("host", ipMark); marks.put("ip", ipMark); marks.put("port", portMark); marks.put("protocol", protocolMark); marks.put("title", titleMark); marks.put("domain", domainMark); marks.put("link", linkMark); marks.put("icp", icpMark); marks.put("city", cityMark); marks.put("country", countryMark); marks.put("country_name", country_nameMark); marks.put("region", regionMark); marks.put("longitude", longitudeMark); marks.put("latitude", latitudeMark); marks.put("asNumber", asNumberMark); marks.put("asOrganization", asOrganizationMark); marks.put("os", osMark); marks.put("server", serverMark); marks.put("jarm", jarmMark); marks.put("header", headerMark); marks.put("banner", bannerMark); marks.put("baseProtocol", baseProtocolMark); marks.put("certsIssuerOrg", certsIssuerOrgMark); marks.put("certsIssuerCn", certsIssuerCnMark); marks.put("certsSubjectOrg", certsSubjectOrgMark); marks.put("certsSubjectCn", certsSubjectCnMark); marks.put("tlsJa3s", tlsJa3sMark); marks.put("tlsVersion", tlsVersionMark); marks.put("product", productMark); marks.put("productCategory", productCategoryMark); marks.put("version", versionMark); marks.put("lastupdatetime", lastupdatetimeMark); marks.put("cname", cnameMark); marks.put("iconHash", iconHashMark); marks.put("certsValid", certsValidMark); marks.put("cnameDomain", cnameDomainMark); marks.put("body", bodyMark); marks.put("icon", iconMark); marks.put("fid", fidMark); marks.put("structinfo", structinfoMark); // 标记为真的放在一起 List<String> trueMarks = extractTrueMarks(marks); System.out.println(trueMarks); if (pageButton.equals("left")) { if (currentPage != 0) { currentPage = currentPage - 1; } else { } currentPage = 1; } else if (pageButton.equals("right")) { currentPage = currentPage + 1; } // 开始查询 JSONObject jsonResponse = FofaAPI.getAllJsonResult(domain, email, key, query, fieldsTotal, sizeSetting, currentPage, setFull); // 检查错误信息 queryResponse.error = (boolean) FofaAPI.getValueFromJson(jsonResponse, "error"); queryResponse.errmsg = (String) FofaAPI.getValueFromJson(jsonResponse, "errmsg"); // 取出整体 results queryResponse.results = (List<List<String>>) FofaAPI.getValueFromJson(jsonResponse, "results"); if (queryResponse.error) { throw new Exception(queryResponse.errmsg); } List<List<String>> allShow = queryResponse.results; // 需要放在异常后面 // currentPage = (int) FofaAPI.getValueFromJson(jsonResponse, "page"); queryTotalNumber = (int) FofaAPI.getValueFromJson(jsonResponse, "size"); List<String> hostShow = FofaAPI.getColumn(allShow, 0); numberOfItems = hostShow.size(); int i = 0; for (String mark : trueMarks) { switch (mark) { case "host": results.host = FofaAPI.getColumn(allShow, i); break; case "ip": results.ip = FofaAPI.getColumn(allShow, i); break; case "protocol": results.protocol = FofaAPI.getColumn(allShow, i); break; case "port": results.port = FofaAPI.getColumn(allShow, i); break; case "title": results.title = decodeHtmlEntities(FofaAPI.getColumn(allShow, i)); break; case "domain": results.domain = FofaAPI.getColumn(allShow, i); break; case "link": results.link = FofaAPI.getColumn(allShow, i); break; case "icp": results.icp = FofaAPI.getColumn(allShow, i); break; case "city": results.city = FofaAPI.getColumn(allShow, i); break; case "country": results.country = FofaAPI.getColumn(allShow, i); break; case "country_name": results.country_name = FofaAPI.getColumn(allShow, i); break; case "region": results.region = FofaAPI.getColumn(allShow, i); break; case "longitude": results.longitude = FofaAPI.getColumn(allShow, i); break; case "latitude": results.latitude = FofaAPI.getColumn(allShow, i); break; case "asNumber": results.asNumber = FofaAPI.getColumn(allShow, i); break; case "asOrganization": results.asOrganization = FofaAPI.getColumn(allShow, i); break; case "os": results.os = FofaAPI.getColumn(allShow, i); break; case "server": results.server = FofaAPI.getColumn(allShow, i); break; case "jarm": results.jarm = FofaAPI.getColumn(allShow, i); break; case "header": results.header = FofaAPI.getColumn(allShow, i); break; case "banner": results.banner = FofaAPI.getColumn(allShow, i); break; case "baseProtocol": results.baseProtocol = FofaAPI.getColumn(allShow, i); break; case "certsIssuerOrg": results.certsIssuerOrg = FofaAPI.getColumn(allShow, i); break; case "certsIssuerCn": results.certsIssuerCn = FofaAPI.getColumn(allShow, i); break; case "certsSubjectOrg": results.certsSubjectOrg = FofaAPI.getColumn(allShow, i); break; case "certsSubjectCn": results.certsSubjectCn = FofaAPI.getColumn(allShow, i); break; case "tlsJa3s": results.tlsJa3s = FofaAPI.getColumn(allShow, i); break; case "tlsVersion": results.tlsVersion = FofaAPI.getColumn(allShow, i); break; case "product": results.product = FofaAPI.getColumn(allShow, i); break; case "productCategory": results.productCategory = FofaAPI.getColumn(allShow, i); break; case "version": results.version = FofaAPI.getColumn(allShow, i); break; case "lastupdatetime": results.lastupdatetime = FofaAPI.getColumn(allShow, i); break; case "cname": results.cname = FofaAPI.getColumn(allShow, i); break; case "iconHash": results.iconHash = FofaAPI.getColumn(allShow, i); break; case "certsValid": results.certsValid = FofaAPI.getColumn(allShow, i); break; case "cnameDomain": results.cnameDomain = FofaAPI.getColumn(allShow, i); break; case "body": results.body = FofaAPI.getColumn(allShow, i); break; case "icon": results.icon = FofaAPI.getColumn(allShow, i); break; case "fid": results.fid = FofaAPI.getColumn(allShow, i); break; case "structinfo": results.structinfo = FofaAPI.getColumn(allShow, i); break; } i = i + 1; } // 导出表格 JButton exportButton = new JButton("Export to Excel"); exportButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制 exportButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态 if (!exportButtonAdded) { exportPanel.add(exportButton); exportButtonAdded = true; } exportButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 在这里检查 table 是否被初始化 if (table == null) { JOptionPane.showMessageDialog(null, "表格没有被初始化"); fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); return; } // 检查 table 是否有模型和数据 if (table.getModel() == null || table.getModel().getRowCount() <= 0) { JOptionPane.showMessageDialog(null, "当前无数据"); fontSet(changeIcon, orginIconStr); setComponentsEnabled(disablePanel2, true); setComponentsEnabled(disablePanel3, true); setComponentsEnabled(disablePanel7, true); return; }
CommonExecute.exportTableToExcel(table);
0
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;
14,447
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()); } //计算企业签署位置和个人签署位置
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())){
0
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,126
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)
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)
21
2023-12-06 13:20:16+00:00
24k
HelpChat/DeluxeMenus
src/main/java/com/extendedclip/deluxemenus/menu/MenuItemOptions.java
[ { "identifier": "ClickHandler", "path": "src/main/java/com/extendedclip/deluxemenus/action/ClickHandler.java", "snippet": "public interface ClickHandler {\r\n\r\n void onClick(@NotNull final MenuHolder menuHolder);\r\n}\r" }, { "identifier": "DeluxeMenusConfig", "path": "src/main/java/com/e...
import com.extendedclip.deluxemenus.action.ClickHandler; import com.extendedclip.deluxemenus.config.DeluxeMenusConfig; import com.extendedclip.deluxemenus.requirement.RequirementList; import org.bukkit.DyeColor; import org.bukkit.block.banner.Pattern; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; import org.bukkit.potion.PotionEffect; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional;
14,433
.displayName(this.displayName) .lore(this.lore) .baseColor(this.baseColor) .headType(this.headType) .placeholderData(this.placeholderData) .rgb(this.rgb) .enchantments(this.enchantments) .potionEffects(this.potionEffects) .bannerMeta(this.bannerMeta) .itemFlags(this.itemFlags) .unbreakable(this.unbreakable) .hideAttributes(this.hideAttributes) .hideEnchants(this.hideEnchants) .hidePotionEffects(this.hidePotionEffects) .hideUnbreakable(this.hideUnbreakable) .nbtString(this.nbtString) .nbtInt(this.nbtInt) .nbtStrings(this.nbtStrings) .nbtInts(this.nbtInts) .slot(this.slot) .priority(this.priority) .updatePlaceholders(this.updatePlaceholders) .clickHandler(this.clickHandler) .leftClickHandler(this.leftClickHandler) .rightClickHandler(this.rightClickHandler) .shiftLeftClickHandler(this.shiftLeftClickHandler) .shiftRightClickHandler(this.shiftRightClickHandler) .middleClickHandler(this.middleClickHandler) .viewRequirements(this.viewRequirements) .clickRequirements(this.clickRequirements) .leftClickRequirements(this.leftClickRequirements) .rightClickRequirements(this.rightClickRequirements) .shiftLeftClickRequirements(this.shiftLeftClickRequirements) .shiftRightClickRequirements(this.shiftRightClickRequirements) .middleClickRequirements(this.middleClickRequirements); } public static class MenuItemOptionsBuilder { private String material; private short data; private int amount; private String customModelData; private String dynamicAmount; private String displayName; private List<String> lore = Collections.emptyList(); private DyeColor baseColor; private HeadType headType; private String placeholderData; private String rgb; private Map<Enchantment, Integer> enchantments = Collections.emptyMap(); private List<PotionEffect> potionEffects = Collections.emptyList(); private List<Pattern> bannerMeta = Collections.emptyList(); private List<ItemFlag> itemFlags = Collections.emptyList(); private boolean unbreakable; private boolean hideAttributes; private boolean hideEnchants; private boolean hidePotionEffects; private boolean hideUnbreakable; private boolean displayNameHasPlaceholders; private boolean loreHasPlaceholders; private String nbtString; private String nbtInt; private List<String> nbtStrings = Collections.emptyList(); private List<String> nbtInts = Collections.emptyList(); private int slot; private int priority; private boolean updatePlaceholders; private ClickHandler clickHandler; private ClickHandler leftClickHandler; private ClickHandler rightClickHandler; private ClickHandler shiftLeftClickHandler; private ClickHandler shiftRightClickHandler; private ClickHandler middleClickHandler; private RequirementList viewRequirements; private RequirementList clickRequirements; private RequirementList leftClickRequirements; private RequirementList rightClickRequirements; private RequirementList shiftLeftClickRequirements; private RequirementList shiftRightClickRequirements; private RequirementList middleClickRequirements; private MenuItemOptionsBuilder() { } public MenuItemOptionsBuilder material(final @NotNull String configMaterial) { this.material = configMaterial; return this; } public MenuItemOptionsBuilder data(final short configData) { this.data = configData; return this; } public MenuItemOptionsBuilder amount(final int configAmount) { this.amount = configAmount; return this; } public MenuItemOptionsBuilder customModelData(final @Nullable String customModelData) { this.customModelData = customModelData; return this; } public MenuItemOptionsBuilder dynamicAmount(final @Nullable String configDynamicAmount) { this.dynamicAmount = configDynamicAmount; return this; } public MenuItemOptionsBuilder displayName(final @Nullable String configDisplayName) { this.displayName = configDisplayName; if (this.displayName != null) {
package com.extendedclip.deluxemenus.menu; public class MenuItemOptions { private final String material; private final short data; private final int amount; private final String customModelData; private final String dynamicAmount; private final String displayName; private final List<String> lore; private final DyeColor baseColor; private HeadType headType; private final String placeholderData; private final String rgb; private final Map<Enchantment, Integer> enchantments; private final List<PotionEffect> potionEffects; private final List<Pattern> bannerMeta; private final List<ItemFlag> itemFlags; private final boolean unbreakable; private final boolean hideAttributes; private final boolean hideEnchants; private final boolean hidePotionEffects; private final boolean hideUnbreakable; private final boolean displayNameHasPlaceholders; private final boolean loreHasPlaceholders; private final String nbtString; private final String nbtInt; private final List<String> nbtStrings; private final List<String> nbtInts; private final int slot; private final int priority; private final boolean updatePlaceholders; private final ClickHandler clickHandler; private final ClickHandler leftClickHandler; private final ClickHandler rightClickHandler; private final ClickHandler shiftLeftClickHandler; private final ClickHandler shiftRightClickHandler; private final ClickHandler middleClickHandler; private final RequirementList viewRequirements; private final RequirementList clickRequirements; private final RequirementList leftClickRequirements; private final RequirementList rightClickRequirements; private final RequirementList shiftLeftClickRequirements; private final RequirementList shiftRightClickRequirements; private final RequirementList middleClickRequirements; private MenuItemOptions(final @NotNull MenuItemOptionsBuilder builder) { this.material = builder.material; this.data = builder.data; this.amount = builder.amount; this.customModelData = builder.customModelData; this.dynamicAmount = builder.dynamicAmount; this.displayName = builder.displayName; this.lore = builder.lore; this.baseColor = builder.baseColor; this.headType = builder.headType; this.placeholderData = builder.placeholderData; this.rgb = builder.rgb; this.enchantments = builder.enchantments; this.potionEffects = builder.potionEffects; this.bannerMeta = builder.bannerMeta; this.itemFlags = builder.itemFlags; this.unbreakable = builder.unbreakable; this.hideAttributes = builder.hideAttributes; this.hideEnchants = builder.hideEnchants; this.hidePotionEffects = builder.hidePotionEffects; this.hideUnbreakable = builder.hideUnbreakable; this.displayNameHasPlaceholders = builder.displayNameHasPlaceholders; this.loreHasPlaceholders = builder.loreHasPlaceholders; this.nbtString = builder.nbtString; this.nbtInt = builder.nbtInt; this.nbtStrings = builder.nbtStrings; this.nbtInts = builder.nbtInts; this.slot = builder.slot; this.priority = builder.priority; this.updatePlaceholders = builder.updatePlaceholders; this.clickHandler = builder.clickHandler; this.leftClickHandler = builder.leftClickHandler; this.rightClickHandler = builder.rightClickHandler; this.shiftLeftClickHandler = builder.shiftLeftClickHandler; this.shiftRightClickHandler = builder.shiftRightClickHandler; this.middleClickHandler = builder.middleClickHandler; this.viewRequirements = builder.viewRequirements; this.clickRequirements = builder.clickRequirements; this.leftClickRequirements = builder.leftClickRequirements; this.rightClickRequirements = builder.rightClickRequirements; this.shiftLeftClickRequirements = builder.shiftLeftClickRequirements; this.shiftRightClickRequirements = builder.shiftRightClickRequirements; this.middleClickRequirements = builder.middleClickRequirements; } public static @NotNull MenuItemOptionsBuilder builder() { return new MenuItemOptionsBuilder(); } public @NotNull String material() { return material; } public short data() { return data; } public int amount() { return amount; } public @NotNull Optional<String> customModelData() { return Optional.ofNullable(customModelData); } public @NotNull Optional<String> dynamicAmount() { return Optional.ofNullable(dynamicAmount); } public @NotNull Optional<String> displayName() { return Optional.ofNullable(displayName); } public @NotNull List<String> lore() { return lore; } public @NotNull Optional<DyeColor> baseColor() { return Optional.ofNullable(baseColor); } public void headType(final @Nullable HeadType headType) { this.headType = headType; } public @NotNull Optional<HeadType> headType() { return Optional.ofNullable(headType); } public @NotNull Optional<String> placeholderData() { return Optional.ofNullable(placeholderData); } public @NotNull Optional<String> rgb() { return Optional.ofNullable(rgb); } public @NotNull Map<Enchantment, Integer> enchantments() { return enchantments; } public @NotNull List<PotionEffect> potionEffects() { return potionEffects; } public @NotNull List<Pattern> bannerMeta() { return bannerMeta; } public @NotNull List<ItemFlag> itemFlags() { return itemFlags; } public boolean unbreakable() { return unbreakable; } public boolean hideAttributes() { return hideAttributes; } public boolean hideEnchants() { return hideEnchants; } public boolean hidePotionEffects() { return hidePotionEffects; } public boolean hideUnbreakable() { return hideUnbreakable; } public boolean displayNameHasPlaceholders() { return displayNameHasPlaceholders; } public boolean loreHasPlaceholders() { return loreHasPlaceholders; } public @NotNull Optional<String> nbtString() { return Optional.ofNullable(nbtString); } public @NotNull Optional<String> nbtInt() { return Optional.ofNullable(nbtInt); } public @NotNull List<String> nbtStrings() { return nbtStrings; } public @NotNull List<String> nbtInts() { return nbtInts; } public int slot() { return slot; } public int priority() { return priority; } public boolean updatePlaceholders() { return updatePlaceholders; } public @NotNull Optional<ClickHandler> clickHandler() { return Optional.ofNullable(clickHandler); } public @NotNull Optional<ClickHandler> leftClickHandler() { return Optional.ofNullable(leftClickHandler); } public @NotNull Optional<ClickHandler> rightClickHandler() { return Optional.ofNullable(rightClickHandler); } public @NotNull Optional<ClickHandler> shiftLeftClickHandler() { return Optional.ofNullable(shiftLeftClickHandler); } public @NotNull Optional<ClickHandler> shiftRightClickHandler() { return Optional.ofNullable(shiftRightClickHandler); } public @NotNull Optional<ClickHandler> middleClickHandler() { return Optional.ofNullable(middleClickHandler); } public @NotNull Optional<RequirementList> viewRequirements() { return Optional.ofNullable(viewRequirements); } public @NotNull Optional<RequirementList> clickRequirements() { return Optional.ofNullable(clickRequirements); } public @NotNull Optional<RequirementList> leftClickRequirements() { return Optional.ofNullable(leftClickRequirements); } public @NotNull Optional<RequirementList> rightClickRequirements() { return Optional.ofNullable(rightClickRequirements); } public @NotNull Optional<RequirementList> shiftLeftClickRequirements() { return Optional.ofNullable(shiftLeftClickRequirements); } public @NotNull Optional<RequirementList> shiftRightClickRequirements() { return Optional.ofNullable(shiftRightClickRequirements); } public @NotNull Optional<RequirementList> middleClickRequirements() { return Optional.ofNullable(middleClickRequirements); } public @NotNull MenuItemOptionsBuilder asBuilder() { return MenuItemOptions.builder() .material(this.material) .data(this.data) .amount(this.amount) .customModelData(this.customModelData) .dynamicAmount(this.dynamicAmount) .displayName(this.displayName) .lore(this.lore) .baseColor(this.baseColor) .headType(this.headType) .placeholderData(this.placeholderData) .rgb(this.rgb) .enchantments(this.enchantments) .potionEffects(this.potionEffects) .bannerMeta(this.bannerMeta) .itemFlags(this.itemFlags) .unbreakable(this.unbreakable) .hideAttributes(this.hideAttributes) .hideEnchants(this.hideEnchants) .hidePotionEffects(this.hidePotionEffects) .hideUnbreakable(this.hideUnbreakable) .nbtString(this.nbtString) .nbtInt(this.nbtInt) .nbtStrings(this.nbtStrings) .nbtInts(this.nbtInts) .slot(this.slot) .priority(this.priority) .updatePlaceholders(this.updatePlaceholders) .clickHandler(this.clickHandler) .leftClickHandler(this.leftClickHandler) .rightClickHandler(this.rightClickHandler) .shiftLeftClickHandler(this.shiftLeftClickHandler) .shiftRightClickHandler(this.shiftRightClickHandler) .middleClickHandler(this.middleClickHandler) .viewRequirements(this.viewRequirements) .clickRequirements(this.clickRequirements) .leftClickRequirements(this.leftClickRequirements) .rightClickRequirements(this.rightClickRequirements) .shiftLeftClickRequirements(this.shiftLeftClickRequirements) .shiftRightClickRequirements(this.shiftRightClickRequirements) .middleClickRequirements(this.middleClickRequirements); } public static class MenuItemOptionsBuilder { private String material; private short data; private int amount; private String customModelData; private String dynamicAmount; private String displayName; private List<String> lore = Collections.emptyList(); private DyeColor baseColor; private HeadType headType; private String placeholderData; private String rgb; private Map<Enchantment, Integer> enchantments = Collections.emptyMap(); private List<PotionEffect> potionEffects = Collections.emptyList(); private List<Pattern> bannerMeta = Collections.emptyList(); private List<ItemFlag> itemFlags = Collections.emptyList(); private boolean unbreakable; private boolean hideAttributes; private boolean hideEnchants; private boolean hidePotionEffects; private boolean hideUnbreakable; private boolean displayNameHasPlaceholders; private boolean loreHasPlaceholders; private String nbtString; private String nbtInt; private List<String> nbtStrings = Collections.emptyList(); private List<String> nbtInts = Collections.emptyList(); private int slot; private int priority; private boolean updatePlaceholders; private ClickHandler clickHandler; private ClickHandler leftClickHandler; private ClickHandler rightClickHandler; private ClickHandler shiftLeftClickHandler; private ClickHandler shiftRightClickHandler; private ClickHandler middleClickHandler; private RequirementList viewRequirements; private RequirementList clickRequirements; private RequirementList leftClickRequirements; private RequirementList rightClickRequirements; private RequirementList shiftLeftClickRequirements; private RequirementList shiftRightClickRequirements; private RequirementList middleClickRequirements; private MenuItemOptionsBuilder() { } public MenuItemOptionsBuilder material(final @NotNull String configMaterial) { this.material = configMaterial; return this; } public MenuItemOptionsBuilder data(final short configData) { this.data = configData; return this; } public MenuItemOptionsBuilder amount(final int configAmount) { this.amount = configAmount; return this; } public MenuItemOptionsBuilder customModelData(final @Nullable String customModelData) { this.customModelData = customModelData; return this; } public MenuItemOptionsBuilder dynamicAmount(final @Nullable String configDynamicAmount) { this.dynamicAmount = configDynamicAmount; return this; } public MenuItemOptionsBuilder displayName(final @Nullable String configDisplayName) { this.displayName = configDisplayName; if (this.displayName != null) {
this.displayNameHasPlaceholders = DeluxeMenusConfig.containsPlaceholders(this.displayName);
1
2023-12-14 23:41:07+00:00
24k
lxs2601055687/contextAdminRuoYi
ruoyi-system/src/main/java/com/ruoyi/system/service/SysLoginService.java
[ { "identifier": "CacheConstants", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheConstants.java", "snippet": "public interface CacheConstants {\n\n /**\n * 登录用户 redis key\n */\n String LOGIN_TOKEN_KEY = \"Authorization:login:token:\";\n\n /**\n * 在线用户 redis key\n...
import cn.dev33.satoken.exception.NotLoginException; import cn.dev33.satoken.secure.BCrypt; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.core.domain.event.LogininforEvent; import com.ruoyi.common.core.domain.dto.RoleDTO; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.domain.model.LoginUser; import com.ruoyi.common.core.domain.model.XcxLoginUser; import com.ruoyi.common.enums.DeviceType; import com.ruoyi.common.enums.LoginType; import com.ruoyi.common.enums.UserStatus; import com.ruoyi.common.exception.user.CaptchaException; import com.ruoyi.common.exception.user.CaptchaExpireException; import com.ruoyi.common.exception.user.UserException; import com.ruoyi.common.helper.LoginHelper; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.MessageUtils; import com.ruoyi.common.utils.ServletUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.redis.RedisUtils; import com.ruoyi.common.utils.spring.SpringUtils; import com.ruoyi.system.mapper.SysUserMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.time.Duration; import java.util.List; import java.util.function.Supplier;
14,674
package com.ruoyi.system.service; /** * 登录校验方法 * * @author Lion Li */ @RequiredArgsConstructor @Slf4j @Service public class SysLoginService { private final SysUserMapper userMapper; private final ISysConfigService configService; private final SysPermissionService permissionService; @Value("${user.password.maxRetryCount}") private Integer maxRetryCount; @Value("${user.password.lockTime}") private Integer lockTime; /** * 登录验证 * * @param username 用户名 * @param password 密码 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public String login(String username, String password, String code, String uuid) { HttpServletRequest request = ServletUtils.getRequest(); boolean captchaEnabled = configService.selectCaptchaEnabled(); // 验证码开关 if (captchaEnabled) { validateCaptcha(username, code, uuid, request); }
package com.ruoyi.system.service; /** * 登录校验方法 * * @author Lion Li */ @RequiredArgsConstructor @Slf4j @Service public class SysLoginService { private final SysUserMapper userMapper; private final ISysConfigService configService; private final SysPermissionService permissionService; @Value("${user.password.maxRetryCount}") private Integer maxRetryCount; @Value("${user.password.lockTime}") private Integer lockTime; /** * 登录验证 * * @param username 用户名 * @param password 密码 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public String login(String username, String password, String code, String uuid) { HttpServletRequest request = ServletUtils.getRequest(); boolean captchaEnabled = configService.selectCaptchaEnabled(); // 验证码开关 if (captchaEnabled) { validateCaptcha(username, code, uuid, request); }
SysUser user = loadUserByUsername(username);
4
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,985
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) { long sdTotal = (long) infos.getSdCardSizeInSectors() * LibUsbMassStorageHelper.SECTOR_SIZE; long sdUsed = (long) infos.getUsedSpaceInSectors() * LibUsbMassStorageHelper.SECTOR_SIZE; String fw = infos.getFirmwareMajor() == -1 ? null : infos.getFirmwareMajor() + "." + infos.getFirmwareMinor(); return new JsonObject() .put("uuid", infos.getUuid().toString()) .put("serial", infos.getSerialNumber()) .put("firmware", fw) .put("storage", new JsonObject() .put("size", sdTotal) .put("free", sdTotal - sdUsed) .put("taken", sdUsed)) .put("error", infos.isInError()) .put("plugged", true) .put("driver", "raw"); }
/* * 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) { long sdTotal = (long) infos.getSdCardSizeInSectors() * LibUsbMassStorageHelper.SECTOR_SIZE; long sdUsed = (long) infos.getUsedSpaceInSectors() * LibUsbMassStorageHelper.SECTOR_SIZE; String fw = infos.getFirmwareMajor() == -1 ? null : infos.getFirmwareMajor() + "." + infos.getFirmwareMinor(); return new JsonObject() .put("uuid", infos.getUuid().toString()) .put("serial", infos.getSerialNumber()) .put("firmware", fw) .put("storage", new JsonObject() .put("size", sdTotal) .put("free", sdTotal - sdUsed) .put("taken", sdUsed)) .put("error", infos.isInError()) .put("plugged", true) .put("driver", "raw"); }
private JsonObject toJson(FsDeviceInfos infos) {
6
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,027
/* * <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"})
/* * <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(
0
2023-12-08 06:06:20+00:00
24k
Ispirer/COBOL-to-Java-Conversion-Samples
IspirerFramework/com/ispirer/sw/file/FileDescription.java
[ { "identifier": "FileComparator", "path": "IspirerFramework/com/ispirer/sw/file/sort/FileComparator.java", "snippet": "public class FileComparator implements Comparator<Object> {\r\n\r\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(FileComparator.class);\r\n\r\n\t@Override\r\n\tpublic i...
import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import com.ispirer.sw.file.sort.FileComparator; import com.ispirer.sw.file.sort.SortKeys; import com.ispirer.sw.types.PictureType; import com.ispirer.sw.types.StructureModel; import com.opencsv.CSVReader; import org.apache.commons.lang3.StringUtils;
16,115
/* © 2021, Ispirer Systems OÜ. All rights reserved. NOTICE OF LICENSE This file\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only. IF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY! PLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS. Redistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes. If you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com */ package com.ispirer.sw.file; /** * FileDescription is a class that implements work with files * * @param <T> is a type of record that file work with at the moment. This type * is using for sorting files and will by specified automatically */ public class FileDescription<T> { private final Logger LOGGER = Logger.getLogger(FileDescription.class.getName()); protected int recordSize; protected int block; protected File file; protected FileInputStream streamInput; protected FileOutputStream streamOutput; protected BufferedReader buffReader; private String name = ""; private Boolean csv = false; private CSVReader csvReader; private T record; private HashMap<String, Object> keys = new HashMap<>(); private TypeOrganization type = TypeOrganization.LINE_SEQUENTIAL; private Boolean advancing = false; private int codeError = 0; private int recordCounter = 0; private boolean isEBCDIC = false; public static String lineSeparator = "\r\n"; // You can specify Line separator that is fit to you public static List<Field> listField = new ArrayList<>(); public boolean isInvalidKey; /** * enum with types of Organization of files * * There are 4 types of Organization in Cobol * * LINE_SEQUENTIAL Line Sequential files are a special type of sequential file. * They correspond to simple text files as produced by the standard editor * provided with your operating system. * * RECORD_SEQUENTIAL Sequential files are the simplest form of COBOL file. * Records are placed in the file in the order they are written, and can only be * read back in the same order. * * RELATIVE_FILES Every record in a relative file can be accessed directly * without having to read through any other records. Each record is identified * by a unique ordinal number both when it is written and when it is read back. * * INDEXED Indexed files are the most complex form of COBOL file which can be * handled directly by COBOL syntax. Records in an indexed file are identified * by a unique user-defined key when written. Each record can contain any number * of user-defined keys which can be used to read the record, either directly or * in key sequence. * * Now is implemented work with LINE_SEQUENTIAL and INDEXED files by default * organization of files is LINE_SEQUENTIAL */ public enum TypeOrganization { LINE_SEQUENTIAL, RECORD_SEQUENTIAL, RELATIVE_FILES, INDEXED } /** * FileDescription Constructor * * @param name path to the file * @param record length of record * @param block count of records in a block * @param isNotEBCDIC indicates file format. True value means ASCII and false * means EBCDIC */ public FileDescription(String name, int record, int block, boolean isNotEBCDIC) { this.name = name; file = new File(this.name); this.recordSize = record; this.block = block; this.isEBCDIC = !isNotEBCDIC; this.csv = false; } /** * FileDescription Constructor * * @param name path to the file * @param record length of record * @param block count of records in a block * @param isNotEBCDIC indicates file format. True value means ASCII and false * means EBCDIC * @param csv indicates file type. True value means CSV file type, false * means another type */ public FileDescription(String name, int record, int block, boolean isNotEBCDIC, boolean csv) { this.name = name; file = new File(this.name); this.recordSize = record; this.block = block; this.isEBCDIC = !isNotEBCDIC; this.csv = csv; } /** * FileDescription Constructor * * @param name path to the file * @param record length of record * @param block count of records in a block * @param isNotEBCDIC indicates file format. True value means ASCII and false * means EBCDIC * @param keys keys (for INDEXED files) */ public FileDescription(String name, int record, int block, boolean isNotEBCDIC, boolean csv, String... keys) { this.name = name; file = new File(this.name); this.recordSize = record; this.block = block; this.isEBCDIC = !isNotEBCDIC; this.csv = csv; for (String key : keys) { this.keys.put(key, new Object()); } } /** * This method opens file for writing. * * @param status status structure. use null value if you don't have this * structure * @param append if <code>true</code>, then bytes will be written to the end of * the file rather than the beginning * @throws IOException */
/* © 2021, Ispirer Systems OÜ. All rights reserved. NOTICE OF LICENSE This file\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only. IF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY! PLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS. Redistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes. If you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com */ package com.ispirer.sw.file; /** * FileDescription is a class that implements work with files * * @param <T> is a type of record that file work with at the moment. This type * is using for sorting files and will by specified automatically */ public class FileDescription<T> { private final Logger LOGGER = Logger.getLogger(FileDescription.class.getName()); protected int recordSize; protected int block; protected File file; protected FileInputStream streamInput; protected FileOutputStream streamOutput; protected BufferedReader buffReader; private String name = ""; private Boolean csv = false; private CSVReader csvReader; private T record; private HashMap<String, Object> keys = new HashMap<>(); private TypeOrganization type = TypeOrganization.LINE_SEQUENTIAL; private Boolean advancing = false; private int codeError = 0; private int recordCounter = 0; private boolean isEBCDIC = false; public static String lineSeparator = "\r\n"; // You can specify Line separator that is fit to you public static List<Field> listField = new ArrayList<>(); public boolean isInvalidKey; /** * enum with types of Organization of files * * There are 4 types of Organization in Cobol * * LINE_SEQUENTIAL Line Sequential files are a special type of sequential file. * They correspond to simple text files as produced by the standard editor * provided with your operating system. * * RECORD_SEQUENTIAL Sequential files are the simplest form of COBOL file. * Records are placed in the file in the order they are written, and can only be * read back in the same order. * * RELATIVE_FILES Every record in a relative file can be accessed directly * without having to read through any other records. Each record is identified * by a unique ordinal number both when it is written and when it is read back. * * INDEXED Indexed files are the most complex form of COBOL file which can be * handled directly by COBOL syntax. Records in an indexed file are identified * by a unique user-defined key when written. Each record can contain any number * of user-defined keys which can be used to read the record, either directly or * in key sequence. * * Now is implemented work with LINE_SEQUENTIAL and INDEXED files by default * organization of files is LINE_SEQUENTIAL */ public enum TypeOrganization { LINE_SEQUENTIAL, RECORD_SEQUENTIAL, RELATIVE_FILES, INDEXED } /** * FileDescription Constructor * * @param name path to the file * @param record length of record * @param block count of records in a block * @param isNotEBCDIC indicates file format. True value means ASCII and false * means EBCDIC */ public FileDescription(String name, int record, int block, boolean isNotEBCDIC) { this.name = name; file = new File(this.name); this.recordSize = record; this.block = block; this.isEBCDIC = !isNotEBCDIC; this.csv = false; } /** * FileDescription Constructor * * @param name path to the file * @param record length of record * @param block count of records in a block * @param isNotEBCDIC indicates file format. True value means ASCII and false * means EBCDIC * @param csv indicates file type. True value means CSV file type, false * means another type */ public FileDescription(String name, int record, int block, boolean isNotEBCDIC, boolean csv) { this.name = name; file = new File(this.name); this.recordSize = record; this.block = block; this.isEBCDIC = !isNotEBCDIC; this.csv = csv; } /** * FileDescription Constructor * * @param name path to the file * @param record length of record * @param block count of records in a block * @param isNotEBCDIC indicates file format. True value means ASCII and false * means EBCDIC * @param keys keys (for INDEXED files) */ public FileDescription(String name, int record, int block, boolean isNotEBCDIC, boolean csv, String... keys) { this.name = name; file = new File(this.name); this.recordSize = record; this.block = block; this.isEBCDIC = !isNotEBCDIC; this.csv = csv; for (String key : keys) { this.keys.put(key, new Object()); } } /** * This method opens file for writing. * * @param status status structure. use null value if you don't have this * structure * @param append if <code>true</code>, then bytes will be written to the end of * the file rather than the beginning * @throws IOException */
public void openOutput(StructureModel status, boolean append) throws IOException {
3
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;
16,328
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() {
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();
5
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,320
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); builder.append('='); UrlEncoded.encodeInto(JsonUtil.toString(n), StandardCharsets.UTF_8, builder); } } else { UrlEncoded.encodeInto(key, StandardCharsets.UTF_8, builder); builder.append('='); UrlEncoded.encodeInto(JsonUtil.toString(jsonNode), StandardCharsets.UTF_8, builder); } builder.append('&'); } while (fields.hasNext()); builder.setLength(builder.length() - 1); uri = builder.toString(); } } else if (StringUtils.isNotEmpty(query)) { uri = uri + '?' + query; } exchange.setUri(uri); } private class ProxyFunc implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) {
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); builder.append('='); UrlEncoded.encodeInto(JsonUtil.toString(n), StandardCharsets.UTF_8, builder); } } else { UrlEncoded.encodeInto(key, StandardCharsets.UTF_8, builder); builder.append('='); UrlEncoded.encodeInto(JsonUtil.toString(jsonNode), StandardCharsets.UTF_8, builder); } builder.append('&'); } while (fields.hasNext()); builder.setLength(builder.length() - 1); uri = builder.toString(); } } else if (StringUtils.isNotEmpty(query)) { uri = uri + '?' + query; } exchange.setUri(uri); } private class ProxyFunc implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) {
HttpExchange httpExchange = HttpDynamicFunc.httpExchange(context);
1
2023-12-08 15:18:05+00:00
24k
netty/netty-incubator-codec-ohttp
codec-ohttp/src/test/java/io/netty/incubator/codec/ohttp/OHttpCodecsTest.java
[ { "identifier": "BinaryHttpRequest", "path": "codec-bhttp/src/main/java/io/netty/incubator/codec/bhttp/BinaryHttpRequest.java", "snippet": "public interface BinaryHttpRequest extends HttpRequest {\n\n /**\n * Returns the scheme used.\n *\n * @return scheme.\n */\n String scheme();\...
import io.netty.incubator.codec.bhttp.BinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultBinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultBinaryHttpResponse; import io.netty.incubator.codec.bhttp.DefaultFullBinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultFullBinaryHttpResponse; import io.netty.incubator.codec.bhttp.FullBinaryHttpRequest; import io.netty.incubator.codec.hpke.AEAD; import io.netty.incubator.codec.hpke.AsymmetricCipherKeyPair; import io.netty.incubator.codec.hpke.AsymmetricKeyParameter; import io.netty.incubator.codec.hpke.KDF; import io.netty.incubator.codec.hpke.KEM; import io.netty.incubator.codec.hpke.OHttpCryptoProvider; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.socket.ChannelInputShutdownEvent; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.logging.LoggingHandler; import io.netty.incubator.codec.hpke.boringssl.BoringSSLHPKE; import io.netty.incubator.codec.hpke.boringssl.BoringSSLOHttpCryptoProvider; import io.netty.incubator.codec.hpke.bouncycastle.BouncyCastleOHttpCryptoProvider; import io.netty.util.ReferenceCountUtil; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import java.nio.charset.StandardCharsets; import java.security.Security; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue;
14,455
"foo.bar", "/test", strToBuf("THIS IS MY BODY"))), Arrays.asList(new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "/test"), new DefaultHttpContent(strToBuf("THIS IS MY BODY")), new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER)) ); testTransferFlow(server, client, false, Collections.singletonList(new DefaultFullBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, strToBuf("RESPONSE"))), Arrays.asList(new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("RESPONSE")), new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER)) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); } @ParameterizedTest @ArgumentsSource(value = OHttpVersionArgumentsProvider.class) void testContentChunked(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { assumeTrue(version != OHttpVersionDraft.INSTANCE); ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Arrays.asList(newRequestWithHeaders("test", true), new DefaultHttpContent(strToBuf("111"))), Arrays.asList(newRequestWithHeaders("test", true), new DefaultHttpContent(strToBuf("111"))) ); testTransferFlow(client, server, false, Collections.singletonList(new DefaultHttpContent(strToBuf("222"))), Collections.singletonList(new DefaultHttpContent(strToBuf("222"))) ); testTransferFlow(client, server, true, Collections.singletonList(new DefaultHttpContent(strToBuf("333"))), Collections.singletonList(new DefaultHttpContent(strToBuf("333"))) ); testTransferFlow(server, client, false, Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("444"))), Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("444"))) ); testTransferFlow(server, client, false, Collections.singletonList(new DefaultHttpContent(strToBuf("555"))), Collections.singletonList(new DefaultHttpContent(strToBuf("555"))) ); testTransferFlow(server, client, true, Collections.singletonList(new DefaultHttpContent(strToBuf("666"))), Collections.singletonList(new DefaultHttpContent(strToBuf("666"))) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); } @ParameterizedTest @ArgumentsSource(value = OHttpVersionArgumentsProvider.class) void testCodec(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Collections.singletonList(newFullRequestWithHeaders("/test", strToBuf("request body"))), Arrays.asList(newRequestWithHeaders("/test", false), new DefaultHttpContent(strToBuf("request body")), new DefaultLastHttpContent())); testTransferFlow(server, client, false, Collections.singletonList(new DefaultFullBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, strToBuf("response body"))), Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("response body")), new DefaultLastHttpContent()) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); } public static BinaryHttpRequest newRequestWithHeaders(String path, boolean chunked) { BinaryHttpRequest httpRequest = new DefaultBinaryHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "https", "foo.bar", path); HttpUtil.setTransferEncodingChunked(httpRequest, chunked); return httpRequest; }
/* * Copyright 2023 The Netty Project * * The Netty Project 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: * * 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 io.netty.incubator.codec.ohttp; public class OHttpCodecsTest { private static final class OHttpVersionArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); if (BoringSSLHPKE.isAvailable()) { arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); } return arguments.stream(); } } @BeforeAll public static void setupAll() { System.setProperty("io.netty.leakDetection.level", "paranoid"); Security.addProvider(new BouncyCastleProvider()); } private static void transfer(EmbeddedChannel writer, EmbeddedChannel reader) { for (;;) { ByteBuf buffer = writer.readOutbound(); if (buffer == null) { break; } reader.writeInbound(buffer); } } public interface ChannelPair { EmbeddedChannel client(); EmbeddedChannel server(); } public static ChannelPair createChannelPair(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { AsymmetricCipherKeyPair kpR = OHttpCryptoTest.createX25519KeyPair(serverProvider, "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a"); byte keyId = 0x66; OHttpServerKeys serverKeys = new OHttpServerKeys( OHttpKey.newPrivateKey( keyId, KEM.X25519_SHA256, Arrays.asList( OHttpKey.newCipher(KDF.HKDF_SHA256, AEAD.AES_GCM128), OHttpKey.newCipher(KDF.HKDF_SHA256, AEAD.CHACHA20_POLY1305)), kpR)); OHttpCiphersuite ciphersuite = new OHttpCiphersuite(keyId, KEM.X25519_SHA256, KDF.HKDF_SHA256, AEAD.AES_GCM128); AsymmetricKeyParameter publicKey = clientProvider.deserializePublicKey( KEM.X25519_SHA256, kpR.publicParameters().encoded()); return new ChannelPair() { @Override public EmbeddedChannel client() { return createClientChannel(version, clientProvider, ciphersuite, publicKey); } @Override public EmbeddedChannel server() { return createServerChannel(serverProvider, serverKeys); } }; } private static EmbeddedChannel createClientChannel(OHttpVersion version, OHttpCryptoProvider cryptoProvider, OHttpCiphersuite ciphersuite, AsymmetricKeyParameter publicKey) { return new EmbeddedChannel( new LoggingHandler("CLIENT-RAW"), new HttpClientCodec(), new LoggingHandler("CLIENT-OUTER"), new OHttpClientCodec(cryptoProvider, __ -> OHttpClientCodec.EncapsulationParameters.newInstance(version, ciphersuite, publicKey, "/ohttp", "autority")), new LoggingHandler("CLIENT-INNER")); } private static EmbeddedChannel createServerChannel(OHttpCryptoProvider cryptoProvider, OHttpServerKeys keys) { return new EmbeddedChannel( new LoggingHandler("SERVER-RAW"), new HttpServerCodec(), new LoggingHandler("SERVER-OUTER"), new OHttpServerCodec(cryptoProvider, keys), new LoggingHandler("SERVER-INNER")); } public static void testTransferFlow(EmbeddedChannel sender, EmbeddedChannel receiver, boolean shutdownReceiverInput, List<HttpObject> sentPieces, List<HttpObject> expectedReceivedPieces) { for (HttpObject obj : sentPieces) { sender.writeOutbound(obj); } transfer(sender, receiver); if (shutdownReceiverInput) { receiver.pipeline().fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE); } for (HttpObject expected : expectedReceivedPieces) { HttpObject received = receiver.readInbound(); assertNotNull(received); assertEquals(expected, received); if (expected instanceof HttpContent) { assertEquals(((HttpContent) expected).content(), ((HttpContent) received).content()); } ReferenceCountUtil.release(expected); ReferenceCountUtil.release(received); } assertTrue(receiver.inboundMessages().isEmpty()); assertTrue(receiver.outboundMessages().isEmpty()); } public static ByteBuf strToBuf(String str) { return Unpooled.directBuffer().writeBytes(str.getBytes(StandardCharsets.US_ASCII)); } @ParameterizedTest @ArgumentsSource(value = OHttpVersionArgumentsProvider.class) void testContent(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Collections.singletonList(new DefaultFullBinaryHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "https", "foo.bar", "/test", strToBuf("THIS IS MY BODY"))), Arrays.asList(new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "/test"), new DefaultHttpContent(strToBuf("THIS IS MY BODY")), new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER)) ); testTransferFlow(server, client, false, Collections.singletonList(new DefaultFullBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, strToBuf("RESPONSE"))), Arrays.asList(new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("RESPONSE")), new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER)) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); } @ParameterizedTest @ArgumentsSource(value = OHttpVersionArgumentsProvider.class) void testContentChunked(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { assumeTrue(version != OHttpVersionDraft.INSTANCE); ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Arrays.asList(newRequestWithHeaders("test", true), new DefaultHttpContent(strToBuf("111"))), Arrays.asList(newRequestWithHeaders("test", true), new DefaultHttpContent(strToBuf("111"))) ); testTransferFlow(client, server, false, Collections.singletonList(new DefaultHttpContent(strToBuf("222"))), Collections.singletonList(new DefaultHttpContent(strToBuf("222"))) ); testTransferFlow(client, server, true, Collections.singletonList(new DefaultHttpContent(strToBuf("333"))), Collections.singletonList(new DefaultHttpContent(strToBuf("333"))) ); testTransferFlow(server, client, false, Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("444"))), Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("444"))) ); testTransferFlow(server, client, false, Collections.singletonList(new DefaultHttpContent(strToBuf("555"))), Collections.singletonList(new DefaultHttpContent(strToBuf("555"))) ); testTransferFlow(server, client, true, Collections.singletonList(new DefaultHttpContent(strToBuf("666"))), Collections.singletonList(new DefaultHttpContent(strToBuf("666"))) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); } @ParameterizedTest @ArgumentsSource(value = OHttpVersionArgumentsProvider.class) void testCodec(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Collections.singletonList(newFullRequestWithHeaders("/test", strToBuf("request body"))), Arrays.asList(newRequestWithHeaders("/test", false), new DefaultHttpContent(strToBuf("request body")), new DefaultLastHttpContent())); testTransferFlow(server, client, false, Collections.singletonList(new DefaultFullBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, strToBuf("response body"))), Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("response body")), new DefaultLastHttpContent()) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); } public static BinaryHttpRequest newRequestWithHeaders(String path, boolean chunked) { BinaryHttpRequest httpRequest = new DefaultBinaryHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "https", "foo.bar", path); HttpUtil.setTransferEncodingChunked(httpRequest, chunked); return httpRequest; }
private static FullBinaryHttpRequest newFullRequestWithHeaders(String path, ByteBuf content) {
5
2023-12-06 09:14:09+00:00
24k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/tag/id3/ID3v1Tag.java
[ { "identifier": "StandardCharsets", "path": "android/src/main/java/org/jaudiotagger/StandardCharsets.java", "snippet": "public final class StandardCharsets {\n\n private StandardCharsets() {\n throw new AssertionError(\"No org.jaudiotagger.StandardCharsets instances for you!\");\n }\n /*...
import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import org.jaudiotagger.StandardCharsets; import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.logging.ErrorMessage; import org.jaudiotagger.tag.*; import org.jaudiotagger.tag.images.Artwork; import org.jaudiotagger.tag.reference.GenreTypes;
17,640
} this.album = convertedTag.album; this.artist = convertedTag.artist; this.comment = convertedTag.comment; this.title = convertedTag.title; this.year = convertedTag.year; this.genre = convertedTag.genre; } } /** * Creates a new ID3v1 datatype. * * @param file * @param loggingFilename * @throws TagNotFoundException * @throws IOException */ public ID3v1Tag(RandomAccessFile file, String loggingFilename) throws TagNotFoundException, IOException { setLoggingFilename(loggingFilename); FileChannel fc; ByteBuffer byteBuffer; fc = file.getChannel(); fc.position(file.length() - TAG_LENGTH); byteBuffer = ByteBuffer.allocate(TAG_LENGTH); fc.read(byteBuffer); byteBuffer.flip(); read(byteBuffer); } /** * Creates a new ID3v1 datatype. * * @param file * @throws TagNotFoundException * @throws IOException * @deprecated use {@link #ID3v1Tag(RandomAccessFile,String)} instead */ public ID3v1Tag(RandomAccessFile file) throws TagNotFoundException, IOException { this(file, ""); } public void addField(TagField field) { //TODO } /** * Maps the generic key to the ogg key and return the list of values for this field as strings * * @param genericKey * @return * @throws KeyNotFoundException */ public List<String> getAll(FieldKey genericKey) throws KeyNotFoundException { List<String> list = new ArrayList<String>(); list.add(getFirst(genericKey.name())); return list; } public List<TagField> getFields(String id) { if (FieldKey.ARTIST.name().equals(id)) { return getArtist(); } else if (FieldKey.ALBUM.name().equals(id)) { return getAlbum(); } else if (FieldKey.TITLE.name().equals(id)) { return getTitle(); } else if (FieldKey.GENRE.name().equals(id)) { return getGenre(); } else if (FieldKey.YEAR.name().equals(id)) { return getYear(); } else if (FieldKey.COMMENT.name().equals(id)) { return getComment(); } return new ArrayList<TagField>(); } public int getFieldCount() { return 6; } public int getFieldCountIncludingSubValues() { return getFieldCount(); } protected List<TagField> returnFieldToList(ID3v1TagField field) { List<TagField> fields = new ArrayList<TagField>(); fields.add(field); return fields; } /** * Set Album * * @param album */ public void setAlbum(String album) { if (album == null) {
/** * @author : Paul Taylor * @author : Eric Farng * * Version @version:$Id$ * * 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 * * Description: * */ package org.jaudiotagger.tag.id3; /** * Represents an ID3v1 tag. * * @author : Eric Farng * @author : Paul Taylor */ public class ID3v1Tag extends AbstractID3v1Tag implements Tag { static EnumMap<FieldKey, ID3v1FieldKey> tagFieldToID3v1Field = new EnumMap<FieldKey, ID3v1FieldKey>(FieldKey.class); static { tagFieldToID3v1Field.put(FieldKey.ARTIST, ID3v1FieldKey.ARTIST); tagFieldToID3v1Field.put(FieldKey.ALBUM, ID3v1FieldKey.ALBUM); tagFieldToID3v1Field.put(FieldKey.TITLE, ID3v1FieldKey.TITLE); tagFieldToID3v1Field.put(FieldKey.TRACK, ID3v1FieldKey.TRACK); tagFieldToID3v1Field.put(FieldKey.YEAR, ID3v1FieldKey.YEAR); tagFieldToID3v1Field.put(FieldKey.GENRE, ID3v1FieldKey.GENRE); tagFieldToID3v1Field.put(FieldKey.COMMENT, ID3v1FieldKey.COMMENT); } //For writing output protected static final String TYPE_COMMENT = "comment"; protected static final int FIELD_COMMENT_LENGTH = 30; protected static final int FIELD_COMMENT_POS = 97; protected static final int BYTE_TO_UNSIGNED = 0xff; protected static final int GENRE_UNDEFINED = 0xff; /** * */ protected String album = ""; /** * */ protected String artist = ""; /** * */ protected String comment = ""; /** * */ protected String title = ""; /** * */ protected String year = ""; /** * */ protected byte genre = (byte) -1; private static final byte RELEASE = 1; private static final byte MAJOR_VERSION = 0; private static final byte REVISION = 0; /** * Retrieve the Release */ public byte getRelease() { return RELEASE; } /** * Retrieve the Major Version */ public byte getMajorVersion() { return MAJOR_VERSION; } /** * Retrieve the Revision */ public byte getRevision() { return REVISION; } /** * Creates a new ID3v1 datatype. */ public ID3v1Tag() { } public ID3v1Tag(ID3v1Tag copyObject) { super(copyObject); this.album = copyObject.album; this.artist = copyObject.artist; this.comment = copyObject.comment; this.title = copyObject.title; this.year = copyObject.year; this.genre = copyObject.genre; } public ID3v1Tag(AbstractTag mp3tag) { if (mp3tag != null) { ID3v11Tag convertedTag; if (mp3tag instanceof ID3v1Tag) { throw new UnsupportedOperationException("Copy Constructor not called. Please type cast the argument"); } if (mp3tag instanceof ID3v11Tag) { convertedTag = (ID3v11Tag) mp3tag; } else { convertedTag = new ID3v11Tag(mp3tag); } this.album = convertedTag.album; this.artist = convertedTag.artist; this.comment = convertedTag.comment; this.title = convertedTag.title; this.year = convertedTag.year; this.genre = convertedTag.genre; } } /** * Creates a new ID3v1 datatype. * * @param file * @param loggingFilename * @throws TagNotFoundException * @throws IOException */ public ID3v1Tag(RandomAccessFile file, String loggingFilename) throws TagNotFoundException, IOException { setLoggingFilename(loggingFilename); FileChannel fc; ByteBuffer byteBuffer; fc = file.getChannel(); fc.position(file.length() - TAG_LENGTH); byteBuffer = ByteBuffer.allocate(TAG_LENGTH); fc.read(byteBuffer); byteBuffer.flip(); read(byteBuffer); } /** * Creates a new ID3v1 datatype. * * @param file * @throws TagNotFoundException * @throws IOException * @deprecated use {@link #ID3v1Tag(RandomAccessFile,String)} instead */ public ID3v1Tag(RandomAccessFile file) throws TagNotFoundException, IOException { this(file, ""); } public void addField(TagField field) { //TODO } /** * Maps the generic key to the ogg key and return the list of values for this field as strings * * @param genericKey * @return * @throws KeyNotFoundException */ public List<String> getAll(FieldKey genericKey) throws KeyNotFoundException { List<String> list = new ArrayList<String>(); list.add(getFirst(genericKey.name())); return list; } public List<TagField> getFields(String id) { if (FieldKey.ARTIST.name().equals(id)) { return getArtist(); } else if (FieldKey.ALBUM.name().equals(id)) { return getAlbum(); } else if (FieldKey.TITLE.name().equals(id)) { return getTitle(); } else if (FieldKey.GENRE.name().equals(id)) { return getGenre(); } else if (FieldKey.YEAR.name().equals(id)) { return getYear(); } else if (FieldKey.COMMENT.name().equals(id)) { return getComment(); } return new ArrayList<TagField>(); } public int getFieldCount() { return 6; } public int getFieldCountIncludingSubValues() { return getFieldCount(); } protected List<TagField> returnFieldToList(ID3v1TagField field) { List<TagField> fields = new ArrayList<TagField>(); fields.add(field); return fields; } /** * Set Album * * @param album */ public void setAlbum(String album) { if (album == null) {
throw new IllegalArgumentException(ErrorMessage.GENERAL_INVALID_NULL_ARGUMENT.getMsg());
2
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;
19,415
return entity.getUserName(); } /** * 根据id修改 * * @param request {@link SysUserBaseAddUpdate} */ @Override @Transactional(rollbackFor = Exception.class) public String update(SysUserBaseAddUpdate request) { String userId = request.getSysUser().getId(); SysUserDO sysUserDO = sysUserMapper.selectOne(SysUserDO::getId, userId).orElse(null); if (Objects.isNull(sysUserDO)) { Assert.fail("修改的对象不存在"); } SysUserProfileDO sysUserProfileDO = sysUserProfileConvert.toDO(request.getProfile()); sysUserProfileDO.setUserId(userId); SysUserProfileDO dbSysUserProfileDO = sysUserProfileMapper.selectOne(SysUserProfileDO::getUserId, userId).orElse(null); if (Objects.nonNull(dbSysUserProfileDO)) { sysUserProfileDO.setId(dbSysUserProfileDO.getId()); sysUserProfileMapper.updateById(sysUserProfileDO); } else { sysUserProfileMapper.insert(sysUserProfileDO); } redisService.delete(RedisKeyTool.createNameTemplate("user:profile:info:{}", sysUserDO.getUserName())); sysUserMapper.updateById(sysUserConvert.toDO(request.getSysUser())); return sysUserDO.getUserName(); } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) { List<SysUserDO> sysUserDOS = sysUserMapper.selectBatchIds(ids); SysUserDO sysUserDO = sysUserDOS.stream().filter(item -> Objects.equals(UserTypeEnums.ADMIN.getValue(), item.getUserType())).findFirst().orElse(null); Assert.isFalse(Objects.nonNull(sysUserDO), "权限不足禁止删除!"); Set<String> collect = sysUserDOS.stream().map(item -> RedisKeyTool.createNameTemplate("user:profile:info:{}", item.getUserName())).collect(Collectors.toSet()); redisService.delete(collect); sysUserMapper.deleteBatchIds(ids); } /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link SysUserResponse} */ @Override public SysUserVo findById(String id) { SysUserVo result = new SysUserVo(); SysUserProfileResponse sysUserProfileResponse = null; SysUserResponse sysUserResponse = sysUserConvert.toResponse(sysUserMapper.findById(id).orElse(null)); if (Objects.nonNull(sysUserResponse)) { sysUserProfileResponse = sysUserProfileConvert.toResponse(sysUserProfileMapper.selectOne(SysUserProfileDO::getUserId, sysUserResponse.getId()).orElse(new SysUserProfileDO())); } result.setSysUser(sysUserResponse); result.setProfile(sysUserProfileResponse); return result; } /** * 分页查询 * * @param queryRequest {@link SysUserQueryRequest} * @return {@link PageResponse<SysUserResponse>} 分页详情 */ @Override public PageResponse<SysUserResponse> findPage(SysUserQueryRequest queryRequest) { LambdaQueryWrapper<SysUserDO> lambdaQuery = SysUserWrapper.getInstance().lambdaQuery(sysUserConvert.toDO(queryRequest)); dataScopeFactory.getDataScopeHandler(DataScopeTypeEnums.DEPT_USER_TYPE).execute(DataScopeFieldBuilder.<SysUserDO>builder() .deptField(SysUserDO::getDeptId) .userField(SysUserDO::getId) .build(), lambdaQuery); if (!CollectionUtils.isEmpty(queryRequest.getUserIds())) { lambdaQuery.in(SysUserDO::getId, queryRequest.getUserIds()); } IPage<SysUserDO> sysUserIPage = sysUserMapper.selectPage(PageTool.getPage(queryRequest), lambdaQuery); return sysUserConvert.toPageResponse(sysUserIPage); } /** * 根据userName查询详细 * * @param userName {@link String} 用户名称 * @return {@link SysUserVo} */ @Override public SysUserVo findByUserName(String userName) { return redisService.getKey(RedisKeyTool.createNameTemplate("user:profile:info:{}", userName), RandomUtil.randomInt(30, 60), TimeUnit.MINUTES, () -> { SysUserVo sysUserVo = new SysUserVo(); SysUserDO sysUserDO = sysUserMapper.selectOne(SysUserDO::getUserName, userName).orElse(null); Assert.notNull(sysUserDO, String.format("账号`%s`不存在", userName)); assert sysUserDO != null; String userId = sysUserDO.getId(); sysUserVo.setSysUser(sysUserConvert.toResponse(sysUserDO)); sysUserVo.setProfile(sysUserProfileConvert.toResponse(sysUserProfileMapper.selectOne(SysUserProfileDO::getUserId, userId).orElse(null))); List<SysRoleDO> sysRoleDOS = sysRoleMapper.selectListByUserId(userId); if (!CollectionUtils.isEmpty(sysRoleDOS)) { sysUserVo.setRoleCode(sysRoleDOS.stream().map(SysRoleDO::getRoleCode).collect(Collectors.toSet())); sysUserVo.setDataScope(sysRoleDOS.stream().map(item -> item.getDataScope().getValue()).min(Comparator.comparingInt(o -> o)).orElse(null)); } List<SysMenuDO> sysMenuDOS; if (SecurityContextUtil.isAdmin()) { sysMenuDOS = sysMenuMapper.selectListIn(SysMenuDO::getMenuType, Arrays.stream(MenuTypeEnums.values()).map(MenuTypeEnums::getValue).toList()); } else { sysMenuDOS = sysMenuMapper.selectByUserIdAndMenuType(sysUserDO.getId(), Arrays.stream(MenuTypeEnums.values()).map(MenuTypeEnums::getValue).toList()); } if (!CollectionUtils.isEmpty(sysMenuDOS)) { sysUserVo.setAuthorities(sysMenuDOS.stream().filter(Objects::nonNull).map(SysMenuDO::getMenuAuthority).filter(StringUtils::hasText).collect(Collectors.toSet())); } if (Objects.nonNull(sysUserDO.getDeptId())) { if (Objects.equals(CommonConstants.TREE_DEFAULT, sysUserDO.getDeptId())) { SysDeptResponse deptResponse = getDeptResponse(); sysUserVo.setDept(deptResponse); } else {
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; /** * 创建 * * @param request {@link SysUserBaseAddUpdate} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysUserBaseAddUpdate request) { SysUserDO entity = sysUserConvert.toDO(request.getSysUser()); entity.setUserName("CS" + RandomUtil.randomNumbers(5)); String randomGenerator = new RandomGenerator(6).generate(); entity.setPassWord(passwordEncoder.encode(String.format("123456%s", randomGenerator))); entity.setPassWordSalt(randomGenerator); entity.setIsActive("1"); entity.setIsLock("1"); entity.setIsAdmin("0"); entity.setUserType("1"); entity.setRegisteredTime(LocalDateTime.now()); SysUserProfileRequest profile = request.getProfile(); if (Objects.isNull(profile)) { profile = new SysUserProfileRequest(); } SysUserProfileDO sysUserProfileDO = sysUserProfileConvert.toDO(profile); sysUserMapper.insert(entity); sysUserProfileDO.setUserId(entity.getId()); sysUserProfileMapper.insert(sysUserProfileDO); return entity.getUserName(); } /** * 根据id修改 * * @param request {@link SysUserBaseAddUpdate} */ @Override @Transactional(rollbackFor = Exception.class) public String update(SysUserBaseAddUpdate request) { String userId = request.getSysUser().getId(); SysUserDO sysUserDO = sysUserMapper.selectOne(SysUserDO::getId, userId).orElse(null); if (Objects.isNull(sysUserDO)) { Assert.fail("修改的对象不存在"); } SysUserProfileDO sysUserProfileDO = sysUserProfileConvert.toDO(request.getProfile()); sysUserProfileDO.setUserId(userId); SysUserProfileDO dbSysUserProfileDO = sysUserProfileMapper.selectOne(SysUserProfileDO::getUserId, userId).orElse(null); if (Objects.nonNull(dbSysUserProfileDO)) { sysUserProfileDO.setId(dbSysUserProfileDO.getId()); sysUserProfileMapper.updateById(sysUserProfileDO); } else { sysUserProfileMapper.insert(sysUserProfileDO); } redisService.delete(RedisKeyTool.createNameTemplate("user:profile:info:{}", sysUserDO.getUserName())); sysUserMapper.updateById(sysUserConvert.toDO(request.getSysUser())); return sysUserDO.getUserName(); } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) { List<SysUserDO> sysUserDOS = sysUserMapper.selectBatchIds(ids); SysUserDO sysUserDO = sysUserDOS.stream().filter(item -> Objects.equals(UserTypeEnums.ADMIN.getValue(), item.getUserType())).findFirst().orElse(null); Assert.isFalse(Objects.nonNull(sysUserDO), "权限不足禁止删除!"); Set<String> collect = sysUserDOS.stream().map(item -> RedisKeyTool.createNameTemplate("user:profile:info:{}", item.getUserName())).collect(Collectors.toSet()); redisService.delete(collect); sysUserMapper.deleteBatchIds(ids); } /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link SysUserResponse} */ @Override public SysUserVo findById(String id) { SysUserVo result = new SysUserVo(); SysUserProfileResponse sysUserProfileResponse = null; SysUserResponse sysUserResponse = sysUserConvert.toResponse(sysUserMapper.findById(id).orElse(null)); if (Objects.nonNull(sysUserResponse)) { sysUserProfileResponse = sysUserProfileConvert.toResponse(sysUserProfileMapper.selectOne(SysUserProfileDO::getUserId, sysUserResponse.getId()).orElse(new SysUserProfileDO())); } result.setSysUser(sysUserResponse); result.setProfile(sysUserProfileResponse); return result; } /** * 分页查询 * * @param queryRequest {@link SysUserQueryRequest} * @return {@link PageResponse<SysUserResponse>} 分页详情 */ @Override public PageResponse<SysUserResponse> findPage(SysUserQueryRequest queryRequest) { LambdaQueryWrapper<SysUserDO> lambdaQuery = SysUserWrapper.getInstance().lambdaQuery(sysUserConvert.toDO(queryRequest)); dataScopeFactory.getDataScopeHandler(DataScopeTypeEnums.DEPT_USER_TYPE).execute(DataScopeFieldBuilder.<SysUserDO>builder() .deptField(SysUserDO::getDeptId) .userField(SysUserDO::getId) .build(), lambdaQuery); if (!CollectionUtils.isEmpty(queryRequest.getUserIds())) { lambdaQuery.in(SysUserDO::getId, queryRequest.getUserIds()); } IPage<SysUserDO> sysUserIPage = sysUserMapper.selectPage(PageTool.getPage(queryRequest), lambdaQuery); return sysUserConvert.toPageResponse(sysUserIPage); } /** * 根据userName查询详细 * * @param userName {@link String} 用户名称 * @return {@link SysUserVo} */ @Override public SysUserVo findByUserName(String userName) { return redisService.getKey(RedisKeyTool.createNameTemplate("user:profile:info:{}", userName), RandomUtil.randomInt(30, 60), TimeUnit.MINUTES, () -> { SysUserVo sysUserVo = new SysUserVo(); SysUserDO sysUserDO = sysUserMapper.selectOne(SysUserDO::getUserName, userName).orElse(null); Assert.notNull(sysUserDO, String.format("账号`%s`不存在", userName)); assert sysUserDO != null; String userId = sysUserDO.getId(); sysUserVo.setSysUser(sysUserConvert.toResponse(sysUserDO)); sysUserVo.setProfile(sysUserProfileConvert.toResponse(sysUserProfileMapper.selectOne(SysUserProfileDO::getUserId, userId).orElse(null))); List<SysRoleDO> sysRoleDOS = sysRoleMapper.selectListByUserId(userId); if (!CollectionUtils.isEmpty(sysRoleDOS)) { sysUserVo.setRoleCode(sysRoleDOS.stream().map(SysRoleDO::getRoleCode).collect(Collectors.toSet())); sysUserVo.setDataScope(sysRoleDOS.stream().map(item -> item.getDataScope().getValue()).min(Comparator.comparingInt(o -> o)).orElse(null)); } List<SysMenuDO> sysMenuDOS; if (SecurityContextUtil.isAdmin()) { sysMenuDOS = sysMenuMapper.selectListIn(SysMenuDO::getMenuType, Arrays.stream(MenuTypeEnums.values()).map(MenuTypeEnums::getValue).toList()); } else { sysMenuDOS = sysMenuMapper.selectByUserIdAndMenuType(sysUserDO.getId(), Arrays.stream(MenuTypeEnums.values()).map(MenuTypeEnums::getValue).toList()); } if (!CollectionUtils.isEmpty(sysMenuDOS)) { sysUserVo.setAuthorities(sysMenuDOS.stream().filter(Objects::nonNull).map(SysMenuDO::getMenuAuthority).filter(StringUtils::hasText).collect(Collectors.toSet())); } if (Objects.nonNull(sysUserDO.getDeptId())) { if (Objects.equals(CommonConstants.TREE_DEFAULT, sysUserDO.getDeptId())) { SysDeptResponse deptResponse = getDeptResponse(); sysUserVo.setDept(deptResponse); } else {
SysDeptDO sysDeptDO = sysDeptMapper.selectById(sysUserDO.getDeptId());
17
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,107
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetFriendRecommendListInfoCsReq) public class HandlerGetFriendRecommendListInfoCsReq extends PacketHandler { @Override public void handle(GameSession session, byte[] data) throws Exception { var list = session.getServer().getRandomOnlinePlayers(10, session.getPlayer());
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetFriendRecommendListInfoCsReq) public class HandlerGetFriendRecommendListInfoCsReq extends PacketHandler { @Override public void handle(GameSession session, byte[] data) throws Exception { var list = session.getServer().getRandomOnlinePlayers(10, session.getPlayer());
session.send(new PacketGetFriendRecommendListInfoScRsp(list));
3
2023-12-08 14:13:04+00:00
24k
quentin452/Garden-Stuff-Continuation
src/main/resources/com/jaquadro/minecraft/gardencontainers/client/renderer/MediumPotRenderer.java
[ { "identifier": "BlockMediumPot", "path": "src/main/java/com/jaquadro/minecraft/gardencontainers/block/BlockMediumPot.java", "snippet": "public abstract class BlockMediumPot extends BlockGardenContainer implements IChainAttachable {\n\n private static final Vec3[] chainAttachPoints = new Vec3[] { Vec...
import com.jaquadro.minecraft.gardencontainers.block.BlockMediumPot; import com.jaquadro.minecraft.gardencontainers.block.tile.TileEntityMediumPot; import com.jaquadro.minecraft.gardencontainers.core.ClientProxy; import com.jaquadro.minecraft.gardencore.client.renderer.support.ModularBoxRenderer; import com.jaquadro.minecraft.gardencore.util.RenderHelper; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; import net.minecraft.util.IIcon; import net.minecraft.world.ColorizerGrass; import net.minecraft.world.IBlockAccess; import org.lwjgl.opengl.GL11;
21,521
package com.jaquadro.minecraft.gardencontainers.client.renderer; public class MediumPotRenderer implements ISimpleBlockRenderingHandler { private ModularBoxRenderer boxRenderer = new ModularBoxRenderer(); private float[] colorScratch = new float[3]; public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { if (block instanceof BlockMediumPot) { this.renderInventoryBlock((BlockMediumPot)block, metadata, modelId, renderer); } } private void renderInventoryBlock(BlockMediumPot block, int metadata, int modelId, RenderBlocks renderer) { IIcon icon = renderer.getBlockIconFromSideAndMetadata(block, 1, metadata & 15); boolean blendEnabled = GL11.glIsEnabled(3042); if (blendEnabled) { GL11.glDisable(3042); } this.boxRenderer.setUnit(0.0625D); this.boxRenderer.setIcon(icon); this.boxRenderer.setColor(ModularBoxRenderer.COLOR_WHITE); GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); this.boxRenderer.renderBox((IBlockAccess)null, block, 0.0D, 0.0D, 0.0D, 0.125D, 0.0D, 0.125D, 0.875D, 0.75D, 0.875D, 0, 2); if (!blendEnabled) { GL11.glDisable(3042); } GL11.glTranslatef(0.5F, 0.5F, 0.5F); } public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { if (!(block instanceof BlockMediumPot)) { return false; } else { try { return this.renderWorldBlockPass0(world, x, y, z, (BlockMediumPot)block, modelId, renderer); } catch (Exception var9) { return false; } } } private boolean renderWorldBlockPass0(IBlockAccess world, int x, int y, int z, BlockMediumPot block, int modelId, RenderBlocks renderer) { int metadata = world.getBlockMetadata(x, y, z); this.boxRenderer.setUnit(0.0625D); this.boxRenderer.setColor(ModularBoxRenderer.COLOR_WHITE); for(int i = 0; i < 6; ++i) { this.boxRenderer.setIcon(renderer.getBlockIconFromSideAndMetadata(block, i, metadata), i); } this.boxRenderer.renderBox(world, block, (double)x, (double)y, (double)z, 0.125D, 0.0D, 0.125D, 0.875D, 0.75D, 0.875D, 0, 2); TileEntityMediumPot te = block.getTileEntity(world, x, y, z); if (te != null && te.getSubstrate() != null && te.getSubstrate().getItem() instanceof ItemBlock) { Block substrate = Block.getBlockFromItem(te.getSubstrate().getItem()); int substrateData = te.getSubstrate().getItemDamage(); if (substrate != Blocks.water) { IIcon substrateIcon = renderer.getBlockIconFromSideAndMetadata(substrate, 1, substrateData); int color = substrate.colorMultiplier(world, x, y, z); if (color == Blocks.grass.colorMultiplier(world, x, y, z)) { color = ColorizerGrass.getGrassColor((double)te.getBiomeTemperature(), (double)te.getBiomeHumidity()); }
package com.jaquadro.minecraft.gardencontainers.client.renderer; public class MediumPotRenderer implements ISimpleBlockRenderingHandler { private ModularBoxRenderer boxRenderer = new ModularBoxRenderer(); private float[] colorScratch = new float[3]; public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { if (block instanceof BlockMediumPot) { this.renderInventoryBlock((BlockMediumPot)block, metadata, modelId, renderer); } } private void renderInventoryBlock(BlockMediumPot block, int metadata, int modelId, RenderBlocks renderer) { IIcon icon = renderer.getBlockIconFromSideAndMetadata(block, 1, metadata & 15); boolean blendEnabled = GL11.glIsEnabled(3042); if (blendEnabled) { GL11.glDisable(3042); } this.boxRenderer.setUnit(0.0625D); this.boxRenderer.setIcon(icon); this.boxRenderer.setColor(ModularBoxRenderer.COLOR_WHITE); GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); this.boxRenderer.renderBox((IBlockAccess)null, block, 0.0D, 0.0D, 0.0D, 0.125D, 0.0D, 0.125D, 0.875D, 0.75D, 0.875D, 0, 2); if (!blendEnabled) { GL11.glDisable(3042); } GL11.glTranslatef(0.5F, 0.5F, 0.5F); } public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { if (!(block instanceof BlockMediumPot)) { return false; } else { try { return this.renderWorldBlockPass0(world, x, y, z, (BlockMediumPot)block, modelId, renderer); } catch (Exception var9) { return false; } } } private boolean renderWorldBlockPass0(IBlockAccess world, int x, int y, int z, BlockMediumPot block, int modelId, RenderBlocks renderer) { int metadata = world.getBlockMetadata(x, y, z); this.boxRenderer.setUnit(0.0625D); this.boxRenderer.setColor(ModularBoxRenderer.COLOR_WHITE); for(int i = 0; i < 6; ++i) { this.boxRenderer.setIcon(renderer.getBlockIconFromSideAndMetadata(block, i, metadata), i); } this.boxRenderer.renderBox(world, block, (double)x, (double)y, (double)z, 0.125D, 0.0D, 0.125D, 0.875D, 0.75D, 0.875D, 0, 2); TileEntityMediumPot te = block.getTileEntity(world, x, y, z); if (te != null && te.getSubstrate() != null && te.getSubstrate().getItem() instanceof ItemBlock) { Block substrate = Block.getBlockFromItem(te.getSubstrate().getItem()); int substrateData = te.getSubstrate().getItemDamage(); if (substrate != Blocks.water) { IIcon substrateIcon = renderer.getBlockIconFromSideAndMetadata(substrate, 1, substrateData); int color = substrate.colorMultiplier(world, x, y, z); if (color == Blocks.grass.colorMultiplier(world, x, y, z)) { color = ColorizerGrass.getGrassColor((double)te.getBiomeTemperature(), (double)te.getBiomeHumidity()); }
RenderHelper.calculateBaseColor(this.colorScratch, color);
4
2023-12-12 08:13:16+00:00
24k