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
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/Speck.java
[ { "identifier": "Assets", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Assets.java", "snippet": "public class Assets {\n\n\tpublic static class Effects {\n\t\tpublic static final String EFFECTS = \"effects/effects.png\";\n\t\tpublic static final String FIREBALL = \"effec...
import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.watabou.noosa.Game; import com.watabou.noosa.Image; import com.watabou.noosa.TextureFilm; import com.watabou.noosa.particles.Emitter; import com.watabou.utils.ColorMath; import com.watabou.utils.PointF; import com.watabou.utils.Random; import com.watabou.utils.SparseArray;
15,810
break; case DUST: hardlight( 0xFFFF66 ); angle = Random.Float( 360 ); speed.polar( Random.Float( 2 * 3.1415926f ), Random.Float( 16, 48 ) ); lifespan = 0.5f; break; case COIN: speed.polar( -PointF.PI * Random.Float( 0.3f, 0.7f ), Random.Float( 48, 96 ) ); acc.y = 256; lifespan = -speed.y / acc.y * 2; break; } left = lifespan; } @Override public void update() { super.update(); left -= Game.elapsed; if (left <= 0) { kill(); } else { float p = 1 - left / lifespan; // 0 -> 1 switch (type) { case STAR: case FORGE: scale.set( 1 - p ); am = p < 0.2f ? p * 5f : (1 - p) * 1.25f; break; case MASK: case CROWN: am = 1 - p * p; break; case EVOKE: case HEALING: am = p < 0.5f ? 1 : 2 - p * 2; break; case RED_LIGHT: case LIGHT: am = scale.set( p < 0.2f ? p * 5f : (1 - p) * 1.25f ).x; break; case DISCOVER: am = 1 - p; scale.set( (p < 0.5f ? p : 1 - p) * 2 ); break; case QUESTION: scale.set( (float)(Math.sqrt( p < 0.5f ? p : 1 - p ) * 3) ); break; case UP: scale.set( (float)(Math.sqrt( p < 0.5f ? p : 1 - p ) * 2) ); break; case CALM: case SCREAM: am = (float)Math.sqrt( (p < 0.5f ? p : 1 - p) * 2f ); scale.set( p * 7 ); break; case BONE: case RATTLE: am = p < 0.9f ? 1 : (1 - p) * 10; break; case ROCK: am = p < 0.2f ? p * 5 : 1 ; break; case NOTE: am = 1 - p * p; break; case WOOL: scale.set( 1 - p ); break; case CHANGE: am = (float)Math.sqrt( (p < 0.5f ? p : 1 - p) * 2); scale.y = (1 + p) * 0.5f; scale.x = scale.y * (float)Math.cos( left * 15 ); break; case HEART: scale.set( 1 - p ); am = 1 - p * p; break; case BUBBLE: am = p < 0.2f ? p * 5 : 1; break; case STEAM: case TOXIC: case PARALYSIS: case CONFUSION: case STORM: case BLIZZARD: case INFERNO: case DUST: am = (float)Math.sqrt( (p < 0.5f ? p : 1 - p) * 0.5f ); scale.set( 1 + p ); break; case CORROSION:
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.effects; public class Speck extends Image { public static final int HEALING = 0; public static final int STAR = 1; public static final int LIGHT = 2; public static final int QUESTION = 3; public static final int UP = 4; public static final int SCREAM = 5; public static final int BONE = 6; public static final int WOOL = 7; public static final int ROCK = 8; public static final int NOTE = 9; public static final int CHANGE = 10; public static final int HEART = 11; public static final int BUBBLE = 12; public static final int STEAM = 13; public static final int COIN = 14; public static final int DISCOVER = 101; public static final int EVOKE = 102; public static final int MASK = 103; public static final int CROWN = 104; public static final int RATTLE = 105; public static final int JET = 106; public static final int TOXIC = 107; public static final int CORROSION = 108; public static final int PARALYSIS = 109; public static final int DUST = 110; public static final int STENCH = 111; public static final int FORGE = 112; public static final int CONFUSION = 113; public static final int RED_LIGHT = 114; public static final int CALM = 115; public static final int SMOKE = 116; public static final int STORM = 117; public static final int INFERNO = 118; public static final int BLIZZARD = 119; private static final int SIZE = 7; private int type; private float lifespan; private float left; private static TextureFilm film; private static SparseArray<Emitter.Factory> factories = new SparseArray<>(); public Speck() { super(); texture( Assets.Effects.SPECKS ); if (film == null) { film = new TextureFilm( texture, SIZE, SIZE ); } origin.set( SIZE / 2f ); } public Speck image( int type ){ reset(0, 0, 0, type); left = lifespan = Float.POSITIVE_INFINITY; this.type = -1; resetColor(); scale.set( 1 ); speed.set( 0 ); acc.set( 0 ); angle = 0; angularSpeed = 0; return this; } public void reset( int index, float x, float y, int type ) { revive(); this.type = type; switch (type) { case DISCOVER: case RED_LIGHT: frame( film.get( LIGHT ) ); break; case EVOKE: case MASK: case CROWN: case FORGE: frame( film.get( STAR ) ); break; case RATTLE: frame( film.get( BONE ) ); break; case JET: case TOXIC: case CORROSION: case PARALYSIS: case STENCH: case CONFUSION: case STORM: case DUST: case SMOKE: case BLIZZARD: case INFERNO: frame( film.get( STEAM ) ); break; case CALM: frame( film.get( SCREAM ) ); break; default: frame( film.get( type ) ); } this.x = x - origin.x; this.y = y - origin.y; resetColor(); scale.set( 1 ); speed.set( 0 ); acc.set( 0 ); angle = 0; angularSpeed = 0; switch (type) { case HEALING: speed.set( 0, -20 ); lifespan = 1f; break; case STAR: speed.polar( Random.Float( 2 * 3.1415926f ), Random.Float( 128 ) ); acc.set( 0, 128 ); angle = Random.Float( 360 ); angularSpeed = Random.Float( -360, +360 ); lifespan = 1f; break; case FORGE: speed.polar( Random.Float( -3.1415926f ), Random.Float( 64 ) ); acc.set( 0, 128 ); angle = Random.Float( 360 ); angularSpeed = Random.Float( -360, +360 ); lifespan = 0.51f; break; case EVOKE: speed.polar( Random.Float( -3.1415926f ), 50 ); acc.set( 0, 50 ); angle = Random.Float( 360 ); angularSpeed = Random.Float( -180, +180 ); lifespan = 1f; break; case MASK: speed.polar( index * 3.1415926f / 5, 50 ); acc.set( -speed.x, -speed.y ); angle = index * 36; angularSpeed = 360; lifespan = 1f; break; case CROWN: acc.set( index % 2 == 0 ? Random.Float( -512, -256 ) : Random.Float( +256, +512 ), 0 ); angularSpeed = acc.x < 0 ? -180 : +180; //acc.set( -speed.x, 0 ); lifespan = 0.5f; break; case RED_LIGHT: tint(0xFFCC0000); case LIGHT: angle = Random.Float( 360 ); angularSpeed = 90; lifespan = 1f; break; case DISCOVER: angle = Random.Float( 360 ); angularSpeed = 90; lifespan = 0.5f; am = 0; break; case QUESTION: lifespan = 0.8f; break; case UP: speed.set( 0, -20 ); lifespan = 1f; break; case CALM: color(0, 1, 1); case SCREAM: lifespan = 0.9f; break; case BONE: lifespan = 0.2f; speed.polar( Random.Float( 2 * 3.1415926f ), 24 / lifespan ); acc.set( 0, 128 ); angle = Random.Float( 360 ); angularSpeed = 360; break; case RATTLE: lifespan = 0.5f; speed.set( 0, -100 ); acc.set( 0, -2 * speed.y / lifespan ); angle = Random.Float( 360 ); angularSpeed = 360; break; case WOOL: lifespan = 0.5f; speed.set( 0, -50 ); angle = Random.Float( 360 ); angularSpeed = Random.Float( -360, +360 ); break; case ROCK: angle = Random.Float( 360 ); angularSpeed = Random.Float( -360, +360 ); scale.set( Random.Float( 1, 2 ) ); speed.set( 0, 64 ); lifespan = 0.2f; this.y -= speed.y * lifespan; break; case NOTE: angularSpeed = Random.Float( -30, +30 ); speed.polar( (angularSpeed - 90) * PointF.G2R, 30 ); lifespan = 1f; break; case CHANGE: angle = Random.Float( 360 ); speed.polar( (angle - 90) * PointF.G2R, Random.Float( 4, 12 ) ); lifespan = 1.5f; break; case HEART: speed.set( Random.IntRange( -10, +10 ), -40 ); angularSpeed = Random.Float( -45, +45 ); lifespan = 1f; break; case BUBBLE: speed.set( 0, -15 ); scale.set( Random.Float( 0.8f, 1 ) ); lifespan = Random.Float( 0.8f, 1.5f ); break; case STEAM: speed.y = -Random.Float( 10, 15 ); angularSpeed = Random.Float( +180 ); angle = Random.Float( 360 ); lifespan = 1f; break; case JET: speed.y = +32; acc.y = -64; angularSpeed = Random.Float( 180, 360 ); angle = Random.Float( 360 ); lifespan = 0.5f; break; case TOXIC: hardlight( 0x50FF60 ); angularSpeed = 30; angle = Random.Float( 360 ); lifespan = Random.Float( 1f, 3f ); break; case CORROSION: hardlight( 0xAAAAAA ); angularSpeed = 30; angle = Random.Float( 360 ); lifespan = Random.Float( 1f, 3f ); break; case PARALYSIS: hardlight( 0xFFFF66 ); angularSpeed = -30; angle = Random.Float( 360 ); lifespan = Random.Float( 1f, 3f ); break; case STENCH: hardlight( 0x003300 ); angularSpeed = -30; angle = Random.Float( 360 ); lifespan = Random.Float( 1f, 3f ); break; case CONFUSION: hardlight( Random.Int( 0x1000000 ) | 0x000080 ); angularSpeed = Random.Float( -20, +20 ); angle = Random.Float( 360 ); lifespan = Random.Float( 1f, 3f ); break; case STORM: hardlight( 0x8AD8D8 ); angularSpeed = Random.Float( -20, +20 ); angle = Random.Float( 360 ); lifespan = Random.Float( 1f, 3f ); break; case INFERNO: hardlight( 0xEE7722 ); angularSpeed = Random.Float( 200, 300 ) * (Random.Int(2) == 0 ? -1 : 1); angle = Random.Float( 360 ); lifespan = Random.Float( 1f, 3f ); break; case BLIZZARD: hardlight( 0xFFFFFF ); angularSpeed = Random.Float( 200, 300 ) * (Random.Int(2) == 0 ? -1 : 1); angle = Random.Float( 360 ); lifespan = Random.Float( 1f, 3f ); break; case SMOKE: hardlight( 0x000000 ); angularSpeed = 30; angle = Random.Float( 360 ); lifespan = Random.Float( 1f, 1.5f ); break; case DUST: hardlight( 0xFFFF66 ); angle = Random.Float( 360 ); speed.polar( Random.Float( 2 * 3.1415926f ), Random.Float( 16, 48 ) ); lifespan = 0.5f; break; case COIN: speed.polar( -PointF.PI * Random.Float( 0.3f, 0.7f ), Random.Float( 48, 96 ) ); acc.y = 256; lifespan = -speed.y / acc.y * 2; break; } left = lifespan; } @Override public void update() { super.update(); left -= Game.elapsed; if (left <= 0) { kill(); } else { float p = 1 - left / lifespan; // 0 -> 1 switch (type) { case STAR: case FORGE: scale.set( 1 - p ); am = p < 0.2f ? p * 5f : (1 - p) * 1.25f; break; case MASK: case CROWN: am = 1 - p * p; break; case EVOKE: case HEALING: am = p < 0.5f ? 1 : 2 - p * 2; break; case RED_LIGHT: case LIGHT: am = scale.set( p < 0.2f ? p * 5f : (1 - p) * 1.25f ).x; break; case DISCOVER: am = 1 - p; scale.set( (p < 0.5f ? p : 1 - p) * 2 ); break; case QUESTION: scale.set( (float)(Math.sqrt( p < 0.5f ? p : 1 - p ) * 3) ); break; case UP: scale.set( (float)(Math.sqrt( p < 0.5f ? p : 1 - p ) * 2) ); break; case CALM: case SCREAM: am = (float)Math.sqrt( (p < 0.5f ? p : 1 - p) * 2f ); scale.set( p * 7 ); break; case BONE: case RATTLE: am = p < 0.9f ? 1 : (1 - p) * 10; break; case ROCK: am = p < 0.2f ? p * 5 : 1 ; break; case NOTE: am = 1 - p * p; break; case WOOL: scale.set( 1 - p ); break; case CHANGE: am = (float)Math.sqrt( (p < 0.5f ? p : 1 - p) * 2); scale.y = (1 + p) * 0.5f; scale.x = scale.y * (float)Math.cos( left * 15 ); break; case HEART: scale.set( 1 - p ); am = 1 - p * p; break; case BUBBLE: am = p < 0.2f ? p * 5 : 1; break; case STEAM: case TOXIC: case PARALYSIS: case CONFUSION: case STORM: case BLIZZARD: case INFERNO: case DUST: am = (float)Math.sqrt( (p < 0.5f ? p : 1 - p) * 0.5f ); scale.set( 1 + p ); break; case CORROSION:
hardlight( ColorMath.interpolate( 0xAAAAAA, 0xFF8800 , p ));
5
2023-11-27 05:56:58+00:00
24k
parttimenerd/hello-ebpf
bcc/src/main/java/me/bechberger/ebpf/samples/chapter2/ex/HelloBufferEvenOdd.java
[ { "identifier": "BPF", "path": "bcc/src/main/java/me/bechberger/ebpf/bcc/BPF.java", "snippet": "public class BPF implements AutoCloseable {\n\n static {\n try {\n System.loadLibrary(\"bcc\");\n } catch (UnsatisfiedLinkError e) {\n try {\n System.load...
import static me.bechberger.ebpf.samples.chapter2.HelloBuffer.DATA_TYPE; import me.bechberger.ebpf.bcc.BPF; import me.bechberger.ebpf.bcc.BPFTable; import me.bechberger.ebpf.samples.chapter2.HelloBuffer;
21,017
/** * HelloBuffer that outputs different trace messages for even and odd process ids */ package me.bechberger.ebpf.samples.chapter2.ex; /** * Also shows how to reuse data types from {@link HelloBuffer} */ public class HelloBufferEvenOdd { public static void main(String[] args) throws InterruptedException { try (var b = BPF.builder(""" BPF_PERF_OUTPUT(output); struct data_t { int pid; int uid; char command[16]; char message[12]; }; int hello(void *ctx) { struct data_t data = {}; char even_message[12] = "Even pid"; char odd_message[12] = "Odd pid"; data.pid = bpf_get_current_pid_tgid() >> 32; data.uid = bpf_get_current_uid_gid() & 0xFFFFFFFF; bpf_get_current_comm(&data.command, sizeof(data.command)); if (data.pid % 2 == 0) { bpf_probe_read_kernel(&data.message, sizeof(data.message), even_message); } else { bpf_probe_read_kernel(&data.message, sizeof(data.message), odd_message); } output.perf_submit(ctx, &data, sizeof(data)); return 0; } """).build()) { var syscall = b.get_syscall_fnname("execve"); b.attach_kprobe(syscall, "hello"); BPFTable.PerfEventArray.EventCallback<HelloBuffer.Data> print_event = (array, cpu, data, size) -> { var d = array.event(data); System.out.printf("%d %d %s %s%n", d.pid(), d.uid(), d.command(), d.message()); };
/** * HelloBuffer that outputs different trace messages for even and odd process ids */ package me.bechberger.ebpf.samples.chapter2.ex; /** * Also shows how to reuse data types from {@link HelloBuffer} */ public class HelloBufferEvenOdd { public static void main(String[] args) throws InterruptedException { try (var b = BPF.builder(""" BPF_PERF_OUTPUT(output); struct data_t { int pid; int uid; char command[16]; char message[12]; }; int hello(void *ctx) { struct data_t data = {}; char even_message[12] = "Even pid"; char odd_message[12] = "Odd pid"; data.pid = bpf_get_current_pid_tgid() >> 32; data.uid = bpf_get_current_uid_gid() & 0xFFFFFFFF; bpf_get_current_comm(&data.command, sizeof(data.command)); if (data.pid % 2 == 0) { bpf_probe_read_kernel(&data.message, sizeof(data.message), even_message); } else { bpf_probe_read_kernel(&data.message, sizeof(data.message), odd_message); } output.perf_submit(ctx, &data, sizeof(data)); return 0; } """).build()) { var syscall = b.get_syscall_fnname("execve"); b.attach_kprobe(syscall, "hello"); BPFTable.PerfEventArray.EventCallback<HelloBuffer.Data> print_event = (array, cpu, data, size) -> { var d = array.event(data); System.out.printf("%d %d %s %s%n", d.pid(), d.uid(), d.command(), d.message()); };
try (var output = b.get("output", BPFTable.PerfEventArray.<HelloBuffer.Data>createProvider(DATA_TYPE)).open_perf_buffer(print_event)) {
3
2023-12-01 20:24:28+00:00
24k
WiIIiam278/HuskClaims
bukkit/src/main/java/net/william278/huskclaims/hook/BukkitGriefPreventionImporter.java
[ { "identifier": "BukkitHuskClaims", "path": "bukkit/src/main/java/net/william278/huskclaims/BukkitHuskClaims.java", "snippet": "@NoArgsConstructor\n@Getter\npublic class BukkitHuskClaims extends JavaPlugin implements HuskClaims, BukkitTask.Supplier, BukkitBlockProvider,\n BukkitEventDispatcher, B...
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import net.william278.huskclaims.BukkitHuskClaims; import net.william278.huskclaims.HuskClaims; import net.william278.huskclaims.claim.Claim; import net.william278.huskclaims.claim.ClaimWorld; import net.william278.huskclaims.claim.Region; import net.william278.huskclaims.trust.TrustLevel; import net.william278.huskclaims.trust.Trustable; import net.william278.huskclaims.user.CommandUser; import net.william278.huskclaims.user.Preferences; import net.william278.huskclaims.user.User; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.stream.IntStream;
16,009
// Get the claim world final Optional<ClaimWorld> optionalWorld = plugin.getClaimWorld(world); if (optionalWorld.isEmpty()) { plugin.log(Level.WARNING, "Skipped claim at %s on missing world %s".formatted(gpc.lesserCorner, world)); return; } final ClaimWorld claimWorld = optionalWorld.get(); // Add the claim world to the list of worlds, then cache the claim owner/trustees claimWorlds.add(claimWorld); hcc.getOwner().flatMap(owner -> users.stream().filter(gpu -> gpu.uuid.equals(owner)).findFirst()) .ifPresent(user -> claimWorld.cacheUser(user.toUser())); hcc.getTrustedUsers().keySet().forEach(u -> users.stream().filter(gpu -> gpu.uuid.equals(u)) .findFirst().ifPresent(user -> claimWorld.cacheUser(user.toUser()))); // Add the claim to either its parent or the claim world if (gpc.isChildClaim()) { allClaims.entrySet().stream() .filter(entry -> entry.getValue().id == gpc.parentId) .map(Map.Entry::getKey).findFirst() .ifPresent(parent -> { parent.getOwner().ifPresent(hcc::setOwner); parent.getChildren().add(hcc); }); } else { claimWorld.getClaims().add(hcc); } if (amount.incrementAndGet() % CLAIMS_PER_PAGE == 0) { log(executor, Level.INFO, "Saved %s claims...".formatted(amount.get())); } }); // Save claim worlds plugin.clearAllMapMarkers(); log(executor, Level.INFO, "Saving %s claim worlds...".formatted(claimWorlds.size())); final List<CompletableFuture<Void>> claimWorldFutures = Lists.newArrayList(); claimWorlds.forEach(claimWorld -> claimWorldFutures.add( CompletableFuture.runAsync(() -> plugin.getDatabase().updateClaimWorld(claimWorld), pool) )); CompletableFuture.allOf(claimWorldFutures.toArray(CompletableFuture[]::new)).join(); plugin.markAllClaims(); return amount.get(); } private int getTotalUsers() { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT COUNT(*) FROM griefprevention_playerdata""")) { final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return resultSet.getInt(1); } } catch (Throwable e) { plugin.log(Level.WARNING, "Exception querying total user count from DB database", e); } return 0; } private int getTotalClaims() { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT COUNT(*) FROM griefprevention_claimdata""")) { final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return resultSet.getInt(1); } } catch (Throwable e) { plugin.log(Level.WARNING, "Exception querying total claim count from DB database", e); } return 0; } private CompletableFuture<List<GriefPreventionClaim>> getClaimPage(int page) { final List<GriefPreventionClaim> claims = Lists.newArrayList(); return CompletableFuture.supplyAsync(() -> { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT * FROM griefprevention_claimdata LIMIT ?, ?;""")) { statement.setInt(1, (page - 1) * CLAIMS_PER_PAGE); statement.setInt(2, CLAIMS_PER_PAGE); final ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { claims.add(new GriefPreventionClaim( resultSet.getInt("id"), resultSet.getString("owner"), resultSet.getString("lessercorner"), resultSet.getString("greatercorner"), parseTrusted(resultSet.getString("builders")), parseTrusted(resultSet.getString("containers")), parseTrusted(resultSet.getString("accessors")), parseTrusted(resultSet.getString("managers")), resultSet.getBoolean("inheritnothing"), resultSet.getInt("parentid") )); } return claims; } catch (Throwable e) { plugin.log(Level.WARNING, "Exception getting claim page #%s from GP database".formatted(page), e); } return claims; }, pool); } @NotNull private List<String> parseTrusted(@NotNull String names) { return Arrays.stream(names.split(";")) .filter(s -> !s.isEmpty()) .toList(); }
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.william278.huskclaims.hook; public class BukkitGriefPreventionImporter extends Importer { // Parameters for the GP database private static final int USERS_PER_PAGE = 500; private static final int CLAIMS_PER_PAGE = 500; private static final String GP_PUBLIC_STRING = "public"; private HikariDataSource dataSource; private ExecutorService pool; private List<GriefPreventionUser> users; public BukkitGriefPreventionImporter(@NotNull BukkitHuskClaims plugin) { super( "GriefPrevention", List.of(ImportData.USERS, ImportData.CLAIMS), plugin, Map.of( "uri", true, "username", true, "password", false ), Map.of( "password", "" ) ); } @Override public void prepare() throws IllegalArgumentException { final String uri = configParameters.get("uri"); final String username = configParameters.get("username"); final String password = configParameters.get("password"); if (uri == null || username == null) { throw new IllegalArgumentException("Missing required config parameters"); } // Setup GriefPrevention database connection final HikariConfig config = new HikariConfig(); config.setJdbcUrl(uri); config.setUsername(username); if (password != null) { config.setPassword(password); } config.setMaximumPoolSize(1); config.setConnectionTimeout(30000); config.setPoolName(String.format("HuskClaims-%s-Importer", getName())); config.setReadOnly(true); this.dataSource = new HikariDataSource(config); this.pool = Executors.newFixedThreadPool(20); } @Override public void finish() { if (dataSource != null) { dataSource.close(); } if (pool != null) { pool.shutdown(); } this.configParameters = Maps.newHashMap(defaultParameters); this.users = Lists.newArrayList(); } @Override protected int importData(@NotNull ImportData importData, @NotNull CommandUser executor) { return switch (importData) { case USERS -> importUsers(); case CLAIMS -> importClaims(executor); }; } private int importUsers() { final int totalUsers = getTotalUsers(); final int totalPages = (int) Math.ceil(totalUsers / (double) USERS_PER_PAGE); final List<CompletableFuture<List<GriefPreventionUser>>> userPages = IntStream.rangeClosed(1, totalPages) .mapToObj(this::getUserPage).toList(); CompletableFuture.allOf(userPages.toArray(CompletableFuture[]::new)).join(); users = Lists.newArrayList(); userPages.stream().map(CompletableFuture::join).forEach(users::addAll); return users.size(); } private int importClaims(@NotNull CommandUser executor) { if (users == null) { throw new IllegalStateException("Users must be imported before claims"); } final int totalClaims = getTotalClaims(); final int totalPages = (int) Math.ceil(totalClaims / (double) CLAIMS_PER_PAGE); final List<CompletableFuture<List<GriefPreventionClaim>>> claimPages = IntStream.rangeClosed(1, totalPages) .mapToObj(this::getClaimPage).toList(); CompletableFuture.allOf(claimPages.toArray(CompletableFuture[]::new)).join(); final List<GriefPreventionClaim> claims = claimPages.stream() .map(CompletableFuture::join) .toList().stream() .flatMap(Collection::stream) .toList(); log(executor, Level.INFO, "Adjusting claim block balances for %s users...".formatted(users.size())); final List<CompletableFuture<Void>> saveFutures = Lists.newArrayList(); final AtomicInteger amount = new AtomicInteger(); users.forEach(user -> { // Update claim blocks final int totalArea = claims.stream() .filter(c -> c.owner.equals(user.uuid.toString())) .mapToInt(c -> { final String[] lesserCorner = c.lesserCorner.split(";"); final String[] greaterCorner = c.greaterCorner.split(";"); int x1 = Integer.parseInt(lesserCorner[1]); int z1 = Integer.parseInt(lesserCorner[3]); int x2 = Integer.parseInt(greaterCorner[1]); int z2 = Integer.parseInt(greaterCorner[3]); int x = Math.abs(x1 - x2) + 1; int z = Math.abs(z1 - z2) + 1; return x * z; }) .sum(); user.claimBlocks = Math.max(0, user.claimBlocks - totalArea); saveFutures.add(CompletableFuture.runAsync( () -> { plugin.getDatabase().createOrUpdateUser( user.uuid, user.name, user.claimBlocks, user.getLastLogin(), Preferences.IMPORTED ); plugin.invalidateClaimListCache(user.uuid); if (amount.incrementAndGet() % USERS_PER_PAGE == 0) { log(executor, Level.INFO, "Adjusted %s users...".formatted(amount.get())); } }, pool )); }); // Wait for all users to be saved CompletableFuture.allOf(saveFutures.toArray(CompletableFuture[]::new)).join(); plugin.invalidateAdminClaimListCache(); // Adding admin claims & child claims log(executor, Level.INFO, "Converting %s claims...".formatted(claims.size())); final Map<Claim, GriefPreventionClaim> allClaims = Maps.newHashMap(); claims.forEach(gpc -> allClaims.put(gpc.toClaim(this), gpc)); // Convert child claims and save to claim worlds log(executor, Level.INFO, "Saving %s claims...".formatted(amount.getAndSet(0))); final Set<ClaimWorld> claimWorlds = Sets.newHashSet(); allClaims.forEach((hcc, gpc) -> { final String world = gpc.lesserCorner.split(";")[0]; // Get the claim world final Optional<ClaimWorld> optionalWorld = plugin.getClaimWorld(world); if (optionalWorld.isEmpty()) { plugin.log(Level.WARNING, "Skipped claim at %s on missing world %s".formatted(gpc.lesserCorner, world)); return; } final ClaimWorld claimWorld = optionalWorld.get(); // Add the claim world to the list of worlds, then cache the claim owner/trustees claimWorlds.add(claimWorld); hcc.getOwner().flatMap(owner -> users.stream().filter(gpu -> gpu.uuid.equals(owner)).findFirst()) .ifPresent(user -> claimWorld.cacheUser(user.toUser())); hcc.getTrustedUsers().keySet().forEach(u -> users.stream().filter(gpu -> gpu.uuid.equals(u)) .findFirst().ifPresent(user -> claimWorld.cacheUser(user.toUser()))); // Add the claim to either its parent or the claim world if (gpc.isChildClaim()) { allClaims.entrySet().stream() .filter(entry -> entry.getValue().id == gpc.parentId) .map(Map.Entry::getKey).findFirst() .ifPresent(parent -> { parent.getOwner().ifPresent(hcc::setOwner); parent.getChildren().add(hcc); }); } else { claimWorld.getClaims().add(hcc); } if (amount.incrementAndGet() % CLAIMS_PER_PAGE == 0) { log(executor, Level.INFO, "Saved %s claims...".formatted(amount.get())); } }); // Save claim worlds plugin.clearAllMapMarkers(); log(executor, Level.INFO, "Saving %s claim worlds...".formatted(claimWorlds.size())); final List<CompletableFuture<Void>> claimWorldFutures = Lists.newArrayList(); claimWorlds.forEach(claimWorld -> claimWorldFutures.add( CompletableFuture.runAsync(() -> plugin.getDatabase().updateClaimWorld(claimWorld), pool) )); CompletableFuture.allOf(claimWorldFutures.toArray(CompletableFuture[]::new)).join(); plugin.markAllClaims(); return amount.get(); } private int getTotalUsers() { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT COUNT(*) FROM griefprevention_playerdata""")) { final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return resultSet.getInt(1); } } catch (Throwable e) { plugin.log(Level.WARNING, "Exception querying total user count from DB database", e); } return 0; } private int getTotalClaims() { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT COUNT(*) FROM griefprevention_claimdata""")) { final ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return resultSet.getInt(1); } } catch (Throwable e) { plugin.log(Level.WARNING, "Exception querying total claim count from DB database", e); } return 0; } private CompletableFuture<List<GriefPreventionClaim>> getClaimPage(int page) { final List<GriefPreventionClaim> claims = Lists.newArrayList(); return CompletableFuture.supplyAsync(() -> { try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(""" SELECT * FROM griefprevention_claimdata LIMIT ?, ?;""")) { statement.setInt(1, (page - 1) * CLAIMS_PER_PAGE); statement.setInt(2, CLAIMS_PER_PAGE); final ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { claims.add(new GriefPreventionClaim( resultSet.getInt("id"), resultSet.getString("owner"), resultSet.getString("lessercorner"), resultSet.getString("greatercorner"), parseTrusted(resultSet.getString("builders")), parseTrusted(resultSet.getString("containers")), parseTrusted(resultSet.getString("accessors")), parseTrusted(resultSet.getString("managers")), resultSet.getBoolean("inheritnothing"), resultSet.getInt("parentid") )); } return claims; } catch (Throwable e) { plugin.log(Level.WARNING, "Exception getting claim page #%s from GP database".formatted(page), e); } return claims; }, pool); } @NotNull private List<String> parseTrusted(@NotNull String names) { return Arrays.stream(names.split(";")) .filter(s -> !s.isEmpty()) .toList(); }
private void setTrust(@NotNull String id, @NotNull TrustLevel level, @NotNull Map<Trustable, TrustLevel> map) {
5
2023-11-28 01:09:43+00:00
24k
Manzzx/multi-channel-message-reach
metax-modules/metax-system/src/main/java/com/metax/system/service/impl/SysUserServiceImpl.java
[ { "identifier": "UserConstants", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/constant/UserConstants.java", "snippet": "public class UserConstants\n{\n /**\n * 平台内系统用户的唯一标志\n */\n public static final String SYS_USER = \"SYS_USER\";\n\n /** 正常状态 */\n pub...
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.validation.Validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import com.metax.common.core.constant.UserConstants; import com.metax.common.core.exception.ServiceException; import com.metax.common.core.utils.SpringUtils; import com.metax.common.core.utils.StringUtils; import com.metax.common.core.utils.bean.BeanValidators; import com.metax.common.datascope.annotation.DataScope; import com.metax.common.security.utils.SecurityUtils; import com.metax.system.api.domain.SysRole; import com.metax.system.api.domain.SysUser; import com.metax.system.domain.SysPost; import com.metax.system.domain.SysUserPost; import com.metax.system.domain.SysUserRole; import com.metax.system.mapper.SysPostMapper; import com.metax.system.mapper.SysRoleMapper; import com.metax.system.mapper.SysUserMapper; import com.metax.system.mapper.SysUserPostMapper; import com.metax.system.mapper.SysUserRoleMapper; import com.metax.system.service.ISysConfigService; import com.metax.system.service.ISysUserService;
16,454
package com.metax.system.service.impl; /** * 用户 业务层处理 * * @author ruoyi */ @Service public class SysUserServiceImpl implements ISysUserService { private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class); @Autowired private SysUserMapper userMapper; @Autowired private SysRoleMapper roleMapper; @Autowired private SysPostMapper postMapper; @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysUserPostMapper userPostMapper; @Autowired
package com.metax.system.service.impl; /** * 用户 业务层处理 * * @author ruoyi */ @Service public class SysUserServiceImpl implements ISysUserService { private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class); @Autowired private SysUserMapper userMapper; @Autowired private SysRoleMapper roleMapper; @Autowired private SysPostMapper postMapper; @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysUserPostMapper userPostMapper; @Autowired
private ISysConfigService configService;
16
2023-12-04 05:10:13+00:00
24k
ydb-platform/yoj-project
repository-ydb-v2/src/main/java/tech/ydb/yoj/repository/ydb/statement/PredicateStatement.java
[ { "identifier": "FieldValueType", "path": "databind/src/main/java/tech/ydb/yoj/databind/FieldValueType.java", "snippet": "public enum FieldValueType {\n /**\n * Integer value.\n * Java-side <strong>must</strong> either be a numeric primitive, or extend {@link Number java.lang.Number} and\n ...
import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Streams; import lombok.Getter; import lombok.NonNull; import tech.ydb.proto.ValueProtos; import tech.ydb.yoj.databind.FieldValueType; import tech.ydb.yoj.databind.schema.Schema; import tech.ydb.yoj.databind.schema.Schema.JavaField; import tech.ydb.yoj.repository.db.Entity; import tech.ydb.yoj.repository.db.EntitySchema; import tech.ydb.yoj.repository.ydb.yql.YqlCompositeType; import tech.ydb.yoj.repository.ydb.yql.YqlPredicate; import tech.ydb.yoj.repository.ydb.yql.YqlPredicateParam; import tech.ydb.yoj.repository.ydb.yql.YqlType; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.regex.Pattern; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap;
20,922
package tech.ydb.yoj.repository.ydb.statement; public abstract class PredicateStatement<PARAMS, ENTITY extends Entity<ENTITY>, RESULT> extends YqlStatement<PARAMS, ENTITY, RESULT> { private final Function<PARAMS, YqlPredicate> getPredicate; private final Map<String, PredParam> predParams; public PredicateStatement( @NonNull EntitySchema<ENTITY> schema,
package tech.ydb.yoj.repository.ydb.statement; public abstract class PredicateStatement<PARAMS, ENTITY extends Entity<ENTITY>, RESULT> extends YqlStatement<PARAMS, ENTITY, RESULT> { private final Function<PARAMS, YqlPredicate> getPredicate; private final Map<String, PredParam> predParams; public PredicateStatement( @NonNull EntitySchema<ENTITY> schema,
@NonNull Schema<RESULT> outSchema,
1
2023-12-05 15:57:58+00:00
24k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/multirt/RTRecyclerViewAdapter.java
[ { "identifier": "sExecutorService", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/PojavApplication.java", "snippet": "public static final ExecutorService sExecutorService = new ThreadPoolExecutor(4, 4, 500, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());" }, { "identifier": ...
import static net.kdt.pojavlaunch.PojavApplication.sExecutorService; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.recyclerview.widget.RecyclerView; import net.kdt.pojavlaunch.Architecture; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import java.io.IOException; import java.util.List;
16,067
package net.kdt.pojavlaunch.multirt; public class RTRecyclerViewAdapter extends RecyclerView.Adapter<RTRecyclerViewAdapter.RTViewHolder> { private boolean mIsDeleting = false; @NonNull @Override public RTViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View recyclableView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_multirt_runtime,parent,false); return new RTViewHolder(recyclableView); } @Override public void onBindViewHolder(@NonNull RTViewHolder holder, int position) { final List<Runtime> runtimes = MultiRTUtils.getRuntimes(); holder.bindRuntime(runtimes.get(position),position); } @Override public int getItemCount() { return MultiRTUtils.getRuntimes().size(); } public boolean isDefaultRuntime(Runtime rt) { return LauncherPreferences.PREF_DEFAULT_RUNTIME.equals(rt.name); } @SuppressLint("NotifyDataSetChanged") //not a problem, given the typical size of the list public void setDefault(Runtime rt){ LauncherPreferences.PREF_DEFAULT_RUNTIME = rt.name; LauncherPreferences.DEFAULT_PREF.edit().putString("defaultRuntime",LauncherPreferences.PREF_DEFAULT_RUNTIME).apply(); notifyDataSetChanged(); } @SuppressLint("NotifyDataSetChanged") //not a problem, given the typical size of the list public void setIsEditing(boolean isEditing) { mIsDeleting = isEditing; notifyDataSetChanged(); } public boolean getIsEditing(){ return mIsDeleting; } public class RTViewHolder extends RecyclerView.ViewHolder { final TextView mJavaVersionTextView; final TextView mFullJavaVersionTextView; final ColorStateList mDefaultColors; final Button mSetDefaultButton; final ImageButton mDeleteButton; final Context mContext; Runtime mCurrentRuntime; int mCurrentPosition; public RTViewHolder(View itemView) { super(itemView); mJavaVersionTextView = itemView.findViewById(R.id.multirt_view_java_version); mFullJavaVersionTextView = itemView.findViewById(R.id.multirt_view_java_version_full); mSetDefaultButton = itemView.findViewById(R.id.multirt_view_setdefaultbtn); mDeleteButton = itemView.findViewById(R.id.multirt_view_removebtn); mDefaultColors = mFullJavaVersionTextView.getTextColors(); mContext = itemView.getContext(); setupOnClickListeners(); } @SuppressLint("NotifyDataSetChanged") // same as all the other ones private void setupOnClickListeners(){ mSetDefaultButton.setOnClickListener(v -> { if(mCurrentRuntime != null) { setDefault(mCurrentRuntime); RTRecyclerViewAdapter.this.notifyDataSetChanged(); } }); mDeleteButton.setOnClickListener(v -> { if (mCurrentRuntime == null) return; if(MultiRTUtils.getRuntimes().size() < 2) { new AlertDialog.Builder(mContext) .setTitle(R.string.global_error) .setMessage(R.string.multirt_config_removeerror_last) .setPositiveButton(android.R.string.ok,(adapter, which)->adapter.dismiss()) .show(); return; } sExecutorService.execute(() -> { try { MultiRTUtils.removeRuntimeNamed(mCurrentRuntime.name); mDeleteButton.post(() -> { if(getBindingAdapter() != null) getBindingAdapter().notifyDataSetChanged(); }); } catch (IOException e) {
package net.kdt.pojavlaunch.multirt; public class RTRecyclerViewAdapter extends RecyclerView.Adapter<RTRecyclerViewAdapter.RTViewHolder> { private boolean mIsDeleting = false; @NonNull @Override public RTViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View recyclableView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_multirt_runtime,parent,false); return new RTViewHolder(recyclableView); } @Override public void onBindViewHolder(@NonNull RTViewHolder holder, int position) { final List<Runtime> runtimes = MultiRTUtils.getRuntimes(); holder.bindRuntime(runtimes.get(position),position); } @Override public int getItemCount() { return MultiRTUtils.getRuntimes().size(); } public boolean isDefaultRuntime(Runtime rt) { return LauncherPreferences.PREF_DEFAULT_RUNTIME.equals(rt.name); } @SuppressLint("NotifyDataSetChanged") //not a problem, given the typical size of the list public void setDefault(Runtime rt){ LauncherPreferences.PREF_DEFAULT_RUNTIME = rt.name; LauncherPreferences.DEFAULT_PREF.edit().putString("defaultRuntime",LauncherPreferences.PREF_DEFAULT_RUNTIME).apply(); notifyDataSetChanged(); } @SuppressLint("NotifyDataSetChanged") //not a problem, given the typical size of the list public void setIsEditing(boolean isEditing) { mIsDeleting = isEditing; notifyDataSetChanged(); } public boolean getIsEditing(){ return mIsDeleting; } public class RTViewHolder extends RecyclerView.ViewHolder { final TextView mJavaVersionTextView; final TextView mFullJavaVersionTextView; final ColorStateList mDefaultColors; final Button mSetDefaultButton; final ImageButton mDeleteButton; final Context mContext; Runtime mCurrentRuntime; int mCurrentPosition; public RTViewHolder(View itemView) { super(itemView); mJavaVersionTextView = itemView.findViewById(R.id.multirt_view_java_version); mFullJavaVersionTextView = itemView.findViewById(R.id.multirt_view_java_version_full); mSetDefaultButton = itemView.findViewById(R.id.multirt_view_setdefaultbtn); mDeleteButton = itemView.findViewById(R.id.multirt_view_removebtn); mDefaultColors = mFullJavaVersionTextView.getTextColors(); mContext = itemView.getContext(); setupOnClickListeners(); } @SuppressLint("NotifyDataSetChanged") // same as all the other ones private void setupOnClickListeners(){ mSetDefaultButton.setOnClickListener(v -> { if(mCurrentRuntime != null) { setDefault(mCurrentRuntime); RTRecyclerViewAdapter.this.notifyDataSetChanged(); } }); mDeleteButton.setOnClickListener(v -> { if (mCurrentRuntime == null) return; if(MultiRTUtils.getRuntimes().size() < 2) { new AlertDialog.Builder(mContext) .setTitle(R.string.global_error) .setMessage(R.string.multirt_config_removeerror_last) .setPositiveButton(android.R.string.ok,(adapter, which)->adapter.dismiss()) .show(); return; } sExecutorService.execute(() -> { try { MultiRTUtils.removeRuntimeNamed(mCurrentRuntime.name); mDeleteButton.post(() -> { if(getBindingAdapter() != null) getBindingAdapter().notifyDataSetChanged(); }); } catch (IOException e) {
Tools.showError(itemView.getContext(), e);
2
2023-12-01 16:16:12+00:00
24k
kawashirov/distant-horizons
common/src/main/java/com/seibel/distanthorizons/common/wrappers/WrapperFactory.java
[ { "identifier": "BiomeWrapper", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/block/BiomeWrapper.java", "snippet": "public class BiomeWrapper implements IBiomeWrapper\n{\n\tprivate static final Logger LOGGER = LogManager.getLogger();\n\t\n\t#if PRE_MC_1_18_2\n\tpublic static f...
import com.seibel.distanthorizons.api.interfaces.override.worldGenerator.IDhApiWorldGenerator; import com.seibel.distanthorizons.common.wrappers.block.BiomeWrapper; import com.seibel.distanthorizons.common.wrappers.block.BlockStateWrapper; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import com.seibel.distanthorizons.common.wrappers.world.ClientLevelWrapper; import com.seibel.distanthorizons.common.wrappers.world.ServerLevelWrapper; import com.seibel.distanthorizons.common.wrappers.worldGeneration.BatchGenerationEnvironment; import com.seibel.distanthorizons.core.level.IDhLevel; import com.seibel.distanthorizons.core.level.IDhServerLevel; import com.seibel.distanthorizons.core.wrapperInterfaces.IWrapperFactory; import com.seibel.distanthorizons.core.wrapperInterfaces.block.IBlockStateWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.chunk.IChunkWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IBiomeWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.ILevelWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.worldGeneration.AbstractBatchGenerationEnvironmentWrapper; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.chunk.ChunkAccess; import java.io.IOException; import java.util.HashSet;
18,424
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers; /** * This handles creating abstract wrapper objects. * * @author James Seibel * @version 2022-12-5 */ public class WrapperFactory implements IWrapperFactory { public static final WrapperFactory INSTANCE = new WrapperFactory(); @Override public AbstractBatchGenerationEnvironmentWrapper createBatchGenerator(IDhLevel targetLevel) { if (targetLevel instanceof IDhServerLevel) { return new BatchGenerationEnvironment((IDhServerLevel) targetLevel); } else { throw new IllegalArgumentException("The target level must be a server-side level."); } } @Override public IBiomeWrapper deserializeBiomeWrapper(String str, ILevelWrapper levelWrapper) throws IOException { return BiomeWrapper.deserialize(str, levelWrapper); } @Override public IBlockStateWrapper deserializeBlockStateWrapper(String str, ILevelWrapper levelWrapper) throws IOException { return BlockStateWrapper.deserialize(str, levelWrapper); } @Override public IBlockStateWrapper getAirBlockStateWrapper() { return BlockStateWrapper.AIR; } @Override public HashSet<IBlockStateWrapper> getRendererIgnoredBlocks(ILevelWrapper levelWrapper) { return BlockStateWrapper.getRendererIgnoredBlocks(levelWrapper); } /** * Note: when this is updated for different MC versions, make sure you also update the documentation in * {@link IDhApiWorldGenerator#generateChunks} and the type list in {@link WrapperFactory#createChunkWrapperErrorMessage}. <br><br> * * For full method documentation please see: {@link IWrapperFactory#createChunkWrapper} * * @see IWrapperFactory#createChunkWrapper */ public IChunkWrapper createChunkWrapper(Object[] objectArray) throws ClassCastException { if (objectArray.length == 1 && objectArray[0] instanceof IChunkWrapper) { try { // this path should only happen when called by Distant Horizons code // API implementors should never hit this path return (IChunkWrapper) objectArray[0]; } catch (Exception e) { throw new ClassCastException(createChunkWrapperErrorMessage(objectArray)); } } // MC 1.16, 1.18, 1.19, 1.20 #if POST_MC_1_17_1 || MC_1_16_5 else if (objectArray.length == 2) { // correct number of parameters from the API // chunk if (!(objectArray[0] instanceof ChunkAccess)) { throw new ClassCastException(createChunkWrapperErrorMessage(objectArray)); } ChunkAccess chunk = (ChunkAccess) objectArray[0]; // level / light source if (!(objectArray[1] instanceof Level)) { throw new ClassCastException(createChunkWrapperErrorMessage(objectArray)); } // the level is needed for the DH level wrapper... Level level = (Level) objectArray[1]; // ...the LevelReader is needed for chunk lighting LevelReader lightSource = level; // level wrapper ILevelWrapper levelWrapper; if (level instanceof ServerLevel) { levelWrapper = ServerLevelWrapper.getWrapper((ServerLevel)level); } else if (level instanceof ClientLevel) { levelWrapper = ClientLevelWrapper.getWrapper((ClientLevel)level); } else { throw new ClassCastException(createChunkWrapperErrorMessage(objectArray)); }
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers; /** * This handles creating abstract wrapper objects. * * @author James Seibel * @version 2022-12-5 */ public class WrapperFactory implements IWrapperFactory { public static final WrapperFactory INSTANCE = new WrapperFactory(); @Override public AbstractBatchGenerationEnvironmentWrapper createBatchGenerator(IDhLevel targetLevel) { if (targetLevel instanceof IDhServerLevel) { return new BatchGenerationEnvironment((IDhServerLevel) targetLevel); } else { throw new IllegalArgumentException("The target level must be a server-side level."); } } @Override public IBiomeWrapper deserializeBiomeWrapper(String str, ILevelWrapper levelWrapper) throws IOException { return BiomeWrapper.deserialize(str, levelWrapper); } @Override public IBlockStateWrapper deserializeBlockStateWrapper(String str, ILevelWrapper levelWrapper) throws IOException { return BlockStateWrapper.deserialize(str, levelWrapper); } @Override public IBlockStateWrapper getAirBlockStateWrapper() { return BlockStateWrapper.AIR; } @Override public HashSet<IBlockStateWrapper> getRendererIgnoredBlocks(ILevelWrapper levelWrapper) { return BlockStateWrapper.getRendererIgnoredBlocks(levelWrapper); } /** * Note: when this is updated for different MC versions, make sure you also update the documentation in * {@link IDhApiWorldGenerator#generateChunks} and the type list in {@link WrapperFactory#createChunkWrapperErrorMessage}. <br><br> * * For full method documentation please see: {@link IWrapperFactory#createChunkWrapper} * * @see IWrapperFactory#createChunkWrapper */ public IChunkWrapper createChunkWrapper(Object[] objectArray) throws ClassCastException { if (objectArray.length == 1 && objectArray[0] instanceof IChunkWrapper) { try { // this path should only happen when called by Distant Horizons code // API implementors should never hit this path return (IChunkWrapper) objectArray[0]; } catch (Exception e) { throw new ClassCastException(createChunkWrapperErrorMessage(objectArray)); } } // MC 1.16, 1.18, 1.19, 1.20 #if POST_MC_1_17_1 || MC_1_16_5 else if (objectArray.length == 2) { // correct number of parameters from the API // chunk if (!(objectArray[0] instanceof ChunkAccess)) { throw new ClassCastException(createChunkWrapperErrorMessage(objectArray)); } ChunkAccess chunk = (ChunkAccess) objectArray[0]; // level / light source if (!(objectArray[1] instanceof Level)) { throw new ClassCastException(createChunkWrapperErrorMessage(objectArray)); } // the level is needed for the DH level wrapper... Level level = (Level) objectArray[1]; // ...the LevelReader is needed for chunk lighting LevelReader lightSource = level; // level wrapper ILevelWrapper levelWrapper; if (level instanceof ServerLevel) { levelWrapper = ServerLevelWrapper.getWrapper((ServerLevel)level); } else if (level instanceof ClientLevel) { levelWrapper = ClientLevelWrapper.getWrapper((ClientLevel)level); } else { throw new ClassCastException(createChunkWrapperErrorMessage(objectArray)); }
return new ChunkWrapper(chunk, lightSource, levelWrapper);
2
2023-12-04 11:41:46+00:00
24k
hmcts/juror-sql-support-library
src/main/java/uk/gov/hmcts/juror/support/sql/service/SqlSupportService.java
[ { "identifier": "Constants", "path": "src/main/java/uk/gov/hmcts/juror/support/sql/Constants.java", "snippet": "public class Constants {\n\n public static final String PHONE_REGEX = \"^(\\\\+44|0)7\\\\d{9}$\";\n public static final String NOTES_REGEX = \"[A-Za-z0-9]{10,501}\";\n public static f...
import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StopWatch; import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromCollectionGeneratorImpl; import uk.gov.hmcts.juror.support.generation.util.RandomGenerator; import uk.gov.hmcts.juror.support.sql.Constants; import uk.gov.hmcts.juror.support.sql.Util; import uk.gov.hmcts.juror.support.sql.dto.JurorAccountDetailsDto; import uk.gov.hmcts.juror.support.sql.entity.CourtLocation; import uk.gov.hmcts.juror.support.sql.entity.Juror; import uk.gov.hmcts.juror.support.sql.entity.JurorGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorPool; import uk.gov.hmcts.juror.support.sql.entity.JurorPoolGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorStatus; import uk.gov.hmcts.juror.support.sql.entity.PoolRequest; import uk.gov.hmcts.juror.support.sql.entity.PoolRequestGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.AbstractJurorResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.AbstractJurorResponseGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.DigitalResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.DigitalResponseGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.PaperResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.PaperResponseGenerator; import uk.gov.hmcts.juror.support.sql.generators.DigitalResponseGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.JurorGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.JurorPoolGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.PaperResponseGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.PoolRequestGeneratorUtil; import uk.gov.hmcts.juror.support.sql.repository.CourtLocationRepository; import uk.gov.hmcts.juror.support.sql.repository.DigitalResponseRepository; import uk.gov.hmcts.juror.support.sql.repository.JurorPoolRepository; import uk.gov.hmcts.juror.support.sql.repository.JurorRepository; import uk.gov.hmcts.juror.support.sql.repository.PaperResponseRepository; import uk.gov.hmcts.juror.support.sql.repository.PoolRequestRepository; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors;
15,634
); jurors.forEach(jurorAccountDetailsDto -> { AbstractJurorResponseGenerator<?> generator = Util.getWeightedRandomItem(weightMap); AbstractJurorResponse jurorResponse = generator.generate(); mapJurorToJurorResponse(jurorAccountDetailsDto.getJuror(), jurorResponse); jurorAccountDetailsDto.setJurorResponse(jurorResponse); }); stopWatch.stop(); } private void mapJurorToJurorResponse(final Juror juror, final AbstractJurorResponse jurorResponse) { jurorResponse.setJurorNumber(juror.getJurorNumber()); jurorResponse.setTitle(juror.getTitle()); jurorResponse.setFirstName(juror.getFirstName()); jurorResponse.setLastName(juror.getLastName()); jurorResponse.setDateOfBirth(juror.getDateOfBirth()); jurorResponse.setPhoneNumber(juror.getPhoneNumber()); jurorResponse.setAltPhoneNumber(juror.getAltPhoneNumber()); jurorResponse.setEmail(juror.getEmail()); jurorResponse.setAddressLine1(juror.getAddressLine1()); jurorResponse.setAddressLine2(juror.getAddressLine2()); jurorResponse.setAddressLine3(juror.getAddressLine3()); jurorResponse.setAddressLine4(juror.getAddressLine4()); jurorResponse.setAddressLine5(juror.getAddressLine5()); jurorResponse.setPostcode(juror.getPostcode()); } private List<JurorAccountDetailsDto> createJurorAccountDetailsDtos(boolean isCourtOwned, Map<JurorStatus, Integer> jurorStatusCountMap) { List<JurorAccountDetailsDto> jurorAccountDetailsDtos = jurorStatusCountMap.entrySet().stream() .map(entity -> { List<JurorAccountDetailsDto> jurors = createJurors(isCourtOwned, entity.getKey(), entity.getValue()); addJurorPoolsToJurorAccountDto(isCourtOwned, entity.getKey(), jurors); addSummonsReplyToJurorAccountDto(66, 34, entity.getKey(), jurors); return jurors; } ) .flatMap(List::stream) .collect(Collectors.toCollection(ArrayList::new)); Collections.shuffle(jurorAccountDetailsDtos); return jurorAccountDetailsDtos; } private void reassignJurorPoolsToRandomPoolWithNewOwner(List<JurorPool> needRandomPool, List<PoolRequest> pools) { RandomFromCollectionGeneratorImpl<PoolRequest> randomPoolRequestGenerator = new RandomFromCollectionGeneratorImpl<>(pools); for (JurorPool jurorPool : needRandomPool) { PoolRequest poolRequest; //Get a pool request which is not the current owner (ensures a new pool is assigned) do { poolRequest = randomPoolRequestGenerator.generate(); } while (poolRequest.getOwner().equals(jurorPool.getOwner())); jurorPool.setOwner(poolRequest.getOwner()); jurorPool.setPoolNumber(poolRequest.getPoolNumber()); jurorPool.setStartDate(poolRequest.getReturnDate()); } } private void addJurorPoolsToJurorAccountDto(boolean isCourtOwned, JurorStatus jurorStatus, List<JurorAccountDetailsDto> jurors) { stopWatch.start("Creating Juror Pools for status: " + jurorStatus); log.info("Creating juror pools with status {} for {} jurors", jurorStatus, jurors.size()); final JurorPoolGenerator jurorPoolGenerator = JurorPoolGeneratorUtil.create(isCourtOwned, jurorStatus); final JurorPoolGenerator respondeedJurorPoolGenerator = JurorPoolGeneratorUtil.create(isCourtOwned, JurorStatus.RESPONDED); BiFunction<Juror, JurorPool, List<JurorPool>> jurorPoolStatusConsumer = switch (jurorStatus) { case TRANSFERRED -> (juror, jurorPool) -> { JurorPool transferredToPool = respondeedJurorPoolGenerator.generate(); transferredToPool.setJurorNumber(juror.getJurorNumber()); transferredToPool.setOwner(Util.getRandomItem(getCourtOwners(), List.of(jurorPool.getOwner()))); return List.of(transferredToPool); }; case REASSIGNED -> (juror, jurorPool) -> { JurorPool reassignedToPool = respondeedJurorPoolGenerator.generate(); reassignedToPool.setJurorNumber(juror.getJurorNumber()); reassignedToPool.setOwner(jurorPool.getOwner()); return List.of(reassignedToPool); }; default -> (juror, jurorPool) -> List.of(); }; jurors.forEach(jurorAccountDetailsDto -> jurorAccountDetailsDto.setJurorPools( createJurorPoolsForJuror( jurorAccountDetailsDto.getJuror(), jurorPoolStatusConsumer, jurorPoolGenerator ) )); stopWatch.stop(); } private List<JurorPool> createJurorPoolsForJuror(Juror juror, BiFunction<Juror, JurorPool, List<JurorPool>> jurorPoolStatusConsumer, JurorPoolGenerator jurorPoolGenerator) { List<JurorPool> jurorPools = new ArrayList<>(); JurorPool jurorPool = jurorPoolGenerator.generate(); jurorPool.setJurorNumber(juror.getJurorNumber()); jurorPools.add(jurorPool); jurorPools.addAll(jurorPoolStatusConsumer.apply(juror, jurorPool)); return jurorPools; } private List<JurorAccountDetailsDto> createJurors(boolean isCourtOwned, JurorStatus jurorStatus, int count) { stopWatch.start("Creating Jurors"); log.info("Creating {} jurors with status {}", count, jurorStatus); List<JurorAccountDetailsDto> jurors = new ArrayList<>(count);
package uk.gov.hmcts.juror.support.sql.service; @Component @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Slf4j public class SqlSupportService { private final JurorRepository jurorRepository; private final PoolRequestRepository poolRequestRepository; private final JurorPoolRepository jurorPoolRepository; private final DigitalResponseRepository digitalResponseRepository; private final PaperResponseRepository paperResponseRepository; private StopWatch stopWatch; private final CourtLocationRepository courtLocationRepository; private static final List<CourtLocation> courtLocations; private static final Set<String> courtOwners; private static final int BATCH_SIZE = 100; static { courtLocations = new ArrayList<>(); courtOwners = new HashSet<>(); } public static List<CourtLocation> getCourtLocations() { return Collections.unmodifiableList(courtLocations); } public static Set<String> getCourtOwners() { return Collections.unmodifiableSet(courtOwners); } @PostConstruct //Temporary for testing purposes public void postConstruct() { this.stopWatch = new StopWatch(); courtLocationRepository.findAll().forEach(courtLocations::add); courtOwners.add("400"); courtOwners.add("415"); //TODO add back courtLocations.forEach(courtLocation -> courtOwners.add(courtLocation.getOwner())); clearDownDatabase(); Map<JurorStatus, Integer> jurorStatusCountMapCourt = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourt.put(JurorStatus.DEFERRED, 12585); jurorStatusCountMapCourt.put(JurorStatus.DISQUALIFIED, 126); jurorStatusCountMapCourt.put(JurorStatus.EXCUSED, 15607); jurorStatusCountMapCourt.put(JurorStatus.FAILED_TO_ATTEND, 705); jurorStatusCountMapCourt.put(JurorStatus.JUROR, 3916); jurorStatusCountMapCourt.put(JurorStatus.PANEL, 472); jurorStatusCountMapCourt.put(JurorStatus.REASSIGNED, 41313); jurorStatusCountMapCourt.put(JurorStatus.RESPONDED, 208525); jurorStatusCountMapCourt.put(JurorStatus.SUMMONED, 56443); jurorStatusCountMapCourt.put(JurorStatus.TRANSFERRED, 1075); //TODO uncomment createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourt); //TODO remove Map<JurorStatus, Integer> jurorStatusCountMapCourtTmp = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourtTmp.put(JurorStatus.SUMMONED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.RESPONDED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.DEFERRED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.EXCUSED, 100); //TODO remove end createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourtTmp); log.info("DONE: " + stopWatch.prettyPrint()); } private void clearDownDatabase() { log.info("Clearing database"); stopWatch.start("Cleaning database"); jurorPoolRepository.deleteAll(); poolRequestRepository.deleteAll(); digitalResponseRepository.deleteAll(); paperResponseRepository.deleteAll(); jurorRepository.deleteAll(); stopWatch.stop(); log.info("Clearing database: DONE"); } public void createJurorsAssociatedToPools(boolean isCourtOwned, int jurorsInPoolMinimumInclusive, int jurorsInPoolMaximumExclusive, Map<JurorStatus, Integer> jurorStatusCountMap) { final int totalCount = jurorStatusCountMap.values().stream().reduce(0, Integer::sum); log.info("Creating Jurors save dtos"); List<JurorAccountDetailsDto> jurorAccountDetailsDtos = createJurorAccountDetailsDtos(isCourtOwned, jurorStatusCountMap); assert totalCount == jurorAccountDetailsDtos.size(); log.info("Creating Pool Request's"); List<JurorPool> needRandomPool = new ArrayList<>(); List<PoolRequest> pools = new ArrayList<>(totalCount / jurorsInPoolMinimumInclusive); PoolRequestGenerator poolRequestGenerator = PoolRequestGeneratorUtil.create(isCourtOwned, Constants.POOL_REQUEST_WEIGHT_MAP); int remainingJurors = totalCount; Collections.shuffle(jurorAccountDetailsDtos); //Ensures pools get a random distribution of juror types while (remainingJurors > 0) { final int totalJurorsInPool = RandomGenerator.nextInt( jurorsInPoolMinimumInclusive, jurorsInPoolMaximumExclusive); PoolRequest poolRequest = poolRequestGenerator.generate(); poolRequest.setTotalNoRequired(RandomGenerator.nextInt(10, 16)); pools.add(poolRequest); List<JurorAccountDetailsDto> selectedJurors = jurorAccountDetailsDtos.subList( Math.max(0, remainingJurors - totalJurorsInPool), remainingJurors); selectedJurors.parallelStream().forEach(juror -> { String firstJurorPoolOwner = null; List<JurorPool> jurorPools = juror.getJurorPools(); for (JurorPool jurorPool : jurorPools) { if (firstJurorPoolOwner == null) { firstJurorPoolOwner = jurorPool.getOwner(); } //Set owner so we know which pool this juror can not be in jurorPool.setOwner(jurorPool.getOwner()); if (jurorPool.getOwner().equals(firstJurorPoolOwner)) { jurorPool.setPoolNumber(poolRequest.getPoolNumber()); jurorPool.setStartDate(poolRequest.getReturnDate()); } else { needRandomPool.add(jurorPool); } } } ); remainingJurors -= totalJurorsInPool; } reassignJurorPoolsToRandomPoolWithNewOwner(needRandomPool, pools); stopWatch.start("Saving Pool Request's"); log.info("Saving Pool Request's to database"); Util.batchSave(poolRequestRepository, pools, BATCH_SIZE); stopWatch.stop(); saveJurorAccountDetailsDtos(jurorAccountDetailsDtos); } private void saveJurorAccountDetailsDtos(List<JurorAccountDetailsDto> jurorAccountDetailsDtos) { stopWatch.start("Saving Juror's"); log.info("Saving Juror's to database"); Util.batchSave(jurorRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJuror).toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Paper Response's"); log.info("Saving Juror Paper Response's"); Util.batchSave(paperResponseRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorResponse) .filter(PaperResponse.class::isInstance) .map(PaperResponse.class::cast) .toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Digital Response's"); log.info("Saving Juror Digital Response's"); Util.batchSave(digitalResponseRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorResponse) .filter(DigitalResponse.class::isInstance) .map(DigitalResponse.class::cast) .toList(), BATCH_SIZE); stopWatch.stop(); stopWatch.start("Saving Juror Pool's"); log.info("Saving Juror Pool's to database"); Util.batchSave(jurorPoolRepository, jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorPools).flatMap(List::stream).toList(), BATCH_SIZE); stopWatch.stop(); } private void addSummonsReplyToJurorAccountDto(int digitalWeight, int paperWeight, JurorStatus jurorStatus, List<JurorAccountDetailsDto> jurors) { stopWatch.start("Creating Summons replies from jurors"); log.info("Creating {} juror responses from jurors", jurors.size()); DigitalResponseGenerator digitalResponseGenerator = DigitalResponseGeneratorUtil.create(jurorStatus); PaperResponseGenerator paperResponseGenerator = PaperResponseGeneratorUtil.create(jurorStatus); Map<AbstractJurorResponseGenerator<?>, Integer> weightMap = Map.of( digitalResponseGenerator, digitalWeight, paperResponseGenerator, paperWeight ); jurors.forEach(jurorAccountDetailsDto -> { AbstractJurorResponseGenerator<?> generator = Util.getWeightedRandomItem(weightMap); AbstractJurorResponse jurorResponse = generator.generate(); mapJurorToJurorResponse(jurorAccountDetailsDto.getJuror(), jurorResponse); jurorAccountDetailsDto.setJurorResponse(jurorResponse); }); stopWatch.stop(); } private void mapJurorToJurorResponse(final Juror juror, final AbstractJurorResponse jurorResponse) { jurorResponse.setJurorNumber(juror.getJurorNumber()); jurorResponse.setTitle(juror.getTitle()); jurorResponse.setFirstName(juror.getFirstName()); jurorResponse.setLastName(juror.getLastName()); jurorResponse.setDateOfBirth(juror.getDateOfBirth()); jurorResponse.setPhoneNumber(juror.getPhoneNumber()); jurorResponse.setAltPhoneNumber(juror.getAltPhoneNumber()); jurorResponse.setEmail(juror.getEmail()); jurorResponse.setAddressLine1(juror.getAddressLine1()); jurorResponse.setAddressLine2(juror.getAddressLine2()); jurorResponse.setAddressLine3(juror.getAddressLine3()); jurorResponse.setAddressLine4(juror.getAddressLine4()); jurorResponse.setAddressLine5(juror.getAddressLine5()); jurorResponse.setPostcode(juror.getPostcode()); } private List<JurorAccountDetailsDto> createJurorAccountDetailsDtos(boolean isCourtOwned, Map<JurorStatus, Integer> jurorStatusCountMap) { List<JurorAccountDetailsDto> jurorAccountDetailsDtos = jurorStatusCountMap.entrySet().stream() .map(entity -> { List<JurorAccountDetailsDto> jurors = createJurors(isCourtOwned, entity.getKey(), entity.getValue()); addJurorPoolsToJurorAccountDto(isCourtOwned, entity.getKey(), jurors); addSummonsReplyToJurorAccountDto(66, 34, entity.getKey(), jurors); return jurors; } ) .flatMap(List::stream) .collect(Collectors.toCollection(ArrayList::new)); Collections.shuffle(jurorAccountDetailsDtos); return jurorAccountDetailsDtos; } private void reassignJurorPoolsToRandomPoolWithNewOwner(List<JurorPool> needRandomPool, List<PoolRequest> pools) { RandomFromCollectionGeneratorImpl<PoolRequest> randomPoolRequestGenerator = new RandomFromCollectionGeneratorImpl<>(pools); for (JurorPool jurorPool : needRandomPool) { PoolRequest poolRequest; //Get a pool request which is not the current owner (ensures a new pool is assigned) do { poolRequest = randomPoolRequestGenerator.generate(); } while (poolRequest.getOwner().equals(jurorPool.getOwner())); jurorPool.setOwner(poolRequest.getOwner()); jurorPool.setPoolNumber(poolRequest.getPoolNumber()); jurorPool.setStartDate(poolRequest.getReturnDate()); } } private void addJurorPoolsToJurorAccountDto(boolean isCourtOwned, JurorStatus jurorStatus, List<JurorAccountDetailsDto> jurors) { stopWatch.start("Creating Juror Pools for status: " + jurorStatus); log.info("Creating juror pools with status {} for {} jurors", jurorStatus, jurors.size()); final JurorPoolGenerator jurorPoolGenerator = JurorPoolGeneratorUtil.create(isCourtOwned, jurorStatus); final JurorPoolGenerator respondeedJurorPoolGenerator = JurorPoolGeneratorUtil.create(isCourtOwned, JurorStatus.RESPONDED); BiFunction<Juror, JurorPool, List<JurorPool>> jurorPoolStatusConsumer = switch (jurorStatus) { case TRANSFERRED -> (juror, jurorPool) -> { JurorPool transferredToPool = respondeedJurorPoolGenerator.generate(); transferredToPool.setJurorNumber(juror.getJurorNumber()); transferredToPool.setOwner(Util.getRandomItem(getCourtOwners(), List.of(jurorPool.getOwner()))); return List.of(transferredToPool); }; case REASSIGNED -> (juror, jurorPool) -> { JurorPool reassignedToPool = respondeedJurorPoolGenerator.generate(); reassignedToPool.setJurorNumber(juror.getJurorNumber()); reassignedToPool.setOwner(jurorPool.getOwner()); return List.of(reassignedToPool); }; default -> (juror, jurorPool) -> List.of(); }; jurors.forEach(jurorAccountDetailsDto -> jurorAccountDetailsDto.setJurorPools( createJurorPoolsForJuror( jurorAccountDetailsDto.getJuror(), jurorPoolStatusConsumer, jurorPoolGenerator ) )); stopWatch.stop(); } private List<JurorPool> createJurorPoolsForJuror(Juror juror, BiFunction<Juror, JurorPool, List<JurorPool>> jurorPoolStatusConsumer, JurorPoolGenerator jurorPoolGenerator) { List<JurorPool> jurorPools = new ArrayList<>(); JurorPool jurorPool = jurorPoolGenerator.generate(); jurorPool.setJurorNumber(juror.getJurorNumber()); jurorPools.add(jurorPool); jurorPools.addAll(jurorPoolStatusConsumer.apply(juror, jurorPool)); return jurorPools; } private List<JurorAccountDetailsDto> createJurors(boolean isCourtOwned, JurorStatus jurorStatus, int count) { stopWatch.start("Creating Jurors"); log.info("Creating {} jurors with status {}", count, jurorStatus); List<JurorAccountDetailsDto> jurors = new ArrayList<>(count);
JurorGenerator jurorGenerator = JurorGeneratorUtil.create(isCourtOwned, jurorStatus);
12
2023-12-01 11:38:42+00:00
24k
SuperRicky14/TpaPlusPlus
src/main/java/net/superricky/tpaplusplus/command/TPAPlusPlusCommand.java
[ { "identifier": "Config", "path": "src/main/java/net/superricky/tpaplusplus/util/configuration/Config.java", "snippet": "public class Config {\n public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n public static final ForgeConfigSpec SPEC;\n\n public static fin...
import com.mojang.brigadier.arguments.StringArgumentType; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.network.chat.Component; import net.minecraftforge.event.RegisterCommandsEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.superricky.tpaplusplus.util.configuration.Config; import net.superricky.tpaplusplus.Main; import net.superricky.tpaplusplus.util.configuration.Messages; import net.superricky.tpaplusplus.util.manager.DeathManager; import net.superricky.tpaplusplus.util.configuration.formatters.MessageReformatter; import net.superricky.tpaplusplus.util.manager.RequestManager; import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.literal;
14,541
package net.superricky.tpaplusplus.command; @Mod.EventBusSubscriber public class TPAPlusPlusCommand { private static final String FORCE_PARAMETER = "-force"; @SubscribeEvent public static void onRegisterCommandEvent(RegisterCommandsEvent event) { event.getDispatcher().register(literal("tpaplusplus") .executes(context -> version(context.getSource())) .then(literal("refactor") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .then(literal("messages") .then(literal("color-set") .then(argument("colors", StringArgumentType.string()) .executes(context -> refactorColorSet(context.getSource(), StringArgumentType.getString(context, "colors"))))))) .then(literal("version") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .executes(context -> version(context.getSource()))) .then(literal("reload") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .executes(context -> reloadConfig(context.getSource(), false)) .then(literal(FORCE_PARAMETER) .executes(context -> reloadConfig(context.getSource(), true))) .then(literal("config") .executes(context -> reloadConfig(context.getSource(), false)) .then(literal(FORCE_PARAMETER) .executes(context -> reloadConfig(context.getSource(), true))))) .then(literal("license") .executes(context -> printLicense(context.getSource())))); } private TPAPlusPlusCommand() { } private static int printLicense(CommandSourceStack source) { source.sendSystemMessage(Component.literal(""" §6The §cMIT §6License §c(MIT) §cCopyright §6(c) §c2023 SuperRicky §6Permission is §chereby granted§6, §cfree of charge§6, to §cany person obtaining a copy of this software §6and associated documentation files (the "Software"), to deal in the Software §cwithout restriction, §6including without limitation the rights to §cuse§6, §ccopy§6, §cmodify§6, §cmerge§6, §cpublish§6, §cdistribute§6, §csublicense§6, and/or §csell copies of the Software§6, and to permit persons to whom the Software is furnished to do so, §4§l§usubject to the following conditions§6: §4§lThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. §6§lTHE SOFTWARE IS PROVIDED "AS IS", §c§lWITHOUT WARRANTY OF ANY KIND§6§l, §c§lEXPRESS OR IMPLIED§6§l, INCLUDING BUT §c§lNOT LIMITED TO §6§lTHE §c§lWARRANTIES OF MERCHANTABILITY§6§l, §c§lFITNESS §6§lFOR A §c§lPARTICULAR PURPOSE §6§lAND §c§lNONINFRINGEMENT§6§l. IN §4§lNO 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. """)); return 1; } private static int refactorColorSet(CommandSourceStack source, String colors) { colors = colors.replace(" ", ""); String[] colorList = colors.split(","); if (colorList.length != 6) { source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_REQUIRE_SIX_COLORS.get(), colorList.length))); return 0; } for (String color : colorList) { if (!MessageReformatter.isValidColor(color)) { source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_INVALID_COLORS.get(), color))); source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_INVALID_COLORS_EXAMPLES.get(), MessageReformatter.getRandomColorCode()))); return 0; } } String oldMainColor = colorList[0].replace("&", "§").toLowerCase(); String oldSecondaryColor = colorList[1].replace("&", "§").toLowerCase(); String oldErrorColor = colorList[2].replace("&", "§").toLowerCase(); String newMainColor = colorList[3].replace("&", "§").toLowerCase(); String newSecondaryColor = colorList[4].replace("&", "§").toLowerCase(); String newErrorColor = colorList[5].replace("&", "§").toLowerCase(); if (oldMainColor.equals(oldSecondaryColor) || newMainColor.equals(newSecondaryColor)) { source.sendSystemMessage(Component.literal(Messages.ERR_TPAPLUSPLUS_COLORS_CANNOT_BE_THE_SAME.get())); return 0; } MessageReformatter.updateColorsAndSave(MessageReformatter.loadRawConfig(), oldMainColor, newMainColor, oldSecondaryColor, newSecondaryColor, oldErrorColor, newErrorColor); source.sendSystemMessage(Component.literal(Messages.TPAPLUSPLUS_COLORS_SUCCESS.get())); return 1; } private static int version(CommandSourceStack source) {
package net.superricky.tpaplusplus.command; @Mod.EventBusSubscriber public class TPAPlusPlusCommand { private static final String FORCE_PARAMETER = "-force"; @SubscribeEvent public static void onRegisterCommandEvent(RegisterCommandsEvent event) { event.getDispatcher().register(literal("tpaplusplus") .executes(context -> version(context.getSource())) .then(literal("refactor") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .then(literal("messages") .then(literal("color-set") .then(argument("colors", StringArgumentType.string()) .executes(context -> refactorColorSet(context.getSource(), StringArgumentType.getString(context, "colors"))))))) .then(literal("version") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .executes(context -> version(context.getSource()))) .then(literal("reload") .requires(context -> context.hasPermission(Commands.LEVEL_OWNERS)) .executes(context -> reloadConfig(context.getSource(), false)) .then(literal(FORCE_PARAMETER) .executes(context -> reloadConfig(context.getSource(), true))) .then(literal("config") .executes(context -> reloadConfig(context.getSource(), false)) .then(literal(FORCE_PARAMETER) .executes(context -> reloadConfig(context.getSource(), true))))) .then(literal("license") .executes(context -> printLicense(context.getSource())))); } private TPAPlusPlusCommand() { } private static int printLicense(CommandSourceStack source) { source.sendSystemMessage(Component.literal(""" §6The §cMIT §6License §c(MIT) §cCopyright §6(c) §c2023 SuperRicky §6Permission is §chereby granted§6, §cfree of charge§6, to §cany person obtaining a copy of this software §6and associated documentation files (the "Software"), to deal in the Software §cwithout restriction, §6including without limitation the rights to §cuse§6, §ccopy§6, §cmodify§6, §cmerge§6, §cpublish§6, §cdistribute§6, §csublicense§6, and/or §csell copies of the Software§6, and to permit persons to whom the Software is furnished to do so, §4§l§usubject to the following conditions§6: §4§lThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. §6§lTHE SOFTWARE IS PROVIDED "AS IS", §c§lWITHOUT WARRANTY OF ANY KIND§6§l, §c§lEXPRESS OR IMPLIED§6§l, INCLUDING BUT §c§lNOT LIMITED TO §6§lTHE §c§lWARRANTIES OF MERCHANTABILITY§6§l, §c§lFITNESS §6§lFOR A §c§lPARTICULAR PURPOSE §6§lAND §c§lNONINFRINGEMENT§6§l. IN §4§lNO 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. """)); return 1; } private static int refactorColorSet(CommandSourceStack source, String colors) { colors = colors.replace(" ", ""); String[] colorList = colors.split(","); if (colorList.length != 6) { source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_REQUIRE_SIX_COLORS.get(), colorList.length))); return 0; } for (String color : colorList) { if (!MessageReformatter.isValidColor(color)) { source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_INVALID_COLORS.get(), color))); source.sendSystemMessage(Component.literal(String.format(Messages.ERR_TPAPLUSPLUS_COLORS_INVALID_COLORS_EXAMPLES.get(), MessageReformatter.getRandomColorCode()))); return 0; } } String oldMainColor = colorList[0].replace("&", "§").toLowerCase(); String oldSecondaryColor = colorList[1].replace("&", "§").toLowerCase(); String oldErrorColor = colorList[2].replace("&", "§").toLowerCase(); String newMainColor = colorList[3].replace("&", "§").toLowerCase(); String newSecondaryColor = colorList[4].replace("&", "§").toLowerCase(); String newErrorColor = colorList[5].replace("&", "§").toLowerCase(); if (oldMainColor.equals(oldSecondaryColor) || newMainColor.equals(newSecondaryColor)) { source.sendSystemMessage(Component.literal(Messages.ERR_TPAPLUSPLUS_COLORS_CANNOT_BE_THE_SAME.get())); return 0; } MessageReformatter.updateColorsAndSave(MessageReformatter.loadRawConfig(), oldMainColor, newMainColor, oldSecondaryColor, newSecondaryColor, oldErrorColor, newErrorColor); source.sendSystemMessage(Component.literal(Messages.TPAPLUSPLUS_COLORS_SUCCESS.get())); return 1; } private static int version(CommandSourceStack source) {
source.sendSystemMessage(Component.literal(String.format(Messages.TPAPLUSPLUS_VERSION.get(), Main.MOD_VERSION))); // send the mod's version to the command executor
1
2023-12-02 05:41:24+00:00
24k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/model/conditions/GlobalOccurrenceCondition.java
[ { "identifier": "ActivityDiaryContract", "path": "app/src/main/java/de/rampro/activitydiary/db/ActivityDiaryContract.java", "snippet": "public class ActivityDiaryContract {\n\n /* no instance of this class is allowed */\n private ActivityDiaryContract() {\n }\n\n public static final String A...
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import java.util.ArrayList; import java.util.List; import de.rampro.activitydiary.db.ActivityDiaryContract; import de.rampro.activitydiary.helpers.ActivityHelper; import de.rampro.activitydiary.model.DiaryActivity; import de.rampro.activitydiary.ui.settings.SettingsActivity;
16,244
/* * ActivityDiary * * Copyright (C) 2018 Raphael Mack http://www.raphael-mack.de * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.model.conditions; /** * Model the likelihood of the activities based on its predecessors in the diary */ public class GlobalOccurrenceCondition extends Condition implements ActivityHelper.DataChangedListener { public GlobalOccurrenceCondition(ActivityHelper helper){ helper.registerDataChangeListener(this); } @Override protected void doEvaluation() { double weight = Double.parseDouble(sharedPreferences.getString(SettingsActivity.KEY_PREF_COND_OCCURRENCE, "20")); List<DiaryActivity> all = ActivityHelper.helper.getUnsortedActivities(); ArrayList<Likelihood> result = new ArrayList<>(all.size()); if(weight > 0.000001) { SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder(); SQLiteDatabase db = mOpenHelper.getReadableDatabase();
/* * ActivityDiary * * Copyright (C) 2018 Raphael Mack http://www.raphael-mack.de * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.model.conditions; /** * Model the likelihood of the activities based on its predecessors in the diary */ public class GlobalOccurrenceCondition extends Condition implements ActivityHelper.DataChangedListener { public GlobalOccurrenceCondition(ActivityHelper helper){ helper.registerDataChangeListener(this); } @Override protected void doEvaluation() { double weight = Double.parseDouble(sharedPreferences.getString(SettingsActivity.KEY_PREF_COND_OCCURRENCE, "20")); List<DiaryActivity> all = ActivityHelper.helper.getUnsortedActivities(); ArrayList<Likelihood> result = new ArrayList<>(all.size()); if(weight > 0.000001) { SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder(); SQLiteDatabase db = mOpenHelper.getReadableDatabase();
qBuilder.setTables(ActivityDiaryContract.Diary.TABLE_NAME + " D, " + ActivityDiaryContract.DiaryActivity.TABLE_NAME + " A");
0
2023-12-02 12:36:40+00:00
24k
Ethylene9160/Chess
src/chess/main/WebStartPanel.java
[ { "identifier": "PanelBase", "path": "src/chess/panels/PanelBase.java", "snippet": "public abstract class PanelBase extends JPanel {\n public PanelType type;\n protected int ax=-1,ay=-1,bx=-1,by=-1;\n protected int currentPlayer, xOld, yOld;\n\n protected Point aOldPoint = new Point(0,0), aC...
import chess.panels.PanelBase; import chess.panels.WebButtons; import chess.panels.WebPanel; import chess.util.Constants; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import static chess.panels.PanelBase.FIRST;
16,347
package chess.main; public class WebStartPanel extends JPanel { private WebPanel webPanel;
package chess.main; public class WebStartPanel extends JPanel { private WebPanel webPanel;
private WebButtons webButtons;
1
2023-12-01 02:33:32+00:00
24k
ynewmark/vector-lang
compiler/src/main/java/org/vectorlang/compiler/App.java
[ { "identifier": "CodeBase", "path": "compiler/src/main/java/org/vectorlang/compiler/ast/CodeBase.java", "snippet": "public class CodeBase {\n \n private final FunctionStatement[] functions;\n\n public CodeBase(FunctionStatement[] functions) {\n this.functions = functions;\n }\n\n p...
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.List; import org.vectorlang.compiler.ast.CodeBase; import org.vectorlang.compiler.compiler.Chunk; import org.vectorlang.compiler.compiler.Compiler; import org.vectorlang.compiler.compiler.Linker; import org.vectorlang.compiler.compiler.Pruner; import org.vectorlang.compiler.compiler.TypeFailure; import org.vectorlang.compiler.compiler.Typer; import org.vectorlang.compiler.parser.Lexer; import org.vectorlang.compiler.parser.Parser; import org.vectorlang.compiler.parser.Token;
15,548
package org.vectorlang.compiler; public class App { public static void main(String[] args) { if (args.length < 1) { System.err.println("Provide a file to compile"); System.exit(1); } File file = new File(args[0]); FileReader reader; StringBuilder builder = new StringBuilder(); try { reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); bufferedReader.lines().forEach((String line) -> { builder.append(line).append('\n'); }); bufferedReader.close(); } catch (FileNotFoundException e) { System.err.println("File " + args[0] + " not found"); System.exit(1); } catch (IOException e) { System.err.println("Failed to close file"); System.exit(1); } String code = builder.toString(); Lexer lexer = new Lexer(code); List<Token> tokens = lexer.lex(); Parser parser = new Parser(); CodeBase codeBase = parser.parse(tokens); Typer typer = new Typer(); Pruner pruner = new Pruner(); org.vectorlang.compiler.compiler.Compiler compiler = new Compiler(); CodeBase typed = typer.type(codeBase); if (!typer.getFailures().isEmpty()) { System.err.println("There were the following type failures:"); for (TypeFailure failure : typer.getFailures()) { System.err.println(failure); } System.exit(1); } if (shouldOptimize(args)) { System.out.println("Optimizing..."); typed = pruner.prune(typed); } Chunk[] chunks = compiler.compile(typed);
package org.vectorlang.compiler; public class App { public static void main(String[] args) { if (args.length < 1) { System.err.println("Provide a file to compile"); System.exit(1); } File file = new File(args[0]); FileReader reader; StringBuilder builder = new StringBuilder(); try { reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); bufferedReader.lines().forEach((String line) -> { builder.append(line).append('\n'); }); bufferedReader.close(); } catch (FileNotFoundException e) { System.err.println("File " + args[0] + " not found"); System.exit(1); } catch (IOException e) { System.err.println("Failed to close file"); System.exit(1); } String code = builder.toString(); Lexer lexer = new Lexer(code); List<Token> tokens = lexer.lex(); Parser parser = new Parser(); CodeBase codeBase = parser.parse(tokens); Typer typer = new Typer(); Pruner pruner = new Pruner(); org.vectorlang.compiler.compiler.Compiler compiler = new Compiler(); CodeBase typed = typer.type(codeBase); if (!typer.getFailures().isEmpty()) { System.err.println("There were the following type failures:"); for (TypeFailure failure : typer.getFailures()) { System.err.println(failure); } System.exit(1); } if (shouldOptimize(args)) { System.out.println("Optimizing..."); typed = pruner.prune(typed); } Chunk[] chunks = compiler.compile(typed);
Linker linker = new Linker();
3
2023-11-30 04:22:36+00:00
24k
godheaven/klib-data-jdbc
src/main/java/cl/kanopus/jdbc/impl/AbstractDAO.java
[ { "identifier": "DAOInterface", "path": "src/main/java/cl/kanopus/jdbc/DAOInterface.java", "snippet": "public interface DAOInterface<T, I> {\r\n\r\n long generateID() throws DataException;\r\n\r\n void persist(T entity) throws DataException;\r\n\r\n int update(T entity) throws DataException;\r\...
import cl.kanopus.common.data.Paginator; import cl.kanopus.common.data.enums.SortOrder; import cl.kanopus.common.enums.EnumIdentifiable; import cl.kanopus.common.util.CryptographyUtils; import cl.kanopus.common.util.GsonUtils; import cl.kanopus.common.util.Utils; import cl.kanopus.jdbc.DAOInterface; import cl.kanopus.jdbc.entity.Mapping; import cl.kanopus.jdbc.entity.annotation.Column; import cl.kanopus.jdbc.entity.annotation.ColumnGroup; import cl.kanopus.jdbc.entity.annotation.JoinTable; import cl.kanopus.jdbc.entity.annotation.Table; import cl.kanopus.jdbc.entity.mapper.AbstractRowMapper; import cl.kanopus.jdbc.exception.DataException; import cl.kanopus.jdbc.impl.engine.CustomEngine; import cl.kanopus.jdbc.impl.engine.Engine; import cl.kanopus.jdbc.impl.engine.OracleEngine; import cl.kanopus.jdbc.impl.engine.PostgresEngine; import cl.kanopus.jdbc.impl.engine.SQLServerEngine; import cl.kanopus.jdbc.util.JdbcCache; import cl.kanopus.jdbc.util.QueryIterator; import cl.kanopus.jdbc.util.SQLQueryDynamic; import cl.kanopus.jdbc.util.parser.ByteaJsonListParser; import cl.kanopus.jdbc.util.parser.ByteaJsonParser; import cl.kanopus.jdbc.util.parser.EnumParser; import cl.kanopus.jdbc.util.parser.JsonListParser; import cl.kanopus.jdbc.util.parser.JsonParser; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.postgresql.util.PGobject; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall;
15,286
T object; try { object = (T) queryForObject(sql, params, rowMapper(getGenericTypeClass(), loadAll)); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected <I extends Mapping> I queryForObject(SQLQueryDynamic sqlQuery) throws DataException { return queryForObject(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), (Class<I>) sqlQuery.getClazz()); } protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz) throws DataException { return queryForObject(sql, params, clazz, true); } protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz, boolean loadAll) throws DataException { Object object; try { object = getJdbcTemplate().queryForObject(sql, params, rowMapper(clazz, loadAll)); } catch (EmptyResultDataAccessException e) { object = null; } return (I) object; } private AbstractRowMapper rowMapper(final Class clazz) { return JdbcCache.rowMapper(clazz, false); } private AbstractRowMapper rowMapper(final Class clazz, boolean loadAll) { return JdbcCache.rowMapper(clazz, loadAll); } protected int update(String sql, HashMap<String, ?> params) throws DataException { return getJdbcTemplate().update(sql, params); } @Override public int update(T object) throws DataException { return updateAny(object); } protected int updateAny(Mapping object) throws DataException { Table table = getTableName(object.getClass()); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } List<String> primaryKeys = Arrays.asList(table.keys()); HashMap<String, Object> params = prepareParams(Operation.UPDATE, object); StringBuilder sql = new StringBuilder(); sql.append("UPDATE ").append(table.name()); sql.append(" SET "); boolean firstElement = true; for (String key : params.keySet()) { if (primaryKeys.contains(key)) { continue; } sql.append(!firstElement ? "," : ""); sql.append(key).append("=:").append(key); firstElement = false; } sql.append(" WHERE "); firstElement = true; for (String key : primaryKeys) { sql.append(!firstElement ? " AND " : ""); sql.append(key).append("=:").append(key); firstElement = false; } return update(sql.toString(), params); } private Table getTableName(Class clazz) throws DataException { Table table = (Table) clazz.getAnnotation(Table.class); if (table == null) { throw new DataException("There is no annotation @Table into the class: " + clazz.getCanonicalName()); } return table; } private boolean isPrimaryKey(Table table, String field) { boolean isPrimary = false; if (table != null) { for (String key : table.keys()) { if (key.equals(field)) { isPrimary = true; break; } } } return isPrimary; } private HashMap<String, Object> prepareParams(Operation operation, Object object) throws DataException { HashMap<String, Object> params = new HashMap<>(); try { if (object != null) { Table table = object.getClass().getAnnotation(Table.class); for (Field field : object.getClass().getDeclaredFields()) { // this is for private scope field.setAccessible(true); Object value = field.get(object); Column column = field.getAnnotation(Column.class); if (column != null && ((operation == Operation.PERSIST && column.insertable()) || (operation == Operation.UPDATE && column.updatable()) || isPrimaryKey(table, column.name()))) { if (column.parser() == EnumParser.class && value instanceof EnumIdentifiable) { params.put(column.name(), ((EnumIdentifiable) value).getId()); } else if (column.parser() == EnumParser.class && value instanceof Enum) { params.put(column.name(), ((Enum) value).name()); } else if (column.parser() == JsonParser.class || column.parser() == JsonListParser.class) { PGobject jsonbObj = new PGobject(); jsonbObj.setType("json"); jsonbObj.setValue(GsonUtils.custom.toJson(value)); params.put(column.name(), jsonbObj);
package cl.kanopus.jdbc.impl; /** * This abstract class defines methods for data access that are common, * generally, all kinds of data access DAO must implement this class.Thus it is * given safely access the Connection database. The JdbcTemplate property is * kept private and gives access to the database through the methods implemented * in this AbstractDAO. * * @param <T> * @param <ID> * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @SuppressWarnings("all") public abstract class AbstractDAO<T extends Mapping, ID> implements DAOInterface<T, ID> { enum Operation { UPDATE, PERSIST } private final Class<T> genericTypeClass; protected AbstractDAO() { Type type = getClass().getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) type; genericTypeClass = (Class<T>) paramType.getActualTypeArguments()[0]; } protected abstract NamedParameterJdbcTemplate getJdbcTemplate(); private static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; protected abstract Engine getEngine(); private String createSqlPagination2Engine(SQLQueryDynamic sqlQuery) { String sql = getCustom().prepareSQL2Engine(sqlQuery.getSQL()); if (sqlQuery.isLimited()) { return getCustom().createSqlPagination(sql, sqlQuery.getLimit(), sqlQuery.getOffset()).toString(); } else { return sql; } } private String createSqlPagination(String sql, int limit, int offset) { return getCustom().createSqlPagination(sql, limit, offset).toString(); } @Override public int deleteByID(ID id) throws DataException { return deleteByID(getGenericTypeClass(), id); } protected int deleteByID(Class clazz, ID key) throws DataException { return deleteByID(clazz, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected int deleteByID(Class clazz, Object... keys) throws DataException { Table table = getTableName(clazz); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } if (table.keys().length != keys.length) { throw new DataException("It is necessary to specify the same amount keys to remove the entity: " + table.getClass().getCanonicalName()); } StringBuilder sql = new StringBuilder(); sql.append("DELETE FROM ").append(table.name()).append(" WHERE "); HashMap<String, Object> params = new HashMap<>(); for (int i = 0; i < keys.length; i++) { params.put(table.keys()[i], keys[i]); sql.append(i == 0 ? "" : " AND "); sql.append(table.keys()[i]).append("=:").append(table.keys()[i]); } return update(sql.toString(), params); } protected <T> List<T> executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params, Class<T> returnType) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters); SqlParameterSource in = new MapSqlParameterSource().addValues(params); Map<String, Object> out = sjc.execute(in); Map.Entry<String, Object> entry = out.entrySet().iterator().next(); if (entry.getValue() instanceof List<?>) { List<?> tempList = (List<?>) entry.getValue(); if (!tempList.isEmpty() && tempList.get(0).getClass().equals(returnType)) { return (List<T>) entry.getValue(); } } return new ArrayList<>(); } protected void executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters); SqlParameterSource in = new MapSqlParameterSource().addValues(params); sjc.execute(in); } protected T executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params, Class<T> returnType) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); return sjc.executeFunction(returnType, params); } protected void executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); sjc.execute(params); } protected Map<String, Object> executeProcedureOut(String name, SqlParameter[] parameters, MapSqlParameterSource params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); Map<String, Object> out = sjc.execute(params); return out; } @Override public List<T> findAll() throws DataException { Table table = getTableName(getGenericTypeClass()); SQLQueryDynamic sqlQuery = new SQLQueryDynamic(getGenericTypeClass()); if (!"[unassigned]".equals(table.defaultOrderBy())) { sqlQuery.setOrderBy(table.defaultOrderBy(), SortOrder.ASCENDING); } return (List<T>) AbstractDAO.this.find(sqlQuery); } public List findAll(Class<? extends Mapping> aClass) throws DataException { return findAll(aClass, false); } public List findAll(Class<? extends Mapping> aClass, boolean loadAll) throws DataException { //@TODO: implementar defaultOrderBy List list; try { String sql = JdbcCache.sqlBase(aClass, loadAll); list = getJdbcTemplate().query(sql, rowMapper(aClass, loadAll)); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } catch (DataException de) { throw de; } catch (Exception ex) { throw new DataException(ex.getMessage(), ex); } return list; } @Override public List<T> findTop(int limit, SortOrder sortOrder) throws DataException { Table table = getTableName(getGenericTypeClass()); StringBuilder sql = new StringBuilder(); sql.append(JdbcCache.sqlBase(getGenericTypeClass())); if (table.keys() != null) { sql.append(" ORDER BY "); for (String s : table.keys()) { sql.append(s); } sql.append(sortOrder == SortOrder.DESCENDING ? " DESC" : " ASC"); } StringBuilder customSql = getCustom().createSqlPagination(sql.toString(), limit, 0); return AbstractDAO.this.find(customSql.toString()); } public Iterator findQueryIterator(SQLQueryDynamic sqlQuery) { int limit = Utils.defaultValue(sqlQuery.getLimit(), 2500); if (!sqlQuery.isSorted()) { throw new DataException("It is necessary to specify a sort with identifier to be able to iterate over the records."); } return new QueryIterator<Map<String, Object>>(limit) { @Override public List getData(int limit, int offset) { sqlQuery.setLimit(limit); sqlQuery.setOffset(offset); List records = null; if (sqlQuery.getClazz() != null) { records = getJdbcTemplate().query(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), rowMapper(sqlQuery.getClazz(), sqlQuery.isLoadAll())); } else { records = getJdbcTemplate().queryForList(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams()); } sqlQuery.setTotalResultCount(sqlQuery.getTotalResultCount() + records.size()); return records; } }; } protected List<T> find(String sql) throws DataException { List list; try { list = getJdbcTemplate().query(sql, rowMapper(getGenericTypeClass())); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<T> find(String sql, HashMap<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().query(sql, params, rowMapper(getGenericTypeClass())); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz) throws DataException { List list; try { list = getJdbcTemplate().query(sql, params, rowMapper(clazz)); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz, int limit, int offset) throws DataException { List list; try { String sqlPagination = createSqlPagination(sql, limit, offset); list = getJdbcTemplate().query(sqlPagination, params, rowMapper(clazz)); } catch (EmptyResultDataAccessException e) { list = new ArrayList(); } return list; } protected List<?> find(SQLQueryDynamic sqlQuery) throws DataException { return find(sqlQuery, sqlQuery.getClazz()); } protected List find(SQLQueryDynamic sqlQuery, Class<? extends Mapping> clazz) throws DataException { List records = getJdbcTemplate().query(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), rowMapper(clazz, sqlQuery.isLoadAll())); if (sqlQuery.isLimited()) { long count = getJdbcTemplate().queryForObject(getCustom().prepareSQL2Engine(sqlQuery.getSQLCount()), sqlQuery.getParams(), Long.class); sqlQuery.setTotalResultCount(count); } else { sqlQuery.setTotalResultCount(records.size()); } return records; } protected Paginator findPaginator(SQLQueryDynamic sqlQuery) throws DataException { List records = find(sqlQuery, sqlQuery.getClazz()); Paginator paginator = new Paginator(); paginator.setRecords(records); paginator.setTotalRecords(sqlQuery.getTotalResultCount()); return paginator; } protected Paginator<Map<String, Object>> findMaps(SQLQueryDynamic sqlQuery) throws DataException { Paginator paginator = new Paginator(); try { List records = getJdbcTemplate().queryForList(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams()); if (sqlQuery.isLimited()) { long count = getJdbcTemplate().queryForObject(getCustom().prepareSQL2Engine(sqlQuery.getSQLCount()), sqlQuery.getParams(), Long.class); sqlQuery.setTotalResultCount(count); } else { sqlQuery.setTotalResultCount(records.size()); } paginator.setRecords(records); paginator.setTotalRecords(sqlQuery.getTotalResultCount()); } catch (EmptyResultDataAccessException e) { paginator.setRecords(new ArrayList<>()); paginator.setTotalRecords(0); } return paginator; } protected List<Map<String, Object>> findMaps(String sql, Map<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().queryForList(sql, params); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<Map<String, Object>> findMaps(String sql, Map<String, ?> params, int limit, int offset) throws DataException { List list; try { String sqlPagination = createSqlPagination(sql, limit, offset); list = getJdbcTemplate().queryForList(sqlPagination, params); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<String> findStrings(String sql, Map<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().queryForList(sql, params, String.class); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<String> findStrings(String sql, Map<String, ?> params, int limit, int offset) throws DataException { List list; try { String sqlPagination = createSqlPagination(sql, limit, offset); list = getJdbcTemplate().queryForList(sqlPagination, params, String.class); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } protected List<Long> findLongs(String sql, Map<String, ?> params) throws DataException { List list; try { list = getJdbcTemplate().queryForList(sql, params, Long.class); } catch (EmptyResultDataAccessException e) { list = new ArrayList<>(); } return list; } @Override public long generateID() throws DataException { Table table = getTableName(getGenericTypeClass()); if (table.sequence() == null) { throw new DataException("It is necessary to specify the sequence related to the entity:"); } String customSql = getCustom().createSqlNextval(table.sequence()); return queryForLong(customSql); } protected long generateAnyID(Class<? extends Mapping> clazz) throws DataException { Table table = getTableName(clazz); if (table.sequence() == null) { throw new DataException("It is necessary to specify the sequence related to the entity:"); } String customSql = getCustom().createSqlNextval(table.sequence()); return queryForLong(customSql); } @Override public T getByID(ID id) throws DataException { return (T) getByID(getGenericTypeClass(), id); } @Override public T getByID(ID key, boolean loadAll) throws DataException { return (T) getByID(getGenericTypeClass(), loadAll, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected <T extends Mapping> T getByID(Class<T> clazz, ID key) throws DataException { return getByID(clazz, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected <T extends Mapping> T getByID(Class<T> clazz, Object... keys) throws DataException { return getByID(clazz, false, keys); } protected <T extends Mapping> T getByID(Class<T> clazz, boolean loadAll, Object... keys) throws DataException { Table table = getTableName(clazz); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } if (table.keys().length != keys.length) { throw new DataException("It is necessary to specify the same keys to identify the entity: " + table.getClass().getCanonicalName()); } StringBuilder sql = new StringBuilder(); sql.append(JdbcCache.sqlBase(clazz, true)).append(" WHERE "); HashMap<String, Object> params = new HashMap<>(); for (int i = 0; i < keys.length; i++) { params.put(table.keys()[i], keys[i]); sql.append(i == 0 ? "" : " AND "); sql.append(table.keys()[i]).append("=:").append(table.keys()[i]); } return (T) queryForObject(sql.toString(), params, rowMapper(clazz, loadAll)); } private Class<T> getGenericTypeClass() { return genericTypeClass; } @Override public void persist(T object) throws DataException { persistAny(object); } protected void persistAny(Mapping object) throws DataException { Table table = getTableName(object.getClass()); HashMap<String, Object> params = prepareParams(Operation.PERSIST, object); StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO ").append(table.name()); sql.append("("); boolean firstElement = true; for (String key : params.keySet()) { sql.append(!firstElement ? "," : ""); sql.append(key); firstElement = false; } sql.append(") VALUES"); sql.append("("); firstElement = true; for (String key : params.keySet()) { sql.append(!firstElement ? "," : ""); sql.append(":").append(key); firstElement = false; } sql.append(")"); update(sql.toString(), params); } protected String queryForString(String sql, HashMap<String, ?> params) throws DataException { String object; try { object = getJdbcTemplate().queryForObject(sql, params, String.class); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected byte[] queryForBytes(String sql, HashMap<String, ?> params) throws DataException { return getJdbcTemplate().queryForObject(sql, params, byte[].class); } protected Integer queryForInteger(String sql) throws DataException { return queryForInteger(sql, null); } protected Integer queryForInteger(String sql, HashMap<String, ?> params) throws DataException { Integer object; try { object = getJdbcTemplate().queryForObject(sql, params, Integer.class); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected Long queryForLong(String sql) throws DataException { return queryForLong(sql, null); } protected Long queryForLong(String sql, HashMap<String, ?> params) throws DataException { Long object; try { object = getJdbcTemplate().queryForObject(sql, params, Long.class); } catch (EmptyResultDataAccessException e) { object = null; } return object; } private T queryForObject(String sql, HashMap<String, ?> params, AbstractRowMapper<T> rowMapper) throws DataException { T mapping; try { mapping = getJdbcTemplate().queryForObject(sql, params, rowMapper); } catch (EmptyResultDataAccessException e) { mapping = null; } return mapping; } protected T queryForObject(String sql, HashMap<String, ?> params) throws DataException { return queryForObject(sql, params, true); } protected T queryForObject(String sql, HashMap<String, ?> params, boolean loadAll) throws DataException { T object; try { object = (T) queryForObject(sql, params, rowMapper(getGenericTypeClass(), loadAll)); } catch (EmptyResultDataAccessException e) { object = null; } return object; } protected <I extends Mapping> I queryForObject(SQLQueryDynamic sqlQuery) throws DataException { return queryForObject(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), (Class<I>) sqlQuery.getClazz()); } protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz) throws DataException { return queryForObject(sql, params, clazz, true); } protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz, boolean loadAll) throws DataException { Object object; try { object = getJdbcTemplate().queryForObject(sql, params, rowMapper(clazz, loadAll)); } catch (EmptyResultDataAccessException e) { object = null; } return (I) object; } private AbstractRowMapper rowMapper(final Class clazz) { return JdbcCache.rowMapper(clazz, false); } private AbstractRowMapper rowMapper(final Class clazz, boolean loadAll) { return JdbcCache.rowMapper(clazz, loadAll); } protected int update(String sql, HashMap<String, ?> params) throws DataException { return getJdbcTemplate().update(sql, params); } @Override public int update(T object) throws DataException { return updateAny(object); } protected int updateAny(Mapping object) throws DataException { Table table = getTableName(object.getClass()); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } List<String> primaryKeys = Arrays.asList(table.keys()); HashMap<String, Object> params = prepareParams(Operation.UPDATE, object); StringBuilder sql = new StringBuilder(); sql.append("UPDATE ").append(table.name()); sql.append(" SET "); boolean firstElement = true; for (String key : params.keySet()) { if (primaryKeys.contains(key)) { continue; } sql.append(!firstElement ? "," : ""); sql.append(key).append("=:").append(key); firstElement = false; } sql.append(" WHERE "); firstElement = true; for (String key : primaryKeys) { sql.append(!firstElement ? " AND " : ""); sql.append(key).append("=:").append(key); firstElement = false; } return update(sql.toString(), params); } private Table getTableName(Class clazz) throws DataException { Table table = (Table) clazz.getAnnotation(Table.class); if (table == null) { throw new DataException("There is no annotation @Table into the class: " + clazz.getCanonicalName()); } return table; } private boolean isPrimaryKey(Table table, String field) { boolean isPrimary = false; if (table != null) { for (String key : table.keys()) { if (key.equals(field)) { isPrimary = true; break; } } } return isPrimary; } private HashMap<String, Object> prepareParams(Operation operation, Object object) throws DataException { HashMap<String, Object> params = new HashMap<>(); try { if (object != null) { Table table = object.getClass().getAnnotation(Table.class); for (Field field : object.getClass().getDeclaredFields()) { // this is for private scope field.setAccessible(true); Object value = field.get(object); Column column = field.getAnnotation(Column.class); if (column != null && ((operation == Operation.PERSIST && column.insertable()) || (operation == Operation.UPDATE && column.updatable()) || isPrimaryKey(table, column.name()))) { if (column.parser() == EnumParser.class && value instanceof EnumIdentifiable) { params.put(column.name(), ((EnumIdentifiable) value).getId()); } else if (column.parser() == EnumParser.class && value instanceof Enum) { params.put(column.name(), ((Enum) value).name()); } else if (column.parser() == JsonParser.class || column.parser() == JsonListParser.class) { PGobject jsonbObj = new PGobject(); jsonbObj.setType("json"); jsonbObj.setValue(GsonUtils.custom.toJson(value)); params.put(column.name(), jsonbObj);
} else if (column.parser() == ByteaJsonParser.class || column.parser() == ByteaJsonListParser.class) {
12
2023-11-27 18:25:00+00:00
24k
aliyun/aliyun-pairec-config-java-sdk
src/main/java/com/aliyun/openservices/pairec/ExperimentClient.java
[ { "identifier": "ApiClient", "path": "src/main/java/com/aliyun/openservices/pairec/api/ApiClient.java", "snippet": "public class ApiClient {\n private Configuration configuration;\n Client client;\n\n private CrowdApi crowdApi;\n\n private SceneApi sceneApi;\n\n private ExperimentRoomApi ...
import com.aliyun.openservices.pairec.api.ApiClient; import com.aliyun.openservices.pairec.common.Constants; import com.aliyun.openservices.pairec.model.DefaultSceneParams; import com.aliyun.openservices.pairec.model.EmptySceneParams; import com.aliyun.openservices.pairec.model.Experiment; import com.aliyun.openservices.pairec.model.ExperimentContext; import com.aliyun.openservices.pairec.model.ExperimentGroup; import com.aliyun.openservices.pairec.model.ExperimentResult; import com.aliyun.openservices.pairec.model.ExperimentRoom; import com.aliyun.openservices.pairec.model.Layer; import com.aliyun.openservices.pairec.model.Param; import com.aliyun.openservices.pairec.model.Scene; import java.math.BigInteger; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.aliyun.openservices.pairec.model.SceneParams; import com.aliyun.openservices.pairec.util.FNV; import org.apache.commons.codec.digest.DigestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
17,486
package com.aliyun.openservices.pairec; public class ExperimentClient { public static Logger logger = LoggerFactory.getLogger(ExperimentClient.class); private ApiClient apiClient ; /** * cache experiment data by per scene */ Map<String, Scene> sceneMap = new HashMap<>(); /** * cache param data by per scene */ Map<String, SceneParams> sceneParamData = new HashMap<>(); ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); boolean started = false; public ExperimentClient(ApiClient apiClient) { this.apiClient = apiClient; } private static class ExperimentWorker extends Thread { ExperimentClient experimentClient; public ExperimentWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadExperimentData(); } catch (Exception e) { logger.error(e.getMessage()); } } } private static class SceneParamWorker extends Thread { ExperimentClient experimentClient; public SceneParamWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadSceneParamsData(); } catch (Exception e) { logger.error(e.getMessage()); } } } public synchronized void init() throws Exception { if (started) { return; } logger.debug("experiment client init"); loadExperimentData(); loadSceneParamsData(); ExperimentWorker worker = new ExperimentWorker(this); scheduledThreadPool.scheduleWithFixedDelay(worker, 60, 60, TimeUnit.SECONDS); SceneParamWorker sceneParamWorker = new SceneParamWorker(this); scheduledThreadPool.scheduleWithFixedDelay(sceneParamWorker, 60, 60, TimeUnit.SECONDS); started = true; } /** * load experiment data from ab server * * @throws Exception */ public void loadExperimentData() throws Exception { Map<String, Scene> sceneData = new HashMap<>(); List<Scene> scenes= apiClient.getSceneApi().listAllScenes(); for (Scene scene : scenes) { List<ExperimentRoom> experimentRooms = apiClient.getExperimentRoomApi().listExperimentRooms(apiClient.getConfiguration().getEnvironment(),
package com.aliyun.openservices.pairec; public class ExperimentClient { public static Logger logger = LoggerFactory.getLogger(ExperimentClient.class); private ApiClient apiClient ; /** * cache experiment data by per scene */ Map<String, Scene> sceneMap = new HashMap<>(); /** * cache param data by per scene */ Map<String, SceneParams> sceneParamData = new HashMap<>(); ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); boolean started = false; public ExperimentClient(ApiClient apiClient) { this.apiClient = apiClient; } private static class ExperimentWorker extends Thread { ExperimentClient experimentClient; public ExperimentWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadExperimentData(); } catch (Exception e) { logger.error(e.getMessage()); } } } private static class SceneParamWorker extends Thread { ExperimentClient experimentClient; public SceneParamWorker(ExperimentClient client) { experimentClient = client; super.setDaemon(true); } @Override public void run() { try { experimentClient.loadSceneParamsData(); } catch (Exception e) { logger.error(e.getMessage()); } } } public synchronized void init() throws Exception { if (started) { return; } logger.debug("experiment client init"); loadExperimentData(); loadSceneParamsData(); ExperimentWorker worker = new ExperimentWorker(this); scheduledThreadPool.scheduleWithFixedDelay(worker, 60, 60, TimeUnit.SECONDS); SceneParamWorker sceneParamWorker = new SceneParamWorker(this); scheduledThreadPool.scheduleWithFixedDelay(sceneParamWorker, 60, 60, TimeUnit.SECONDS); started = true; } /** * load experiment data from ab server * * @throws Exception */ public void loadExperimentData() throws Exception { Map<String, Scene> sceneData = new HashMap<>(); List<Scene> scenes= apiClient.getSceneApi().listAllScenes(); for (Scene scene : scenes) { List<ExperimentRoom> experimentRooms = apiClient.getExperimentRoomApi().listExperimentRooms(apiClient.getConfiguration().getEnvironment(),
scene.getSceneId(), Constants.ExpRoom_Status_Online);
1
2023-11-29 06:27:36+00:00
24k
tuxiaobei-scu/SCU-CCSOJ-Backend
DataBackup/src/main/java/top/hcode/hoj/manager/oj/DiscussionManager.java
[ { "identifier": "HOJAccessEnum", "path": "DataBackup/src/main/java/top/hcode/hoj/annotation/HOJAccessEnum.java", "snippet": "public enum HOJAccessEnum {\n /**\n * 公共讨论区\n */\n PUBLIC_DISCUSSION,\n\n /**\n * 团队讨论区\n */\n GROUP_DISCUSSION,\n\n /**\n * 比赛评论\n */\n ...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import top.hcode.hoj.annotation.HOJAccessEnum; import top.hcode.hoj.common.exception.StatusFailException; import top.hcode.hoj.common.exception.StatusForbiddenException; import top.hcode.hoj.common.exception.StatusNotFoundException; import top.hcode.hoj.dao.discussion.DiscussionEntityService; import top.hcode.hoj.dao.discussion.DiscussionLikeEntityService; import top.hcode.hoj.dao.discussion.DiscussionReportEntityService; import top.hcode.hoj.dao.problem.CategoryEntityService; import top.hcode.hoj.dao.problem.ProblemEntityService; import top.hcode.hoj.dao.user.UserAcproblemEntityService; import top.hcode.hoj.exception.AccessException; import top.hcode.hoj.pojo.entity.discussion.Discussion; import top.hcode.hoj.pojo.entity.discussion.DiscussionLike; import top.hcode.hoj.pojo.entity.discussion.DiscussionReport; import top.hcode.hoj.pojo.entity.problem.Category; import top.hcode.hoj.pojo.entity.problem.Problem; import top.hcode.hoj.pojo.entity.user.UserAcproblem; import top.hcode.hoj.pojo.vo.ConfigVo; import top.hcode.hoj.pojo.vo.DiscussionVo; import top.hcode.hoj.pojo.vo.UserRolesVo; import top.hcode.hoj.utils.Constants; import top.hcode.hoj.utils.RedisUtils; import top.hcode.hoj.validator.AccessValidator; import top.hcode.hoj.validator.GroupValidator; import java.util.List;
14,628
package top.hcode.hoj.manager.oj; /** * @Author: Himit_ZH * @Date: 2022/3/11 15:21 * @Description: */ @Component public class DiscussionManager { @Autowired private DiscussionEntityService discussionEntityService; @Autowired private DiscussionLikeEntityService discussionLikeEntityService; @Autowired private CategoryEntityService categoryEntityService; @Autowired private DiscussionReportEntityService discussionReportEntityService; @Autowired private RedisUtils redisUtils; @Autowired private UserAcproblemEntityService userAcproblemEntityService; @Autowired private ProblemEntityService problemEntityService; @Autowired private GroupValidator groupValidator; @Autowired private AccessValidator accessValidator; @Autowired private ConfigVo configVo;
package top.hcode.hoj.manager.oj; /** * @Author: Himit_ZH * @Date: 2022/3/11 15:21 * @Description: */ @Component public class DiscussionManager { @Autowired private DiscussionEntityService discussionEntityService; @Autowired private DiscussionLikeEntityService discussionLikeEntityService; @Autowired private CategoryEntityService categoryEntityService; @Autowired private DiscussionReportEntityService discussionReportEntityService; @Autowired private RedisUtils redisUtils; @Autowired private UserAcproblemEntityService userAcproblemEntityService; @Autowired private ProblemEntityService problemEntityService; @Autowired private GroupValidator groupValidator; @Autowired private AccessValidator accessValidator; @Autowired private ConfigVo configVo;
public IPage<Discussion> getDiscussionList(Integer limit,
11
2023-12-03 14:15:51+00:00
24k
yichenhsiaonz/EscAIpe-room-final
src/main/java/nz/ac/auckland/se206/controllers/ControlRoomController.java
[ { "identifier": "App", "path": "src/main/java/nz/ac/auckland/se206/App.java", "snippet": "public class App extends Application {\n\n private static Scene scene;\n public static ControlRoomController controlRoomController;\n public static LabController labController;\n public static KitchenController...
import java.io.IOException; import javafx.animation.FadeTransition; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.shape.Circle; import javafx.util.Duration; import nz.ac.auckland.se206.App; import nz.ac.auckland.se206.GameState; import nz.ac.auckland.se206.SceneManager.AppUi; import nz.ac.auckland.se206.TextToSpeechManager; import nz.ac.auckland.se206.gpt.ChatMessage; import nz.ac.auckland.se206.gpt.GptPromptEngineering; import nz.ac.auckland.se206.gpt.openai.ApiProxyException; import nz.ac.auckland.se206.gpt.openai.ChatCompletionRequest; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult.Choice;
17,015
AnchorPane.setBottomAnchor(blackRectangle, 0.0); AnchorPane.setLeftAnchor(blackRectangle, 0.0); AnchorPane.setRightAnchor(blackRectangle, 0.0); // Add the black rectangle to AnchorPane anchorPane.getChildren().add(blackRectangle); // Create a fade transition FadeTransition fadeToBlack = new FadeTransition(Duration.seconds(5), blackRectangle); fadeToBlack.setFromValue(0.0); fadeToBlack.setToValue(1.0); // Change to end scene when the fade animation is complete fadeToBlack.setOnFinished( event -> { try { App.setRoot(AppUi.ENDING); } catch (IOException e) { e.printStackTrace(); System.out.println("Error changing to ending scene"); } }); fadeToBlack.play(); } // get image of loading AI public ImageView getLoadingAi() { return loadingAi; } // get image of talking AI public ImageView getTalkingAi() { return talkingAi; } @FXML private void onBackToMenu(ActionEvent event) throws IOException { TextToSpeechManager.cutOff(); GameState.stopAllThreads(); GameState.stopSound(); App.setRoot(AppUi.MENU); } @FXML private void onMute(ActionEvent event) { GameState.toggleMuted(); } public void fadeIn() { GameState.fadeIn(room); } // keypad methods // Implement keypad functionality @FXML private void onOneClicked() { appendNumber("1"); } @FXML private void onTwoClicked() { appendNumber("2"); } @FXML private void onThreeClicked() { appendNumber("3"); } @FXML private void onFourClicked() { appendNumber("4"); } @FXML private void onFiveClicked() { appendNumber("5"); } @FXML private void onSixClicked() { appendNumber("6"); } @FXML private void onSevenClicked() { appendNumber("7"); } @FXML private void onEightClicked() { appendNumber("8"); } @FXML private void onNineClicked() { appendNumber("9"); } @FXML private void onZeroClicked() { appendNumber("0"); } /** Deletes the last entered digit of the code. */ @FXML private void onDeleteClicked() { if (code.length() > 0) { code = code.substring(0, code.length() - 1); codeText.setText(code); } } /** * Checks if the code is correct. * * @throws ApiProxyException if there is an error communicating with the API proxy */ @FXML
package nz.ac.auckland.se206.controllers; /** Controller class for the Control Room. */ public class ControlRoomController { static ControlRoomController instance; @FXML private AnchorPane contentPane; @FXML private ImageView computer; @FXML private ImageView keypad; @FXML private ImageView exitDoor; @FXML private ImageView rightArrow; @FXML private ImageView rightGlowArrow; @FXML private ImageView leftArrow; @FXML private ImageView leftGlowArrow; @FXML private ImageView computerGlow; @FXML private ImageView exitGlow; @FXML private ImageView keypadGlow; @FXML private ImageView character; @FXML private ImageView running; @FXML private AnchorPane room; @FXML private HBox dialogueHorizontalBox; @FXML private Pane inventoryPane; @FXML private VBox hintVerticalBox; @FXML private VBox bottomVerticalBox; @FXML private ImageView neutralAi; @FXML private ImageView loadingAi; @FXML private ImageView talkingAi; @FXML private Circle rightDoorMarker; @FXML private Circle leftDoorMarker; @FXML private Circle computerMarker; @FXML private Circle keypadMarker; @FXML private Circle centerDoorMarker; @FXML private Button muteButton; // elements of keypad @FXML private AnchorPane keyPadAnchorPane; @FXML private TextField codeText; // elements of computer @FXML private AnchorPane computerAnchorPane; @FXML private AnchorPane computerLoginAnchorPane; @FXML private Label gptLabel; @FXML private Button enterButton; @FXML private TextField inputText; @FXML private AnchorPane computerSignedInAnchorPane; @FXML private ImageView computerDocumentIcon; @FXML private ImageView computerPrintIcon; @FXML private ImageView computerCatsIcon; @FXML private Image document = new Image("images/Computer/document.png"); @FXML private Image print = new Image("images/Computer/printer.png"); @FXML private Image cats = new Image("images/Computer/image.png"); @FXML private Image documentHover = new Image("images/Computer/document_hover.png"); @FXML private Image printHover = new Image("images/Computer/printer_hover.png"); @FXML private Image catsHover = new Image("images/Computer/image_hover.png"); @FXML private AnchorPane computerPrintWindowAnchorPane; @FXML private ImageView printIcon; @FXML private ImageView printIconComplete; @FXML private Button printButton; @FXML private Label printLabel; @FXML private AnchorPane computerTextWindowAnchorPane; @FXML private TextArea computerDoorCodeTextArea; @FXML private AnchorPane computerImageWindowAnchorPane; @FXML private Label riddleLabel; private String code = ""; private ChatCompletionRequest endingChatCompletionRequest; private ChatCompletionRequest computerChatCompletionRequest; private boolean firstOpeningTextFile; /** This method initializes the control room for when the user first enters it. */ public void initialize() { SharedElements.initialize( room, bottomVerticalBox, inventoryPane, dialogueHorizontalBox, muteButton, contentPane); // computer initialization firstOpeningTextFile = true; try { computerChatCompletionRequest = new ChatCompletionRequest().setN(1).setTemperature(0.2).setTopP(0.5).setMaxTokens(100); runGpt( new ChatMessage("user", GptPromptEngineering.getRiddle(GameState.getRiddleAnswer())), true); computerDoorCodeTextArea.setText( "TOP SECRET DOOR CODE: \n\n__" + GameState.getSecondDigits() + "__\n\n\n\n" + "(If only I could remember the other four digits)"); } catch (Exception e) { e.printStackTrace(); } GameState.goToInstant( centerDoorMarker.getLayoutX(), centerDoorMarker.getLayoutY(), character, running); instance = this; } /** * Handles the click event on the computer. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML private void clickComputer(MouseEvent event) throws IOException { System.out.println("computer clicked"); try { // move character to clicked location GameState.goTo(computerMarker.getLayoutX(), computerMarker.getLayoutY(), character, running); // flag the current puzzle as the computer puzzle for hints // set root to the computer // enable movement after delay Runnable accessComputer = () -> { GameState.setPuzzleComputer(); computerAnchorPane.setVisible(true); }; GameState.setOnMovementComplete(accessComputer); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to computer when hover @FXML private void onComputerHovered(MouseEvent event) { computerGlow.setVisible(true); } @FXML private void onComputerUnhovered(MouseEvent event) { computerGlow.setVisible(false); } /** * Handles the click event on the exit door. * * @param event the mouse event */ @FXML private void clickExit(MouseEvent event) { try { // move character to center door marker position GameState.goTo( centerDoorMarker.getLayoutX(), centerDoorMarker.getLayoutY(), character, running); Runnable leaveRoom = () -> { System.out.println("exit door clicked"); if (GameState.isExitUnlocked) { // if the exit is unlocked, fade to black for ending scene TextToSpeechManager.cutOff(); GameState.stopAllThreads(); GameState.stopSound(); GameState.playSound("/sounds/gate-open.m4a"); fadeBlack(); } else { String message = "The exit is locked and will not budge"; // otherwise, display notification in chat SharedElements.appendChat(message); SharedElements.chatBubbleSpeak(message); } }; GameState.setOnMovementComplete(leaveRoom); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to exit door when hover @FXML private void onExitHovered(MouseEvent event) { exitGlow.setVisible(true); } @FXML private void onExitUnhovered(MouseEvent event) { exitGlow.setVisible(false); } /** * Handles the click event on the keypad. * * @param event the mouse event * @throws IOException throws an exception if there is an error loading the keypad view */ @FXML private void clickKeypad(MouseEvent event) throws IOException { System.out.println("keypad clicked"); try { // check if the character is already moving to prevent multiple clicks // move character to clicked location GameState.goTo(keypadMarker.getLayoutX(), keypadMarker.getLayoutY(), character, running); // set root to the keypad after delay and enable movement Runnable accessKeypad = () -> { keyPadAnchorPane.setVisible(true); }; GameState.setOnMovementComplete(accessKeypad); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to keypad when hover @FXML private void onKeypadHovered(MouseEvent event) { keypadGlow.setVisible(true); } @FXML private void onKeypadUnhovered(MouseEvent event) { keypadGlow.setVisible(false); } /** * Handles the click event on the right arrow. * * @param event the mouse event */ @FXML private void onRightClicked(MouseEvent event) throws IOException { try { // move character to clicked location GameState.goTo( rightDoorMarker.getLayoutX(), rightDoorMarker.getLayoutY(), character, running); // set root to the kitchen after delay and enable movement Runnable leaveRoom = () -> { GameState.playSound("/sounds/door-opening.m4a"); GameState.fadeOut(room); Runnable loadKitchen = () -> { try { App.setRoot(AppUi.KITCHEN); KitchenController.instance.fadeIn(); } catch (IOException e) { e.printStackTrace(); } }; GameState.delayRun(loadKitchen, 1); }; GameState.setOnMovementComplete(leaveRoom); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to right arrow when hover @FXML private void onRightHovered(MouseEvent event) { rightGlowArrow.setVisible(true); } @FXML private void onRightUnhovered(MouseEvent event) { rightGlowArrow.setVisible(false); } /** * Handles the click event on the left arrow. * * @param event the mouse event */ @FXML private void onLeftClicked(MouseEvent event) { try { // move character to clicked location GameState.goTo(leftDoorMarker.getLayoutX(), leftDoorMarker.getLayoutY(), character, running); // set root to the lab after delay and enable movement Runnable leaveRoom = () -> { GameState.playSound("/sounds/door-opening.m4a"); GameState.fadeOut(room); Runnable loadLab = () -> { try { App.setRoot(AppUi.LAB); LabController.instance.fadeIn(); } catch (IOException e) { e.printStackTrace(); } }; GameState.delayRun(loadLab, 1); }; GameState.setOnMovementComplete(leaveRoom); GameState.startMoving(); } catch (Exception e) { e.printStackTrace(); } } // add glow highlight to left arrow when hover @FXML private void onLeftHovered(MouseEvent event) { leftGlowArrow.setVisible(true); } @FXML private void onLeftUnhovered(MouseEvent event) { leftGlowArrow.setVisible(false); } /** * 'Consumes' the mouse event, preventing it from being registered. * * @param event the mouse event */ @FXML private void consumeMouseEvent(MouseEvent event) { System.out.println("mouse event consumed"); System.out.println(event.getSource()); event.consume(); } /** * Handles the mouse click event on the room, moving the character to the clicked location. * * @param event the mouse event */ @FXML private void onMoveCharacter(MouseEvent event) { // check if the character is already moving to prevent multiple clicks // play click animation GameState.onCharacterMovementClick(event, room); // move character to clicked location double mouseX = event.getX(); double mouseY = event.getY(); GameState.goTo(mouseX, mouseY, character, running); GameState.startMoving(); } /** This method fades the room into black for transitions. */ public void fadeBlack() { // stop timer GameState.stopTimer(); // Create a black rectangle that covers the entire AnchorPane AnchorPane anchorPane = contentPane; AnchorPane blackRectangle = new AnchorPane(); blackRectangle.setStyle("-fx-background-color: black;"); blackRectangle.setOpacity(0.0); AnchorPane.setTopAnchor(blackRectangle, 0.0); AnchorPane.setBottomAnchor(blackRectangle, 0.0); AnchorPane.setLeftAnchor(blackRectangle, 0.0); AnchorPane.setRightAnchor(blackRectangle, 0.0); // Add the black rectangle to AnchorPane anchorPane.getChildren().add(blackRectangle); // Create a fade transition FadeTransition fadeToBlack = new FadeTransition(Duration.seconds(5), blackRectangle); fadeToBlack.setFromValue(0.0); fadeToBlack.setToValue(1.0); // Change to end scene when the fade animation is complete fadeToBlack.setOnFinished( event -> { try { App.setRoot(AppUi.ENDING); } catch (IOException e) { e.printStackTrace(); System.out.println("Error changing to ending scene"); } }); fadeToBlack.play(); } // get image of loading AI public ImageView getLoadingAi() { return loadingAi; } // get image of talking AI public ImageView getTalkingAi() { return talkingAi; } @FXML private void onBackToMenu(ActionEvent event) throws IOException { TextToSpeechManager.cutOff(); GameState.stopAllThreads(); GameState.stopSound(); App.setRoot(AppUi.MENU); } @FXML private void onMute(ActionEvent event) { GameState.toggleMuted(); } public void fadeIn() { GameState.fadeIn(room); } // keypad methods // Implement keypad functionality @FXML private void onOneClicked() { appendNumber("1"); } @FXML private void onTwoClicked() { appendNumber("2"); } @FXML private void onThreeClicked() { appendNumber("3"); } @FXML private void onFourClicked() { appendNumber("4"); } @FXML private void onFiveClicked() { appendNumber("5"); } @FXML private void onSixClicked() { appendNumber("6"); } @FXML private void onSevenClicked() { appendNumber("7"); } @FXML private void onEightClicked() { appendNumber("8"); } @FXML private void onNineClicked() { appendNumber("9"); } @FXML private void onZeroClicked() { appendNumber("0"); } /** Deletes the last entered digit of the code. */ @FXML private void onDeleteClicked() { if (code.length() > 0) { code = code.substring(0, code.length() - 1); codeText.setText(code); } } /** * Checks if the code is correct. * * @throws ApiProxyException if there is an error communicating with the API proxy */ @FXML
private void onEnterClicked() throws ApiProxyException {
6
2023-12-02 04:57:43+00:00
24k
nageoffer/shortlink
project/src/main/java/com/nageoffer/shortlink/project/service/impl/ShortLinkServiceImpl.java
[ { "identifier": "ClientException", "path": "project/src/main/java/com/nageoffer/shortlink/project/common/convention/exception/ClientException.java", "snippet": "public class ClientException extends AbstractException {\n\n public ClientException(IErrorCode errorCode) {\n this(null, null, errorC...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.Week; import cn.hutool.core.lang.UUID; import cn.hutool.core.text.StrBuilder; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; 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.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.nageoffer.shortlink.project.common.convention.exception.ClientException; import com.nageoffer.shortlink.project.common.convention.exception.ServiceException; import com.nageoffer.shortlink.project.common.enums.VailDateTypeEnum; import com.nageoffer.shortlink.project.config.GotoDomainWhiteListConfiguration; import com.nageoffer.shortlink.project.dao.entity.LinkAccessLogsDO; import com.nageoffer.shortlink.project.dao.entity.LinkAccessStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkBrowserStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkDeviceStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkLocaleStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkNetworkStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkOsStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkStatsTodayDO; import com.nageoffer.shortlink.project.dao.entity.ShortLinkDO; import com.nageoffer.shortlink.project.dao.entity.ShortLinkGotoDO; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessLogsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkBrowserStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkDeviceStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkLocaleStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkNetworkStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkOsStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkStatsTodayMapper; import com.nageoffer.shortlink.project.dao.mapper.ShortLinkGotoMapper; import com.nageoffer.shortlink.project.dao.mapper.ShortLinkMapper; import com.nageoffer.shortlink.project.dto.biz.ShortLinkStatsRecordDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkBatchCreateReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkCreateReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkPageReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkUpdateReqDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkBaseInfoRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkBatchCreateRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkCreateRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkGroupCountQueryRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkPageRespDTO; import com.nageoffer.shortlink.project.mq.producer.DelayShortLinkStatsProducer; import com.nageoffer.shortlink.project.service.LinkStatsTodayService; import com.nageoffer.shortlink.project.service.ShortLinkService; import com.nageoffer.shortlink.project.toolkit.HashUtil; import com.nageoffer.shortlink.project.toolkit.LinkUtil; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.redisson.api.RBloomFilter; import org.redisson.api.RLock; import org.redisson.api.RReadWriteLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DuplicateKeyException; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.GOTO_IS_NULL_SHORT_LINK_KEY; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.GOTO_SHORT_LINK_KEY; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.LOCK_GID_UPDATE_KEY; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.LOCK_GOTO_SHORT_LINK_KEY; import static com.nageoffer.shortlink.project.common.constant.ShortLinkConstant.AMAP_REMOTE_URL;
15,625
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nageoffer.shortlink.project.service.impl; /** * 短链接接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class ShortLinkServiceImpl extends ServiceImpl<ShortLinkMapper, ShortLinkDO> implements ShortLinkService { private final RBloomFilter<String> shortUriCreateCachePenetrationBloomFilter; private final ShortLinkGotoMapper shortLinkGotoMapper; private final StringRedisTemplate stringRedisTemplate; private final RedissonClient redissonClient; private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper; private final LinkOsStatsMapper linkOsStatsMapper; private final LinkBrowserStatsMapper linkBrowserStatsMapper; private final LinkAccessLogsMapper linkAccessLogsMapper; private final LinkDeviceStatsMapper linkDeviceStatsMapper; private final LinkNetworkStatsMapper linkNetworkStatsMapper; private final LinkStatsTodayMapper linkStatsTodayMapper; private final LinkStatsTodayService linkStatsTodayService; private final DelayShortLinkStatsProducer delayShortLinkStatsProducer; private final GotoDomainWhiteListConfiguration gotoDomainWhiteListConfiguration; @Value("${short-link.stats.locale.amap-key}") private String statsLocaleAmapKey; @Value("${short-link.domain.default}") private String createShortLinkDefaultDomain; @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.nageoffer.shortlink.project.service.impl; /** * 短链接接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class ShortLinkServiceImpl extends ServiceImpl<ShortLinkMapper, ShortLinkDO> implements ShortLinkService { private final RBloomFilter<String> shortUriCreateCachePenetrationBloomFilter; private final ShortLinkGotoMapper shortLinkGotoMapper; private final StringRedisTemplate stringRedisTemplate; private final RedissonClient redissonClient; private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper; private final LinkOsStatsMapper linkOsStatsMapper; private final LinkBrowserStatsMapper linkBrowserStatsMapper; private final LinkAccessLogsMapper linkAccessLogsMapper; private final LinkDeviceStatsMapper linkDeviceStatsMapper; private final LinkNetworkStatsMapper linkNetworkStatsMapper; private final LinkStatsTodayMapper linkStatsTodayMapper; private final LinkStatsTodayService linkStatsTodayService; private final DelayShortLinkStatsProducer delayShortLinkStatsProducer; private final GotoDomainWhiteListConfiguration gotoDomainWhiteListConfiguration; @Value("${short-link.stats.locale.amap-key}") private String statsLocaleAmapKey; @Value("${short-link.domain.default}") private String createShortLinkDefaultDomain; @Override
public ShortLinkCreateRespDTO createShortLink(ShortLinkCreateReqDTO requestParam) {
26
2023-11-19 16:04:32+00:00
24k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/parser/HitsResultParser.java
[ { "identifier": "Constants", "path": "src/main/java/com/ly/ckibana/constants/Constants.java", "snippet": "public class Constants {\n\n public static final String HEADER_ELASTICSEARCH = \"Elasticsearch\";\n\n public static final String HEADER_X_ELASTIC_PRODUCT = \"X-elastic-product\";\n\n public...
import com.alibaba.fastjson2.JSONObject; import com.ly.ckibana.constants.Constants; import com.ly.ckibana.constants.SqlConstants; import com.ly.ckibana.model.compute.Range; import com.ly.ckibana.model.enums.SortType; import com.ly.ckibana.model.request.CkRequest; import com.ly.ckibana.model.request.CkRequestContext; import com.ly.ckibana.model.request.SortedField; import com.ly.ckibana.model.response.DocValue; import com.ly.ckibana.model.response.Hit; import com.ly.ckibana.model.response.HitsOptimizedResult; import com.ly.ckibana.model.response.Response; import com.ly.ckibana.service.CkService; import com.ly.ckibana.util.DateUtils; import com.ly.ckibana.util.JSONUtils; import com.ly.ckibana.util.ProxyUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
14,730
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ly.ckibana.parser; /** * 封装结果类. */ @Slf4j @Service public class HitsResultParser { @Resource private CkService ckService; /** * 查询hit *. * * @param ckRequestContext ckRequestContext * @param response response * @throws Exception Exception */ public void queryHits(CkRequestContext ckRequestContext, Response response) throws Exception { if (ckRequestContext.getSize() > 0) { CkRequest hitsRequest = buildHitRequest(ckRequestContext); optimizeSearchTimeRange(hitsRequest, ckRequestContext, response); String optimizedSql = hitsRequest.buildToStr(); queryHitsFromCk(ckRequestContext, response, optimizedSql); response.getSqls().add(String.format("%s", optimizedSql)); } } /** * 查询count. * * @param ckRequestContext ckRequestContext * @param response response * @return long count * @throws Exception Exception */ public long queryTotalCount(CkRequestContext ckRequestContext, Response response) throws Exception { long result = 0; String sql = getTotalCountQuerySql(ckRequestContext); Pair<List<JSONObject>, Boolean> countResultAndStatus = ckService.queryDataWithCacheAndStatus(ckRequestContext, sql); if (!countResultAndStatus.getLeft().isEmpty()) {
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ly.ckibana.parser; /** * 封装结果类. */ @Slf4j @Service public class HitsResultParser { @Resource private CkService ckService; /** * 查询hit *. * * @param ckRequestContext ckRequestContext * @param response response * @throws Exception Exception */ public void queryHits(CkRequestContext ckRequestContext, Response response) throws Exception { if (ckRequestContext.getSize() > 0) { CkRequest hitsRequest = buildHitRequest(ckRequestContext); optimizeSearchTimeRange(hitsRequest, ckRequestContext, response); String optimizedSql = hitsRequest.buildToStr(); queryHitsFromCk(ckRequestContext, response, optimizedSql); response.getSqls().add(String.format("%s", optimizedSql)); } } /** * 查询count. * * @param ckRequestContext ckRequestContext * @param response response * @return long count * @throws Exception Exception */ public long queryTotalCount(CkRequestContext ckRequestContext, Response response) throws Exception { long result = 0; String sql = getTotalCountQuerySql(ckRequestContext); Pair<List<JSONObject>, Boolean> countResultAndStatus = ckService.queryDataWithCacheAndStatus(ckRequestContext, sql); if (!countResultAndStatus.getLeft().isEmpty()) {
result = countResultAndStatus.getLeft().get(0).getLongValue(SqlConstants.DEFAULT_COUNT_NAME);
1
2023-11-21 09:12:07+00:00
24k
lidaofu-hub/j_zlm_sdk
src/main/java/com/aizuda/test/Test.java
[ { "identifier": "IMKProxyPlayCloseCallBack", "path": "src/main/java/com/aizuda/callback/IMKProxyPlayCloseCallBack.java", "snippet": "public interface IMKProxyPlayCloseCallBack extends Callback {\n /**\n * MediaSource.close()回调事件\n * 在选择关闭一个关联的MediaSource时,将会最终触发到该回调\n * 你应该通过该事件调用mk_proxy...
import com.aizuda.callback.IMKProxyPlayCloseCallBack; import com.aizuda.core.ZLMApi; import com.aizuda.structure.MK_EVENTS; import com.aizuda.structure.MK_INI; import com.aizuda.structure.MK_PROXY_PLAYER; import com.sun.jna.Native; import com.sun.jna.Pointer;
18,253
package com.aizuda.test; /** * 测试程序 展示了服务器配置 系统配置 流媒体服务启动 回调监听 拉流代理 * * @author lidaofu * @since 2023/11/23 **/ public class Test { //动态链接库放在/resource/win32-x86-64&/resource/linux-x86-64下JNA会自动查找目录 //public static ZLMApi ZLM_API = Native.load("mk_api", ZLMApi.class); //Windows环境测试 public static ZLMApi ZLM_API = Native.load("D:\\ZLMediaKit\\source\\release\\windows\\Debug\\mk_api.dll", ZLMApi.class); //Linux环境测试 //public static ZLMApi ZLM_API = Native.load("/opt/media/libmk_api.so", ZLMApi.class); public static void main(String[] args) throws InterruptedException { //初始化环境配置 MK_INI mkIni = ZLM_API.mk_ini_default(); //配置参数 全部配置参数及说明见(resources/conf.ini) 打开自动关流 对应conf.ini中配置[protocol] auto_close ZLM_API.mk_ini_set_option_int(mkIni, "protocol.auto_close", 1); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_fmp4", 0); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_hls", 0); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_ts", 0); //全局回调 全部回调见MK_EVENTS内所有的回调属性,有些需要去实现,不然流无法播放或者无法推流 MK_EVENTS mkEvents = new MK_EVENTS(); //流状态改变回调 mkEvents.on_mk_media_changed = (regist, sender) -> { System.out.println("这里是流改变回调通知:" + regist); }; //无人观看回调 mkEvents.on_mk_media_no_reader = sender -> { System.out.println("这里是无人观看回调通知"); ZLM_API.mk_media_source_close(sender, 1); }; //播放回调可做播放鉴权 mkEvents.on_mk_media_play = (url_info, invoker, sender) -> { //这里拿到访问路径后(例如http://xxxx/xxx/xxx.live.flv?token=xxxx其中?后面就是拿到的参数)的参数 // err_msg返回 空字符串表示鉴权成功 否则鉴权失败提示 //String param = ZLM_API.mk_media_info_get_params(url_info); ZLM_API.mk_auth_invoker_do(invoker, ""); }; //推流回调 可控制鉴权、录制、转协议控制等 mkEvents.on_mk_media_publish = (url_info, invoker, sender) -> { //这里拿到访问路径后(例如rtmp://xxxx/xxx/xxx?token=xxxx其中?后面就是拿到的参数)的参数 // err_msg返回 空字符串表示鉴权成功 否则鉴权失败提示 //String param = ZLM_API.mk_media_info_get_params(url_info); ZLM_API.mk_publish_auth_invoker_do(invoker, "", 0, 0); }; //添加全局回调 ZLM_API.mk_events_listen(mkEvents); //Pointer iniPointer = ZLM_API.mk_ini_dump_string(mkIni); //初始化zmk服务器 ZLM_API.mk_env_init1(1, 1, 1, null, 0, 0, null, 0, null, null); //创建http服务器 0:失败,非0:端口号 short http_server_port = ZLM_API.mk_http_server_start((short) 7788, 0); //创建rtsp服务器 0:失败,非0:端口号 short rtsp_server_port = ZLM_API.mk_rtsp_server_start((short) 554, 0); //创建rtmp服务器 0:失败,非0:端口号 short rtmp_server_port = ZLM_API.mk_rtmp_server_start((short) 1935, 0); /*****************************下面为推流及播放********************************/ // 推流:利用obs、ffmpeg 进行推流 RTMP推流:rtmp://127.0.0.1:rtmp_port/流APP/流名称 RTSP推流:rtsp://127.0.0.1:rtsp_port/流APP/流名称 // 下面是各协议拉流播放的访问格式 // FLV拉流:http://127.0.0.1:http_port/流APP/流名称.live.flv // WS-FLV拉流:ws://127.0.0.1:http_port/流APP/流名称.live.flv // HLS拉流:http://127.0.0.1:http_port/流APP/流名称/hls.m3u8 // RTMP拉流:rtmp://127.0.0.1:rtmp_port/流APP/流名称 // RTSP拉流:rtsp://127.0.0.1:rtsp_port/流APP/流名称 /*****************************下面为流代理演示********************************/ //创建拉流代理
package com.aizuda.test; /** * 测试程序 展示了服务器配置 系统配置 流媒体服务启动 回调监听 拉流代理 * * @author lidaofu * @since 2023/11/23 **/ public class Test { //动态链接库放在/resource/win32-x86-64&/resource/linux-x86-64下JNA会自动查找目录 //public static ZLMApi ZLM_API = Native.load("mk_api", ZLMApi.class); //Windows环境测试 public static ZLMApi ZLM_API = Native.load("D:\\ZLMediaKit\\source\\release\\windows\\Debug\\mk_api.dll", ZLMApi.class); //Linux环境测试 //public static ZLMApi ZLM_API = Native.load("/opt/media/libmk_api.so", ZLMApi.class); public static void main(String[] args) throws InterruptedException { //初始化环境配置 MK_INI mkIni = ZLM_API.mk_ini_default(); //配置参数 全部配置参数及说明见(resources/conf.ini) 打开自动关流 对应conf.ini中配置[protocol] auto_close ZLM_API.mk_ini_set_option_int(mkIni, "protocol.auto_close", 1); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_fmp4", 0); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_hls", 0); ZLM_API.mk_ini_set_option_int(mkIni, "protocol.enable_ts", 0); //全局回调 全部回调见MK_EVENTS内所有的回调属性,有些需要去实现,不然流无法播放或者无法推流 MK_EVENTS mkEvents = new MK_EVENTS(); //流状态改变回调 mkEvents.on_mk_media_changed = (regist, sender) -> { System.out.println("这里是流改变回调通知:" + regist); }; //无人观看回调 mkEvents.on_mk_media_no_reader = sender -> { System.out.println("这里是无人观看回调通知"); ZLM_API.mk_media_source_close(sender, 1); }; //播放回调可做播放鉴权 mkEvents.on_mk_media_play = (url_info, invoker, sender) -> { //这里拿到访问路径后(例如http://xxxx/xxx/xxx.live.flv?token=xxxx其中?后面就是拿到的参数)的参数 // err_msg返回 空字符串表示鉴权成功 否则鉴权失败提示 //String param = ZLM_API.mk_media_info_get_params(url_info); ZLM_API.mk_auth_invoker_do(invoker, ""); }; //推流回调 可控制鉴权、录制、转协议控制等 mkEvents.on_mk_media_publish = (url_info, invoker, sender) -> { //这里拿到访问路径后(例如rtmp://xxxx/xxx/xxx?token=xxxx其中?后面就是拿到的参数)的参数 // err_msg返回 空字符串表示鉴权成功 否则鉴权失败提示 //String param = ZLM_API.mk_media_info_get_params(url_info); ZLM_API.mk_publish_auth_invoker_do(invoker, "", 0, 0); }; //添加全局回调 ZLM_API.mk_events_listen(mkEvents); //Pointer iniPointer = ZLM_API.mk_ini_dump_string(mkIni); //初始化zmk服务器 ZLM_API.mk_env_init1(1, 1, 1, null, 0, 0, null, 0, null, null); //创建http服务器 0:失败,非0:端口号 short http_server_port = ZLM_API.mk_http_server_start((short) 7788, 0); //创建rtsp服务器 0:失败,非0:端口号 short rtsp_server_port = ZLM_API.mk_rtsp_server_start((short) 554, 0); //创建rtmp服务器 0:失败,非0:端口号 short rtmp_server_port = ZLM_API.mk_rtmp_server_start((short) 1935, 0); /*****************************下面为推流及播放********************************/ // 推流:利用obs、ffmpeg 进行推流 RTMP推流:rtmp://127.0.0.1:rtmp_port/流APP/流名称 RTSP推流:rtsp://127.0.0.1:rtsp_port/流APP/流名称 // 下面是各协议拉流播放的访问格式 // FLV拉流:http://127.0.0.1:http_port/流APP/流名称.live.flv // WS-FLV拉流:ws://127.0.0.1:http_port/流APP/流名称.live.flv // HLS拉流:http://127.0.0.1:http_port/流APP/流名称/hls.m3u8 // RTMP拉流:rtmp://127.0.0.1:rtmp_port/流APP/流名称 // RTSP拉流:rtsp://127.0.0.1:rtsp_port/流APP/流名称 /*****************************下面为流代理演示********************************/ //创建拉流代理
MK_PROXY_PLAYER mk_proxy = ZLM_API.mk_proxy_player_create("__defaultVhost__", "live", "test", 0, 0);
4
2023-11-23 11:05:10+00:00
24k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/gdxparticleeditor/widgets/poptables/PopExport.java
[ { "identifier": "FileDialogs", "path": "core/src/main/java/com/ray3k/gdxparticleeditor/FileDialogs.java", "snippet": "public class FileDialogs {\n public static Array<FileHandle> openMultipleDialog(String title, String defaultPath, String[] filterPatterns, String filterDescription) {\n //fix f...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.scenes.scene2d.Event; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle; import com.badlogic.gdx.utils.Align; import com.ray3k.gdxparticleeditor.FileDialogs; import com.ray3k.gdxparticleeditor.Settings; import com.ray3k.gdxparticleeditor.runnables.ExportRunnable; import com.ray3k.gdxparticleeditor.widgets.LeadingTruncateLabel; import com.ray3k.gdxparticleeditor.widgets.styles.Styles; import com.ray3k.stripe.PopTable; import static com.ray3k.gdxparticleeditor.Core.*; import static com.ray3k.gdxparticleeditor.Listeners.*; import static com.ray3k.gdxparticleeditor.Settings.*;
20,141
package com.ray3k.gdxparticleeditor.widgets.poptables; /** * PopTable used to export a particle effect. This enables the user to save a copy of the file without affecting the * save location of the original particle effect. An option to include the images bypasses the option in the settings. */ public class PopExport extends PopTable { private final InputProcessor previousInputProcessor; private CheckBox exportImagesCheckBox; private FileHandle fileHandle; private TextButton exportTextButton; public PopExport() { super(skin.get(WindowStyle.class)); setHideOnUnfocus(true); key(Keys.ESCAPE, this::hide); key(Keys.ENTER, this::save); key(Keys.NUMPAD_ENTER, this::save); previousInputProcessor = Gdx.input.getInputProcessor(); Gdx.input.setInputProcessor(foregroundStage); addListener(new TableShowHideListener() { @Override public void tableShown(Event event) { hideAllTooltips(); } @Override public void tableHidden(Event event) { if (Gdx.input.getInputProcessor() == foregroundStage) Gdx.input.setInputProcessor(previousInputProcessor); } }); populate(); } private void populate() { clearChildren(); pad(20); defaults().space(10); var label = new Label("Export", skin, "bold"); add(label); row(); label = new Label("Save a copy to the selected path.", skin); add(label); row(); defaults().left(); var table = new Table(); add(table); table.defaults().space(5); label = new Label("Save Path:", skin); table.add(label); fileHandle = Gdx.files.absolute(getDefaultExportPath()); var disabled = fileHandle.isDirectory() || !fileHandle.parent().exists(); var leadingTruncateLabel = new LeadingTruncateLabel(disabled ? "" : fileHandle.path(), skin, "textfield"); leadingTruncateLabel.setEllipsis("..."); table.add(leadingTruncateLabel).width(250); addHandListenerIgnoreDisabled(leadingTruncateLabel); if (!disabled) addTooltip(leadingTruncateLabel, fileHandle.path(), Align.top, Align.top, Styles.tooltipBottomArrowStyle, true); onClick(leadingTruncateLabel, () -> { var useFileExtension = preferences.getBoolean(NAME_PRESUME_FILE_EXTENSION, DEFAULT_PRESUME_FILE_EXTENSION); var filterPatterns = useFileExtension ? new String[] {"p"} : null; var f = FileDialogs.saveDialog("Export File...", fileHandle.isDirectory() ? fileHandle.path() : fileHandle.parent().path(), defaultFileName, filterPatterns, "Particle Files (*.p)"); if (f != null) { fileHandle = f; setDefaultExportPath(fileHandle); leadingTruncateLabel.setText(fileHandle.path()); exportTextButton.setDisabled(false); } }); row(); exportImagesCheckBox = new CheckBox("Export images", skin); exportImagesCheckBox.setChecked(preferences.getBoolean(Settings.NAME_EXPORT_IMAGES)); add(exportImagesCheckBox); addHandListener(exportImagesCheckBox); defaults().center(); row(); table = new Table(); table.defaults().uniformX().fillX().space(10); add(table); exportTextButton = new TextButton("Export", skin, "highlighted"); exportTextButton.setDisabled(disabled); table.add(exportTextButton); addHandListener(exportTextButton); onChange(exportTextButton, this::save); var textButton = new TextButton("Cancel", skin); table.add(textButton); addHandListener(textButton); onChange(textButton, this::hide); } private void save() { if (fileHandle == null) return; hide();
package com.ray3k.gdxparticleeditor.widgets.poptables; /** * PopTable used to export a particle effect. This enables the user to save a copy of the file without affecting the * save location of the original particle effect. An option to include the images bypasses the option in the settings. */ public class PopExport extends PopTable { private final InputProcessor previousInputProcessor; private CheckBox exportImagesCheckBox; private FileHandle fileHandle; private TextButton exportTextButton; public PopExport() { super(skin.get(WindowStyle.class)); setHideOnUnfocus(true); key(Keys.ESCAPE, this::hide); key(Keys.ENTER, this::save); key(Keys.NUMPAD_ENTER, this::save); previousInputProcessor = Gdx.input.getInputProcessor(); Gdx.input.setInputProcessor(foregroundStage); addListener(new TableShowHideListener() { @Override public void tableShown(Event event) { hideAllTooltips(); } @Override public void tableHidden(Event event) { if (Gdx.input.getInputProcessor() == foregroundStage) Gdx.input.setInputProcessor(previousInputProcessor); } }); populate(); } private void populate() { clearChildren(); pad(20); defaults().space(10); var label = new Label("Export", skin, "bold"); add(label); row(); label = new Label("Save a copy to the selected path.", skin); add(label); row(); defaults().left(); var table = new Table(); add(table); table.defaults().space(5); label = new Label("Save Path:", skin); table.add(label); fileHandle = Gdx.files.absolute(getDefaultExportPath()); var disabled = fileHandle.isDirectory() || !fileHandle.parent().exists(); var leadingTruncateLabel = new LeadingTruncateLabel(disabled ? "" : fileHandle.path(), skin, "textfield"); leadingTruncateLabel.setEllipsis("..."); table.add(leadingTruncateLabel).width(250); addHandListenerIgnoreDisabled(leadingTruncateLabel); if (!disabled) addTooltip(leadingTruncateLabel, fileHandle.path(), Align.top, Align.top, Styles.tooltipBottomArrowStyle, true); onClick(leadingTruncateLabel, () -> { var useFileExtension = preferences.getBoolean(NAME_PRESUME_FILE_EXTENSION, DEFAULT_PRESUME_FILE_EXTENSION); var filterPatterns = useFileExtension ? new String[] {"p"} : null; var f = FileDialogs.saveDialog("Export File...", fileHandle.isDirectory() ? fileHandle.path() : fileHandle.parent().path(), defaultFileName, filterPatterns, "Particle Files (*.p)"); if (f != null) { fileHandle = f; setDefaultExportPath(fileHandle); leadingTruncateLabel.setText(fileHandle.path()); exportTextButton.setDisabled(false); } }); row(); exportImagesCheckBox = new CheckBox("Export images", skin); exportImagesCheckBox.setChecked(preferences.getBoolean(Settings.NAME_EXPORT_IMAGES)); add(exportImagesCheckBox); addHandListener(exportImagesCheckBox); defaults().center(); row(); table = new Table(); table.defaults().uniformX().fillX().space(10); add(table); exportTextButton = new TextButton("Export", skin, "highlighted"); exportTextButton.setDisabled(disabled); table.add(exportTextButton); addHandListener(exportTextButton); onChange(exportTextButton, this::save); var textButton = new TextButton("Cancel", skin); table.add(textButton); addHandListener(textButton); onChange(textButton, this::hide); } private void save() { if (fileHandle == null) return; hide();
var exportRunnable = new ExportRunnable();
2
2023-11-24 15:58:20+00:00
24k
siam1026/siam-server
siam-system/system-provider/src/main/java/com/siam/system/modular/package_goods/service_impl/internal/PointsMallGoodsSpecificationServiceImpl.java
[ { "identifier": "PointsMallGoodsSpecification", "path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_goods/entity/internal/PointsMallGoodsSpecification.java", "snippet": "@Data\n@TableName(\"tb_points_mall_goods_specification\")\n@ApiModel(value = \"商品规格表\")\npublic class Points...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.system.modular.package_goods.entity.internal.PointsMallGoodsSpecification; import com.siam.system.modular.package_goods.entity.internal.PointsMallGoodsSpecificationOption; import com.siam.system.modular.package_goods.mapper.internal.PointsMallGoodsSpecificationMapper; import com.siam.system.modular.package_goods.mapper.internal.PointsMallGoodsSpecificationOptionMapper; import com.siam.system.modular.package_goods.model.dto.internal.PointsMallGoodsSpecificationDto; import com.siam.system.modular.package_goods.model.dto.internal.PointsMallGoodsSpecificationOptionDto; import com.siam.system.modular.package_goods.model.example.internal.PointsMallGoodsSpecificationExample; import com.siam.system.modular.package_goods.service.internal.PointsMallGoodsSpecificationService; import com.siam.system.modular.package_goods.mapper.internal.PointsMallGoodsSpecificationMapper; import com.siam.system.modular.package_goods.mapper.internal.PointsMallGoodsSpecificationOptionMapper; import com.siam.system.modular.package_goods.service.internal.PointsMallGoodsSpecificationService; import com.siam.package_common.exception.StoneCustomerException; import com.siam.system.modular.package_goods.model.dto.internal.PointsMallGoodsSpecificationDto; import com.siam.system.modular.package_goods.model.dto.internal.PointsMallGoodsSpecificationOptionDto; import com.siam.system.modular.package_goods.entity.internal.PointsMallGoodsSpecification; import com.siam.system.modular.package_goods.entity.internal.PointsMallGoodsSpecificationOption; import com.siam.system.modular.package_goods.model.example.internal.PointsMallGoodsSpecificationExample; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map;
19,147
package com.siam.system.modular.package_goods.service_impl.internal; @Service public class PointsMallGoodsSpecificationServiceImpl implements PointsMallGoodsSpecificationService { @Autowired private PointsMallGoodsSpecificationMapper goodsSpecificationMapper; @Autowired private PointsMallGoodsSpecificationOptionMapper goodsSpecificationOptionMapper; public int countByExample(PointsMallGoodsSpecificationExample example){ return goodsSpecificationMapper.countByExample(example); } public void deleteByPrimaryKey(Integer id){ goodsSpecificationMapper.deleteByPrimaryKey(id); } public void insertSelective(PointsMallGoodsSpecification record){ goodsSpecificationMapper.insertSelective(record); } public List<PointsMallGoodsSpecification> selectByExample(PointsMallGoodsSpecificationExample example){ return goodsSpecificationMapper.selectByExample(example); } public PointsMallGoodsSpecification selectByPrimaryKey(Integer id){ return goodsSpecificationMapper.selectByPrimaryKey(id); } public void updateByExampleSelective(PointsMallGoodsSpecification record, PointsMallGoodsSpecificationExample example){ goodsSpecificationMapper.updateByExampleSelective(record, example); } public void updateByPrimaryKeySelective(PointsMallGoodsSpecification record){ goodsSpecificationMapper.updateByPrimaryKeySelective(record); } public Page<PointsMallGoodsSpecification> getListByPage(int pageNo, int pageSize, PointsMallGoodsSpecification goodsSpecification) { Page<PointsMallGoodsSpecification> page = goodsSpecificationMapper.getListByPage(new Page(pageNo, pageSize), goodsSpecification); return page; } @Override public Page<Map<String, Object>> getListByPageJoinPointsMallGoods(int pageNo, int pageSize, PointsMallGoodsSpecificationDto goodsSpecificationDto) { Page<Map<String, Object>> page = goodsSpecificationMapper.getListByPageJoinPointsMallGoods(goodsSpecificationDto); return page; } @Override public int selectMaxSortNumberByPointsMallGoodsId(Integer goodsId) { return goodsSpecificationMapper.selectMaxSortNumberByPointsMallGoodsId(goodsId); } @Override public PointsMallGoodsSpecification selectByPointsMallGoodsIdAndName(Integer goodsId, String name) { return goodsSpecificationMapper.selectByPointsMallGoodsIdAndName(goodsId, name); } @Override public void insertPublicGoodsSpecification(int goodsId) { //如果商品已经有规格,则不能生成,避免重复插入 PointsMallGoodsSpecificationExample goodsSpecificationExample = new PointsMallGoodsSpecificationExample(); goodsSpecificationExample.createCriteria().andPointsMallGoodsIdEqualTo(goodsId); int result = goodsSpecificationMapper.countByExample(goodsSpecificationExample); if(result > 0){ throw new StoneCustomerException("商品已存在其他规格,生成失败"); } //获取商品公共规格,插入数据
package com.siam.system.modular.package_goods.service_impl.internal; @Service public class PointsMallGoodsSpecificationServiceImpl implements PointsMallGoodsSpecificationService { @Autowired private PointsMallGoodsSpecificationMapper goodsSpecificationMapper; @Autowired private PointsMallGoodsSpecificationOptionMapper goodsSpecificationOptionMapper; public int countByExample(PointsMallGoodsSpecificationExample example){ return goodsSpecificationMapper.countByExample(example); } public void deleteByPrimaryKey(Integer id){ goodsSpecificationMapper.deleteByPrimaryKey(id); } public void insertSelective(PointsMallGoodsSpecification record){ goodsSpecificationMapper.insertSelective(record); } public List<PointsMallGoodsSpecification> selectByExample(PointsMallGoodsSpecificationExample example){ return goodsSpecificationMapper.selectByExample(example); } public PointsMallGoodsSpecification selectByPrimaryKey(Integer id){ return goodsSpecificationMapper.selectByPrimaryKey(id); } public void updateByExampleSelective(PointsMallGoodsSpecification record, PointsMallGoodsSpecificationExample example){ goodsSpecificationMapper.updateByExampleSelective(record, example); } public void updateByPrimaryKeySelective(PointsMallGoodsSpecification record){ goodsSpecificationMapper.updateByPrimaryKeySelective(record); } public Page<PointsMallGoodsSpecification> getListByPage(int pageNo, int pageSize, PointsMallGoodsSpecification goodsSpecification) { Page<PointsMallGoodsSpecification> page = goodsSpecificationMapper.getListByPage(new Page(pageNo, pageSize), goodsSpecification); return page; } @Override public Page<Map<String, Object>> getListByPageJoinPointsMallGoods(int pageNo, int pageSize, PointsMallGoodsSpecificationDto goodsSpecificationDto) { Page<Map<String, Object>> page = goodsSpecificationMapper.getListByPageJoinPointsMallGoods(goodsSpecificationDto); return page; } @Override public int selectMaxSortNumberByPointsMallGoodsId(Integer goodsId) { return goodsSpecificationMapper.selectMaxSortNumberByPointsMallGoodsId(goodsId); } @Override public PointsMallGoodsSpecification selectByPointsMallGoodsIdAndName(Integer goodsId, String name) { return goodsSpecificationMapper.selectByPointsMallGoodsIdAndName(goodsId, name); } @Override public void insertPublicGoodsSpecification(int goodsId) { //如果商品已经有规格,则不能生成,避免重复插入 PointsMallGoodsSpecificationExample goodsSpecificationExample = new PointsMallGoodsSpecificationExample(); goodsSpecificationExample.createCriteria().andPointsMallGoodsIdEqualTo(goodsId); int result = goodsSpecificationMapper.countByExample(goodsSpecificationExample); if(result > 0){ throw new StoneCustomerException("商品已存在其他规格,生成失败"); } //获取商品公共规格,插入数据
List<PointsMallGoodsSpecificationOptionDto> list = this.getPublicPointsMallGoodsSpecification();
13
2023-11-26 12:41:06+00:00
24k
3dcitydb/citydb-tool
citydb-io-citygml/src/main/java/org/citydb/io/citygml/adapter/generics/DoubleAttributeAdapter.java
[ { "identifier": "AbstractGenericAttributeAdapter", "path": "citydb-io-citygml/src/main/java/org/citydb/io/citygml/adapter/core/AbstractGenericAttributeAdapter.java", "snippet": "public abstract class AbstractGenericAttributeAdapter<T extends AbstractGenericAttribute<?>> implements ModelBuilder<T, Attrib...
import org.citygml4j.core.model.generics.DoubleAttribute; import org.citydb.io.citygml.adapter.core.AbstractGenericAttributeAdapter; import org.citydb.io.citygml.annotation.DatabaseType; import org.citydb.io.citygml.builder.ModelBuildException; import org.citydb.io.citygml.reader.ModelBuilderHelper; import org.citydb.io.citygml.serializer.ModelSerializeException; import org.citydb.io.citygml.writer.ModelSerializerHelper; import org.citydb.model.common.Namespaces; import org.citydb.model.property.Attribute; import org.citydb.model.property.DataType;
15,042
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.io.citygml.adapter.generics; @DatabaseType(name = "DoubleAttribute", namespace = Namespaces.GENERICS) public class DoubleAttributeAdapter extends AbstractGenericAttributeAdapter<DoubleAttribute> { @Override public void build(DoubleAttribute source, Attribute target, ModelBuilderHelper helper) throws ModelBuildException { target.setDoubleValue(source.getValue())
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.io.citygml.adapter.generics; @DatabaseType(name = "DoubleAttribute", namespace = Namespaces.GENERICS) public class DoubleAttributeAdapter extends AbstractGenericAttributeAdapter<DoubleAttribute> { @Override public void build(DoubleAttribute source, Attribute target, ModelBuilderHelper helper) throws ModelBuildException { target.setDoubleValue(source.getValue())
.setDataType(DataType.DOUBLE);
7
2023-11-19 12:29:54+00:00
24k
magmamaintained/Magma-1.12.2
src/main/java/org/bukkit/inventory/meta/EnchantmentStorageMeta.java
[ { "identifier": "Material", "path": "src/main/java/org/bukkit/Material.java", "snippet": "public enum Material {\n AIR(0, 0),\n STONE(1),\n GRASS(2),\n DIRT(3),\n COBBLESTONE(4),\n WOOD(5, Wood.class),\n SAPLING(6, Sapling.class),\n BEDROCK(7),\n WATER(8, MaterialData.class),\...
import java.util.Map; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment;
16,051
package org.bukkit.inventory.meta; /** * EnchantmentMeta is specific to items that can <i>store</i> enchantments, as * opposed to being enchanted. {@link Material#ENCHANTED_BOOK} is an example * of an item with enchantment storage. */ public interface EnchantmentStorageMeta extends ItemMeta { /** * Checks for the existence of any stored enchantments. * * @return true if an enchantment exists on this meta */ boolean hasStoredEnchants(); /** * Checks for storage of the specified enchantment. * * @param ench enchantment to check * @return true if this enchantment is stored in this meta */
package org.bukkit.inventory.meta; /** * EnchantmentMeta is specific to items that can <i>store</i> enchantments, as * opposed to being enchanted. {@link Material#ENCHANTED_BOOK} is an example * of an item with enchantment storage. */ public interface EnchantmentStorageMeta extends ItemMeta { /** * Checks for the existence of any stored enchantments. * * @return true if an enchantment exists on this meta */ boolean hasStoredEnchants(); /** * Checks for storage of the specified enchantment. * * @param ench enchantment to check * @return true if this enchantment is stored in this meta */
boolean hasStoredEnchant(Enchantment ench);
1
2023-11-22 11:25:51+00:00
24k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/loaders/recipe/chains/TungstenChain.java
[ { "identifier": "EPRecipeMaps", "path": "src/main/java/cn/gtcommunity/epimorphism/api/recipe/EPRecipeMaps.java", "snippet": "@ZenClass(\"mods.epimorphism.recipe.RecipeMaps\")\n@ZenRegister\npublic class EPRecipeMaps {\n\n // Singleblock Machine Recipemap\n @ZenProperty\n public static final Re...
import cn.gtcommunity.epimorphism.api.recipe.EPRecipeMaps; import gregtech.api.recipes.GTRecipeHandler; import gregtech.api.unification.OreDictUnifier; import static cn.gtcommunity.epimorphism.api.unification.EPMaterials.*; import static gregtech.api.GTValues.*; import static gregtech.api.recipes.RecipeMaps.*; import static gregtech.api.unification.material.Materials.*; import static gregtech.api.unification.ore.OrePrefix.*;
15,608
package cn.gtcommunity.epimorphism.loaders.recipe.chains; public class TungstenChain { public static void init() { // Delete original recipes GTRecipeHandler.removeRecipesByInputs(ELECTROLYZER_RECIPES, OreDictUnifier.get(dust, TungsticAcid, 7)); // Tungstic Acid -> Tungsten Trioxide + Water
package cn.gtcommunity.epimorphism.loaders.recipe.chains; public class TungstenChain { public static void init() { // Delete original recipes GTRecipeHandler.removeRecipesByInputs(ELECTROLYZER_RECIPES, OreDictUnifier.get(dust, TungsticAcid, 7)); // Tungstic Acid -> Tungsten Trioxide + Water
EPRecipeMaps.DRYER_RECIPES.recipeBuilder()
0
2023-11-26 01:56:35+00:00
24k
myzticbean/QSFindItemAddOn
src/main/java/io/myzticbean/finditemaddon/Handlers/GUIHandler/Menus/FoundShopsMenu.java
[ { "identifier": "ConfigProvider", "path": "src/main/java/io/myzticbean/finditemaddon/ConfigUtil/ConfigProvider.java", "snippet": "public class ConfigProvider {\n\n public final String PLUGIN_PREFIX = ColorTranslator.translateColorCodes(ConfigSetup.get().getString(\"plugin-prefix\"));\n public fina...
import io.myzticbean.finditemaddon.ConfigUtil.ConfigProvider; import io.myzticbean.finditemaddon.Dependencies.EssentialsXPlugin; import io.myzticbean.finditemaddon.Dependencies.PlayerWarpsPlugin; import io.myzticbean.finditemaddon.Dependencies.WGPlugin; import io.myzticbean.finditemaddon.FindItemAddOn; import io.myzticbean.finditemaddon.Handlers.GUIHandler.PaginatedMenu; import io.myzticbean.finditemaddon.Handlers.GUIHandler.PlayerMenuUtility; import io.myzticbean.finditemaddon.Models.FoundShopItemModel; import io.myzticbean.finditemaddon.Utils.Defaults.PlayerPerms; import io.myzticbean.finditemaddon.Utils.Defaults.ShopLorePlaceholders; import io.myzticbean.finditemaddon.Utils.JsonStorageUtils.ShopSearchActivityStorageUtil; import io.myzticbean.finditemaddon.Utils.LocationUtils; import io.myzticbean.finditemaddon.Utils.LoggerUtils; import io.myzticbean.finditemaddon.Utils.WarpUtils.EssentialWarpsUtil; import io.myzticbean.finditemaddon.Utils.WarpUtils.PlayerWarpsUtil; import io.myzticbean.finditemaddon.Utils.WarpUtils.WGRegionUtils; import io.papermc.lib.PaperLib; import me.kodysimpson.simpapi.colors.ColorTranslator; import org.apache.commons.lang3.StringUtils; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects;
15,677
package io.myzticbean.finditemaddon.Handlers.GUIHandler.Menus; /** * Handler class for FoundShops GUI * @author ronsane */ public class FoundShopsMenu extends PaginatedMenu { private final String NO_WARP_NEAR_SHOP_ERROR_MSG = "No Warp near this shop"; private final String NO_WG_REGION_NEAR_SHOP_ERROR_MSG = "No WG Region near this shop"; public FoundShopsMenu(PlayerMenuUtility playerMenuUtility, List<FoundShopItemModel> searchResult) { super(playerMenuUtility, searchResult); } @Override public String getMenuName() { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_GUI_TITLE)) { return ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().SHOP_SEARCH_GUI_TITLE); } else { return ColorTranslator.translateColorCodes("&l» &rShops"); } } @Override public int getSlots() { return 54; } @Override public void handleMenu(InventoryClickEvent event) { if(event.getSlot() == 45) { handleMenuClickForNavToPrevPage(event); } else if(event.getSlot() == 53) { handleMenuClickForNavToNextPage(event); } // Issue #31: Removing condition 'event.getCurrentItem().getType().equals(Material.BARRIER)' else if(event.getSlot() == 49) { event.getWhoClicked().closeInventory(); } else if(event.getCurrentItem().getType().equals(Material.AIR)) { // do nothing LoggerUtils.logDebugInfo(event.getWhoClicked().getName() + " just clicked on AIR!"); } else { Player player = (Player) event.getWhoClicked(); ItemStack item = event.getCurrentItem(); ItemMeta meta = item.getItemMeta(); NamespacedKey key = new NamespacedKey(FindItemAddOn.getInstance(), "locationData"); if(!meta.getPersistentDataContainer().isEmpty() && meta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { String locData = meta.getPersistentDataContainer().get(key, PersistentDataType.STRING); List<String> locDataList = Arrays.asList(locData.split("\\s*,\\s*")); if(FindItemAddOn.getConfigProvider().TP_PLAYER_DIRECTLY_TO_SHOP) { if(playerMenuUtility.getOwner().hasPermission(PlayerPerms.FINDITEM_SHOPTP.value())) { World world = Bukkit.getWorld(locDataList.get(0)); int locX = Integer.parseInt(locDataList.get(1)), locY = Integer.parseInt(locDataList.get(2)), locZ = Integer.parseInt(locDataList.get(3)); Location shopLocation = new Location(world, locX, locY, locZ);
package io.myzticbean.finditemaddon.Handlers.GUIHandler.Menus; /** * Handler class for FoundShops GUI * @author ronsane */ public class FoundShopsMenu extends PaginatedMenu { private final String NO_WARP_NEAR_SHOP_ERROR_MSG = "No Warp near this shop"; private final String NO_WG_REGION_NEAR_SHOP_ERROR_MSG = "No WG Region near this shop"; public FoundShopsMenu(PlayerMenuUtility playerMenuUtility, List<FoundShopItemModel> searchResult) { super(playerMenuUtility, searchResult); } @Override public String getMenuName() { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_GUI_TITLE)) { return ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().SHOP_SEARCH_GUI_TITLE); } else { return ColorTranslator.translateColorCodes("&l» &rShops"); } } @Override public int getSlots() { return 54; } @Override public void handleMenu(InventoryClickEvent event) { if(event.getSlot() == 45) { handleMenuClickForNavToPrevPage(event); } else if(event.getSlot() == 53) { handleMenuClickForNavToNextPage(event); } // Issue #31: Removing condition 'event.getCurrentItem().getType().equals(Material.BARRIER)' else if(event.getSlot() == 49) { event.getWhoClicked().closeInventory(); } else if(event.getCurrentItem().getType().equals(Material.AIR)) { // do nothing LoggerUtils.logDebugInfo(event.getWhoClicked().getName() + " just clicked on AIR!"); } else { Player player = (Player) event.getWhoClicked(); ItemStack item = event.getCurrentItem(); ItemMeta meta = item.getItemMeta(); NamespacedKey key = new NamespacedKey(FindItemAddOn.getInstance(), "locationData"); if(!meta.getPersistentDataContainer().isEmpty() && meta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { String locData = meta.getPersistentDataContainer().get(key, PersistentDataType.STRING); List<String> locDataList = Arrays.asList(locData.split("\\s*,\\s*")); if(FindItemAddOn.getConfigProvider().TP_PLAYER_DIRECTLY_TO_SHOP) { if(playerMenuUtility.getOwner().hasPermission(PlayerPerms.FINDITEM_SHOPTP.value())) { World world = Bukkit.getWorld(locDataList.get(0)); int locX = Integer.parseInt(locDataList.get(1)), locY = Integer.parseInt(locDataList.get(2)), locZ = Integer.parseInt(locDataList.get(3)); Location shopLocation = new Location(world, locX, locY, locZ);
Location locToTeleport = LocationUtils.findSafeLocationAroundShop(shopLocation);
11
2023-11-22 11:36:01+00:00
24k
DIDA-lJ/qiyao-12306
services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/service/impl/TicketServiceImpl.java
[ { "identifier": "RefundTypeEnum", "path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/common/enums/RefundTypeEnum.java", "snippet": "@Getter\n@RequiredArgsConstructor\npublic enum RefundTypeEnum {\n\n /**\n * 部分退款\n */\n PARTIAL_REFUND(11, 0, \"PARTIAL...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson2.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.google.common.collect.Lists; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.opengoofy.index12306.biz.ticketservice.common.enums.RefundTypeEnum; import org.opengoofy.index12306.biz.ticketservice.common.enums.SourceEnum; import org.opengoofy.index12306.biz.ticketservice.common.enums.TicketChainMarkEnum; import org.opengoofy.index12306.biz.ticketservice.common.enums.TicketStatusEnum; import org.opengoofy.index12306.biz.ticketservice.common.enums.VehicleTypeEnum; import org.opengoofy.index12306.biz.ticketservice.dao.entity.StationDO; import org.opengoofy.index12306.biz.ticketservice.dao.entity.TicketDO; import org.opengoofy.index12306.biz.ticketservice.dao.entity.TrainDO; import org.opengoofy.index12306.biz.ticketservice.dao.entity.TrainStationPriceDO; import org.opengoofy.index12306.biz.ticketservice.dao.entity.TrainStationRelationDO; import org.opengoofy.index12306.biz.ticketservice.dao.mapper.StationMapper; import org.opengoofy.index12306.biz.ticketservice.dao.mapper.TicketMapper; import org.opengoofy.index12306.biz.ticketservice.dao.mapper.TrainMapper; import org.opengoofy.index12306.biz.ticketservice.dao.mapper.TrainStationPriceMapper; import org.opengoofy.index12306.biz.ticketservice.dao.mapper.TrainStationRelationMapper; import org.opengoofy.index12306.biz.ticketservice.dto.domain.PurchaseTicketPassengerDetailDTO; import org.opengoofy.index12306.biz.ticketservice.dto.domain.RouteDTO; import org.opengoofy.index12306.biz.ticketservice.dto.domain.SeatClassDTO; import org.opengoofy.index12306.biz.ticketservice.dto.domain.TicketListDTO; import org.opengoofy.index12306.biz.ticketservice.dto.req.CancelTicketOrderReqDTO; import org.opengoofy.index12306.biz.ticketservice.dto.req.PurchaseTicketReqDTO; import org.opengoofy.index12306.biz.ticketservice.dto.req.RefundTicketReqDTO; import org.opengoofy.index12306.biz.ticketservice.dto.req.TicketOrderItemQueryReqDTO; import org.opengoofy.index12306.biz.ticketservice.dto.req.TicketPageQueryReqDTO; import org.opengoofy.index12306.biz.ticketservice.dto.resp.RefundTicketRespDTO; import org.opengoofy.index12306.biz.ticketservice.dto.resp.TicketOrderDetailRespDTO; import org.opengoofy.index12306.biz.ticketservice.dto.resp.TicketPageQueryRespDTO; import org.opengoofy.index12306.biz.ticketservice.dto.resp.TicketPurchaseRespDTO; import org.opengoofy.index12306.biz.ticketservice.remote.PayRemoteService; import org.opengoofy.index12306.biz.ticketservice.remote.TicketOrderRemoteService; import org.opengoofy.index12306.biz.ticketservice.remote.dto.PayInfoRespDTO; import org.opengoofy.index12306.biz.ticketservice.remote.dto.RefundReqDTO; import org.opengoofy.index12306.biz.ticketservice.remote.dto.RefundRespDTO; import org.opengoofy.index12306.biz.ticketservice.remote.dto.TicketOrderCreateRemoteReqDTO; import org.opengoofy.index12306.biz.ticketservice.remote.dto.TicketOrderItemCreateRemoteReqDTO; import org.opengoofy.index12306.biz.ticketservice.remote.dto.TicketOrderPassengerDetailRespDTO; import org.opengoofy.index12306.biz.ticketservice.service.SeatService; import org.opengoofy.index12306.biz.ticketservice.service.TicketService; import org.opengoofy.index12306.biz.ticketservice.service.TrainStationService; import org.opengoofy.index12306.biz.ticketservice.service.cache.SeatMarginCacheLoader; import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.dto.TrainPurchaseTicketRespDTO; import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.select.TrainSeatTypeSelector; import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.tokenbucket.TicketAvailabilityTokenBucket; import org.opengoofy.index12306.biz.ticketservice.toolkit.DateUtil; import org.opengoofy.index12306.biz.ticketservice.toolkit.TimeStringComparator; import org.opengoofy.index12306.framework.starter.bases.ApplicationContextHolder; import org.opengoofy.index12306.framework.starter.cache.DistributedCache; import org.opengoofy.index12306.framework.starter.cache.toolkit.CacheUtil; import org.opengoofy.index12306.framework.starter.common.toolkit.BeanUtil; import org.opengoofy.index12306.framework.starter.convention.exception.ServiceException; import org.opengoofy.index12306.framework.starter.convention.result.Result; import org.opengoofy.index12306.framework.starter.designpattern.chain.AbstractChainContext; import org.opengoofy.index12306.frameworks.starter.user.core.UserContext; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import static org.opengoofy.index12306.biz.ticketservice.common.constant.Index12306Constant.ADVANCE_TICKET_DAY; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.LOCK_PURCHASE_TICKETS; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.LOCK_PURCHASE_TICKETS_V2; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.LOCK_REGION_TRAIN_STATION; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.LOCK_REGION_TRAIN_STATION_MAPPING; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.REGION_TRAIN_STATION; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.REGION_TRAIN_STATION_MAPPING; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.TRAIN_INFO; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.TRAIN_STATION_PRICE; import static org.opengoofy.index12306.biz.ticketservice.common.constant.RedisKeyConstant.TRAIN_STATION_REMAINING_TICKET; import static org.opengoofy.index12306.biz.ticketservice.toolkit.DateUtil.convertDateToLocalTime;
21,511
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengoofy.index12306.biz.ticketservice.service.impl; /** * 车票接口实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class TicketServiceImpl extends ServiceImpl<TicketMapper, TicketDO> implements TicketService, CommandLineRunner { private final TrainMapper trainMapper; private final TrainStationRelationMapper trainStationRelationMapper; private final TrainStationPriceMapper trainStationPriceMapper;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengoofy.index12306.biz.ticketservice.service.impl; /** * 车票接口实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class TicketServiceImpl extends ServiceImpl<TicketMapper, TicketDO> implements TicketService, CommandLineRunner { private final TrainMapper trainMapper; private final TrainStationRelationMapper trainStationRelationMapper; private final TrainStationPriceMapper trainStationPriceMapper;
private final DistributedCache distributedCache;
46
2023-11-23 07:59:11+00:00
24k
estkme-group/infineon-lpa-mirror
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 {
7
2023-11-22 07:46:30+00:00
24k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/certificate/acme/api/endpoints/challenge/ChallengeCallbackEndpoint.java
[ { "identifier": "Provisioner", "path": "src/main/java/de/morihofi/acmeserver/certificate/acme/api/Provisioner.java", "snippet": "public class Provisioner {\n\n\n /**\n * Get the ACME Server URL, reachable from other Hosts\n *\n * @return Full url (including HTTPS prefix) and port to this ...
import com.google.gson.Gson; import de.morihofi.acmeserver.certificate.acme.api.Provisioner; import de.morihofi.acmeserver.certificate.acme.api.abstractclass.AbstractAcmeEndpoint; import de.morihofi.acmeserver.certificate.acme.api.endpoints.challenge.objects.ACMEChallengeResponse; import de.morihofi.acmeserver.certificate.acme.challenges.DNSChallenge; import de.morihofi.acmeserver.certificate.acme.challenges.HTTPChallenge; import de.morihofi.acmeserver.certificate.objects.ACMERequestBody; import de.morihofi.acmeserver.database.Database; import de.morihofi.acmeserver.database.objects.ACMEIdentifier; import de.morihofi.acmeserver.exception.exceptions.ACMEConnectionErrorException; import de.morihofi.acmeserver.exception.exceptions.ACMEMalformedException; import de.morihofi.acmeserver.tools.crypto.Crypto; import de.morihofi.acmeserver.tools.dateAndTime.DateTools; import io.javalin.http.Context; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
14,697
package de.morihofi.acmeserver.certificate.acme.api.endpoints.challenge; /** * A handler endpoint for processing challenge callbacks. */ public class ChallengeCallbackEndpoint extends AbstractAcmeEndpoint { /** * Logger */ private final Logger log = LogManager.getLogger(getClass()); /** * Constructs a NewNonce handler with the specified ACME provisioner. * * @param provisioner The ACME provisioner to use for generating nonces. */ public ChallengeCallbackEndpoint(Provisioner provisioner) { super(provisioner); } @Override public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception { String challengeId = ctx.pathParam("challengeId"); String challengeType = ctx.pathParam("challengeType"); //dns-01 or http-01 ctx.header("Content-Type", "application/json"); ctx.header("Replay-Nonce", Crypto.createNonce()); // Check if challenge is valid ACMEIdentifier identifier = Database.getACMEIdentifierByChallengeId(challengeId); // Check signature and nonce performSignatureAndNonceCheck(ctx, identifier.getOrder().getAccount(), acmeRequestBody); boolean isWildcardDomain = false; String nonWildcardDomain = identifier.getDataValue(); if (nonWildcardDomain.startsWith("*.")) { nonWildcardDomain = nonWildcardDomain.substring(2); // Remove wildcard part for validation isWildcardDomain = true; } if (!"dns-01".equals(challengeType) && isWildcardDomain) { throw new ACMEMalformedException("DNS-01 method is only valid for non wildcard domains"); } boolean challengePassed; String possibleErrorReasonIfFailed; switch (challengeType) { case "http-01" -> { challengePassed = HTTPChallenge.check(identifier.getAuthorizationToken(), identifier.getDataValue(), identifier.getOrder().getAccount()); possibleErrorReasonIfFailed = "Unable to reach host \"" + identifier.getDataValue() + "\" or invalid token. Is the host reachable? Is the http server on port 80 running? If it is running, check your access logs"; } case "dns-01" -> { challengePassed = DNSChallenge.check(identifier.getAuthorizationToken(), nonWildcardDomain, identifier.getOrder().getAccount()); possibleErrorReasonIfFailed = "Unable to verify DNS TXT entry for host \"" + nonWildcardDomain + "\""; } default -> { log.error("Unsupported challenge type: " + challengeType);
package de.morihofi.acmeserver.certificate.acme.api.endpoints.challenge; /** * A handler endpoint for processing challenge callbacks. */ public class ChallengeCallbackEndpoint extends AbstractAcmeEndpoint { /** * Logger */ private final Logger log = LogManager.getLogger(getClass()); /** * Constructs a NewNonce handler with the specified ACME provisioner. * * @param provisioner The ACME provisioner to use for generating nonces. */ public ChallengeCallbackEndpoint(Provisioner provisioner) { super(provisioner); } @Override public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception { String challengeId = ctx.pathParam("challengeId"); String challengeType = ctx.pathParam("challengeType"); //dns-01 or http-01 ctx.header("Content-Type", "application/json"); ctx.header("Replay-Nonce", Crypto.createNonce()); // Check if challenge is valid ACMEIdentifier identifier = Database.getACMEIdentifierByChallengeId(challengeId); // Check signature and nonce performSignatureAndNonceCheck(ctx, identifier.getOrder().getAccount(), acmeRequestBody); boolean isWildcardDomain = false; String nonWildcardDomain = identifier.getDataValue(); if (nonWildcardDomain.startsWith("*.")) { nonWildcardDomain = nonWildcardDomain.substring(2); // Remove wildcard part for validation isWildcardDomain = true; } if (!"dns-01".equals(challengeType) && isWildcardDomain) { throw new ACMEMalformedException("DNS-01 method is only valid for non wildcard domains"); } boolean challengePassed; String possibleErrorReasonIfFailed; switch (challengeType) { case "http-01" -> { challengePassed = HTTPChallenge.check(identifier.getAuthorizationToken(), identifier.getDataValue(), identifier.getOrder().getAccount()); possibleErrorReasonIfFailed = "Unable to reach host \"" + identifier.getDataValue() + "\" or invalid token. Is the host reachable? Is the http server on port 80 running? If it is running, check your access logs"; } case "dns-01" -> { challengePassed = DNSChallenge.check(identifier.getAuthorizationToken(), nonWildcardDomain, identifier.getOrder().getAccount()); possibleErrorReasonIfFailed = "Unable to verify DNS TXT entry for host \"" + nonWildcardDomain + "\""; } default -> { log.error("Unsupported challenge type: " + challengeType);
throw new ACMEConnectionErrorException("Unsupported challenge type: " + challengeType);
8
2023-11-22 15:54:36+00:00
24k
NBHZW/hnustDatabaseCourseDesign
ruoyi-admin/src/main/java/com/ruoyi/web/controller/studentInformation/RewardCodeController.java
[ { "identifier": "BaseController", "path": "ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java", "snippet": "public class BaseController\r\n{\r\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\r\n\r\n /**\r\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型...
import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.studentInformation.domain.RewardCode; import com.ruoyi.studentInformation.service.IRewardCodeService; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.common.core.page.TableDataInfo;
16,961
package com.ruoyi.web.controller.studentInformation; /** * 奖励等级代码Controller * * @author ruoyi * @date 2023-11-08 */ @RestController @RequestMapping("/system/code")
package com.ruoyi.web.controller.studentInformation; /** * 奖励等级代码Controller * * @author ruoyi * @date 2023-11-08 */ @RestController @RequestMapping("/system/code")
public class RewardCodeController extends BaseController
0
2023-11-25 02:50:45+00:00
24k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/mods/JERIceAndFire.java
[ { "identifier": "JERRenderHippocampus", "path": "src/main/java/com/invadermonky/justenoughmagiculture/client/model/entity/mods/iceandfire/JERRenderHippocampus.java", "snippet": "public class JERRenderHippocampus extends RenderHippocampus {\n public JERRenderHippocampus(RenderManager renderManager) {\...
import com.github.alexthe666.iceandfire.entity.*; import com.github.alexthe666.iceandfire.enums.EnumTroll; import com.github.alexthe666.iceandfire.item.IafItemRegistry; import com.github.alexthe666.iceandfire.world.gen.*; import com.github.alexthe666.rats.server.entity.EntityPirat; import com.github.alexthe666.rats.server.entity.EntityRat; import com.google.common.collect.Sets; import com.invadermonky.justenoughmagiculture.client.model.entity.mods.iceandfire.JERRenderHippocampus; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.rats.JERRenderPirat; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.rats.JERRenderRat; import com.invadermonky.justenoughmagiculture.configs.JEMConfig; import com.invadermonky.justenoughmagiculture.configs.mods.JEMConfigIceAndFire; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.jer.villager.CustomVanillaVillagerEntry; import com.invadermonky.justenoughmagiculture.integrations.jer.IJERIntegration; import com.invadermonky.justenoughmagiculture.integrations.jer.JERBase; import com.invadermonky.justenoughmagiculture.registry.CustomVillagerRegistry; import com.invadermonky.justenoughmagiculture.util.BiomeHelper; import com.invadermonky.justenoughmagiculture.util.LogHelper; import com.invadermonky.justenoughmagiculture.util.ReflectionHelper; import com.invadermonky.justenoughmagiculture.util.StringHelper; import com.invadermonky.justenoughmagiculture.util.modhelpers.IaFLootHelper; import gnu.trove.map.hash.THashMap; import gnu.trove.set.hash.THashSet; import jeresources.api.conditionals.LightLevel; import jeresources.api.drop.LootDrop; import jeresources.entry.MobEntry; import jeresources.registry.MobRegistry; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityWitherSkeleton; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.world.biome.Biome; import net.minecraftforge.common.BiomeDictionary; import net.minecraftforge.common.BiomeDictionary.Type; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerCareer; import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession; import org.apache.commons.lang3.reflect.FieldUtils; import javax.annotation.Nonnull; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; import java.util.Set;
14,799
troll.setType(EnumTroll.FOREST); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.FOREST_LOOT); } if(jerConfig.JER_MOBS.enableTrollFrost) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.FROST); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.FROST_LOOT); } if(jerConfig.JER_MOBS.enableTrollMountain) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.MOUNTAIN); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.MOUNTAIN_LOOT); } //Generic Render Hooks registerRenderHook(EntityTroll.class, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.8,0); return renderInfo; })); } public void registerRenderOverrides() { if(JEMConfig.ICE_AND_FIRE.enableRenderFixes) { //Ice and Fire uses the depreciated method to register entity renders. RenderingRegistry.registerEntityRenderingHandler(EntityHippocampus.class, new JERRenderHippocampus(Minecraft.getMinecraft().getRenderManager())); } } private THashSet<Biome> getIaFLinkedBiomes(Type... types) { THashSet<Biome> biomes = new THashSet<>(); for(Type type : types) { if(biomes.isEmpty()) { biomes.addAll(BiomeDictionary.getBiomes(type)); } else { biomes.removeIf(biome -> (!BiomeDictionary.getBiomes(type).contains(biome))); } } return biomes; } private String[] getIaFSpawnBiomesFromTypes(THashSet<Type> validTypes, THashSet<Type> invalidTypes) { THashSet<Biome> validBiomes = new THashSet<>(); for(Type validType : validTypes) { validBiomes.addAll(BiomeDictionary.getBiomes(validType)); } for(Type invalidType : invalidTypes) { validBiomes.removeAll(BiomeDictionary.getBiomes(invalidType)); } return validBiomes.isEmpty() ? new String[] {"jer.any"} : BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])); } private String[] getIaFSpawnBiomes(THashSet<Biome> biomes, THashSet<Type> invalidTypes) { for(Type type : invalidTypes) { biomes.removeAll(BiomeDictionary.getBiomes(type)); } return biomes.isEmpty() ? new String[] {"jer.any"} : BiomeHelper.getBiomeNamesForBiomes(biomes.toArray(new Biome[0])); } private void adjustHumanoidRenderHook(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.4,0); return renderInfo; })); } @Override public void registerModVillagers() { CustomVillagerRegistry registry = CustomVillagerRegistry.getInstance(); THashMap<VillagerProfession,EntityMyrmexBase> desertMyrmexVillagers = new THashMap<>(5); THashMap<VillagerProfession,EntityMyrmexBase> jungleMyrmexVillagers = new THashMap<>(5); if(jerConfig.JER_VILLAGERS.enableMyrmexQueen) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexQueen, setMyrmexTexture(new EntityMyrmexQueen(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexQueen, setMyrmexTexture(new EntityMyrmexQueen(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexRoyal) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexRoyal, setMyrmexTexture(new EntityMyrmexRoyal(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexRoyal, setMyrmexTexture(new EntityMyrmexRoyal(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexSentinel) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexSentinel, setMyrmexTexture(new EntityMyrmexSentinel(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexSentinel, setMyrmexTexture(new EntityMyrmexSentinel(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexSoldier) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexSoldier, setMyrmexTexture(new EntityMyrmexSoldier(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexSoldier, setMyrmexTexture(new EntityMyrmexSoldier(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexWorker) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexWorker, setMyrmexTexture(new EntityMyrmexWorker(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexWorker, setMyrmexTexture(new EntityMyrmexWorker(world), true)); } registerMyrmexVillagers(registry, desertMyrmexVillagers); registerMyrmexVillagers(registry, jungleMyrmexVillagers); if(jerConfig.JER_VILLAGERS.enableSnowVillager) { registerSnowVillagers(registry); } } private EntityMyrmexBase setMyrmexTexture(EntityMyrmexBase entity, boolean isJungle) { entity.setJungleVariant(isJungle); return entity; } private void registerMyrmexVillagers(CustomVillagerRegistry registry, THashMap<VillagerProfession,EntityMyrmexBase> myrmexVillagers) { myrmexVillagers.forEach((profession, villager) -> { try { VillagerCareer career = profession.getCareer(0); List<List<EntityVillager.ITradeList>> trades = (List<List<EntityVillager.ITradeList>>) ReflectionHelper.getFieldObject(career, "trades");
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERIceAndFire extends JERBase implements IJERIntegration { private static JERIceAndFire instance; JEMConfigIceAndFire.JER jerConfig = JEMConfig.ICE_AND_FIRE.JUST_ENOUGH_RESOURCES; private JERIceAndFire() {} public JERIceAndFire(boolean enableJERDungeons, boolean enableJERMobs, boolean enableJERVillagers) { if(enableJERDungeons) registerModDungeons(); if(enableJERMobs) registerModEntities(); if(enableJERVillagers) registerModVillagers(); getInstance(); } public static JERIceAndFire getInstance() { return instance != null ? instance : (instance = new JERIceAndFire()); } /** * Ice and fire needs to register render overrides here because they don't work if registered normally. */ public void lateInit() { registerRenderOverrides(); injectLoot(); } @Override public void registerModDungeons() { registerIAFDungeon(WorldGenCyclopsCave.CYCLOPS_CHEST); registerIAFDungeon(WorldGenFireDragonCave.FIREDRAGON_CHEST); registerIAFDungeon(WorldGenFireDragonCave.FIREDRAGON_MALE_CHEST); registerIAFDungeon(WorldGenHydraCave.HYDRA_CHEST); registerIAFDungeon(WorldGenIceDragonCave.ICEDRAGON_CHEST); registerIAFDungeon(WorldGenIceDragonCave.ICEDRAGON_MALE_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.DESERT_MYRMEX_FOOD_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.JUNGLE_MYRMEX_FOOD_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.MYRMEX_GOLD_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.MYRMEX_TRASH_CHEST); } @Override public void registerModEntities() { registerDragons(); registerDeathworms(); registerDread(); registerMyrmex(); registerSeaSerpents(); registerMiscMobs(); } @Override @SuppressWarnings("unchecked") public void injectLoot() { if(JEMConfig.ICE_AND_FIRE.enableJERInjectedLoot) { for (MobEntry mobEntry : MobRegistry.getInstance().getMobs()) { if (mobEntry.getEntity() instanceof EntityWitherSkeleton) { try { Field entryField = MobRegistry.getInstance().getClass().getDeclaredField("registry"); entryField.setAccessible(true); Set<MobEntry> mobEntries = (Set<MobEntry>) entryField.get(MobRegistry.getInstance()); mobEntries.remove(mobEntry); Field dropsField = mobEntry.getClass().getDeclaredField("drops"); dropsField.setAccessible(true); mobEntry.addDrop(new LootDrop(IafItemRegistry.witherbone, 0, 1)); mobEntries.add(mobEntry); } catch(Exception ignored) {} } } } } private void registerDragons() { THashSet<Type> validFireTypes = new THashSet<>(Sets.newHashSet(Type.HILLS, Type.MOUNTAIN)); THashSet<Type> invalidForeTypes = new THashSet<>(Sets.newHashSet(Type.COLD, Type.SNOWY)); THashSet<Biome> validIceBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); THashSet<Type> invalidIceTypes = new THashSet<>(Sets.newHashSet(Type.BEACH)); if(jerConfig.JER_MOBS.enableFireDragonMale) { for (int i = 0; i < 3; i++) { EntityFireDragon fireDragon = new EntityFireDragon(world); fireDragon.setVariant(i); fireDragon.setCustomNameTag("entity.jem:iaf_fire_dragon_male.name"); List<LootDrop> drops = IaFLootHelper.toDrops(fireDragon, manager.getLootTableFromLocation(EntityFireDragon.MALE_LOOT)); if (jerConfig.JER_MOBS.enableFireDragonMale) { registerMob(fireDragon, LightLevel.any, getIaFSpawnBiomesFromTypes(validFireTypes, invalidForeTypes), drops); } } } if(jerConfig.JER_MOBS.enableIceDragonMale) { for (int i = 0; i < 3; i++) { EntityIceDragon iceDragon = new EntityIceDragon(world); iceDragon.setVariant(i); iceDragon.setCustomNameTag("entity.jem:iaf_ice_dragon_male.name"); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); List<LootDrop> drops = IaFLootHelper.toDrops(iceDragon, manager.getLootTableFromLocation(EntityIceDragon.MALE_LOOT)); if (jerConfig.JER_MOBS.enableFireDragonMale) { registerMob(iceDragon, LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), drops); } } } if(jerConfig.JER_MOBS.enableFireDragonFemale) { for (int i = 0; i < 3; i++) { EntityFireDragon fireDragon = new EntityFireDragon(world); fireDragon.setVariant(i); fireDragon.setCustomNameTag("entity.jem:iaf_fire_dragon_female.name"); List<LootDrop> femaleDrops = IaFLootHelper.toDrops(fireDragon, manager.getLootTableFromLocation(EntityFireDragon.FEMALE_LOOT)); registerMob(fireDragon, LightLevel.any, getIaFSpawnBiomesFromTypes(validFireTypes, invalidForeTypes), femaleDrops); } } if(jerConfig.JER_MOBS.enableIceDragonFemale) { for(int i = 0; i < 3; i++) { EntityIceDragon iceDragon = new EntityIceDragon(world); iceDragon.setVariant(i); iceDragon.setCustomNameTag("entity.jem:iaf_ice_dragon_female.name"); List<LootDrop> femaleDrops = IaFLootHelper.toDrops(iceDragon, manager.getLootTableFromLocation(EntityIceDragon.FEMALE_LOOT)); registerMob(iceDragon, LightLevel.any, getIaFSpawnBiomes(validIceBiomes, invalidIceTypes), femaleDrops); } } registerRenderHook(EntityDragonBase.class, ((renderInfo, e) -> { GlStateManager.scale(3.0,3.0,3.0); GlStateManager.translate(-0.005,-0.05,0); return renderInfo; })); } private void registerDeathworms() { if(jerConfig.JER_MOBS.enableDeathWormRed) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(2); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(5); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.RED_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormRedGiant) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(2); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(10); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.RED_GIANT_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormTan) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(0); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(5); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.TAN_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormTanGiant) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(0); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(10); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.TAN_GIANT_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormWhite) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(1); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(5); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.WHITE_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormWhiteGiant) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(1); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(10); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.WHITE_GIANT_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } } private void registerDread() { if(jerConfig.JER_MOBS.enableDreadBeast) { EntityDreadBeast dreadBeast = new EntityDreadBeast(world); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadBeast, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadBeast.LOOT); adjustHumanoidRenderHook(EntityDreadBeast.class); } if(jerConfig.JER_MOBS.enableDreadGhoul) { EntityDreadGhoul dreadGhoul = new EntityDreadGhoul(world); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadGhoul, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadGhoul.LOOT); adjustHumanoidRenderHook(EntityDreadGhoul.class); } if(jerConfig.JER_MOBS.enableDreadKnight) { EntityDreadKnight dreadKnight = new EntityDreadKnight(world); dreadKnight.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(IafItemRegistry.dread_knight_sword)); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadKnight, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadKnight.LOOT); registerRenderHook(EntityDreadKnight.class, ((renderInfo, e) -> { GlStateManager.translate(-0.05,0.2,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableDreadLich) { EntityDreadLich lich = new EntityDreadLich(world); lich.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(IafItemRegistry.lich_staff)); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(lich, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadLich.LOOT); adjustHumanoidRenderHook(EntityDreadLich.class); } if(jerConfig.JER_MOBS.enableDreadScuttler) { EntityDreadScuttler dreadScuttler = new EntityDreadScuttler(world); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadScuttler, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadScuttler.LOOT); registerRenderHook(EntityDreadScuttler.class, ((renderInfo, e) -> { GlStateManager.scale(0.9,0.9,0.9); GlStateManager.translate(0,-0.2,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableDreadThrall) { EntityDreadThrall dreadThrall = new EntityDreadThrall(world); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(IafItemRegistry.dread_sword)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.HEAD, new ItemStack(Items.CHAINMAIL_HELMET)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.CHEST, new ItemStack(Items.CHAINMAIL_CHESTPLATE)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.LEGS, new ItemStack(Items.CHAINMAIL_LEGGINGS)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.FEET, new ItemStack(Items.CHAINMAIL_BOOTS)); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadThrall, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadThrall.LOOT); adjustHumanoidRenderHook(dreadThrall.getClass()); } } private void registerMyrmex() { if(jerConfig.JER_MOBS.enableMyrmexDesertQueen) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexQueen(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexQueen.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertRoyal) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexRoyal(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexRoyal.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertSentinel) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexSentinel(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexSentinel.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertSoldier) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexSoldier(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexSoldier.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertWorker) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexWorker(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexWorker.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleQueen) { registerMob(setMyrmexTexture(new EntityMyrmexQueen(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexQueen.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleRoyal) { registerMob(setMyrmexTexture(new EntityMyrmexRoyal(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexRoyal.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleSentinel) { registerMob(setMyrmexTexture(new EntityMyrmexSentinel(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexSentinel.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleSoldier) { registerMob(setMyrmexTexture(new EntityMyrmexSoldier(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexSoldier.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleWorker) { registerMob(setMyrmexTexture(new EntityMyrmexWorker(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexWorker.JUNGLE_LOOT); } registerRenderHook(EntityMyrmexQueen.class, ((renderInfo, entityLivingBase) -> { GlStateManager.scale(1.7,1.7,1.7); return renderInfo; })); } private void registerSeaSerpents() { if(jerConfig.JER_MOBS.enableSeaSerpent) { for(int i = 0; i < 6; i++) { EntitySeaSerpent seaSerpent = new EntitySeaSerpent(world); NBTTagCompound tag = new NBTTagCompound(); tag.setFloat("Scale", 1f); seaSerpent.readEntityFromNBT(tag); seaSerpent.setVariant(i); List<LootDrop> drops = IaFLootHelper.toDrops(seaSerpent, manager.getLootTableFromLocation(EntitySeaSerpent.LOOT)); registerMob(seaSerpent, LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.OCEAN), drops); } } } private void registerMiscMobs() { if(jerConfig.JER_MOBS.enableAmphithere) { registerMob(new EntityAmphithere(world), LightLevel.any, BiomeHelper.getTypeNamesForTypes(Type.JUNGLE), EntityAmphithere.LOOT); registerRenderHook(EntityAmphithere.class, ((renderInfo, entityLivingBase) -> { GlStateManager.translate(-0.05,1.4,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableCockatrice) { registerMob(new EntityCockatrice(world), LightLevel.any, BiomeHelper.getTypeNamesForTypes(Type.SAVANNA, Type.SPARSE), EntityCockatrice.LOOT); } if(jerConfig.JER_MOBS.enableCyclops) { registerMob(new EntityCyclops(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.BEACH, Type.PLAINS), EntityCyclops.LOOT); registerRenderHook(EntityCyclops.class, ((renderInfo, entityLivingBase) -> { GlStateManager.scale(0.9,0.9,0.9); GlStateManager.translate(-0.05,-1.75,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableGorgon) { registerMob(new EntityGorgon(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.BEACH), EntityGorgon.LOOT); adjustHumanoidRenderHook(EntityGorgon.class); } if(jerConfig.JER_MOBS.enableHippocampus) { registerMob(new EntityHippocampus(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.OCEAN), EntityHippocampus.LOOT); } if(jerConfig.JER_MOBS.enableHippogryph) { registerMob(new EntityHippogryph(world), LightLevel.any, BiomeHelper.getTypeNamesForTypes(Type.HILLS), EntityHippogryph.LOOT); } if(jerConfig.JER_MOBS.enableHydra) { registerMob(new EntityHydra(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.SWAMP), EntityHydra.LOOT); registerRenderHook(EntityHydra.class, ((renderInfo, e) -> { GlStateManager.scale(1.75,1.75,1.75); GlStateManager.translate(-0.05,-0.4,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enablePixie) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.FOREST, Type.SPOOKY); validBiomes.addAll(BiomeDictionary.getBiomes(Type.MAGICAL)); registerMob(new EntityPixie(world), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityPixie.LOOT); } if(jerConfig.JER_MOBS.enableSiren) { THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.OCEAN)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.COLD)); registerMob(new EntitySiren(world), LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), EntitySiren.LOOT); } if(jerConfig.JER_MOBS.enableStymphalianBird) { registerMob(new EntityStymphalianBird(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.SWAMP), EntityStymphalianBird.LOOT); registerRenderHook(EntityStymphalianBird.class, ((renderInfo, e) -> { GlStateManager.scale(1.75,1.75,1.75); GlStateManager.translate(-0.05,-0.3,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableTrollForest) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.FOREST); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.FOREST_LOOT); } if(jerConfig.JER_MOBS.enableTrollFrost) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.FROST); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.FROST_LOOT); } if(jerConfig.JER_MOBS.enableTrollMountain) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.MOUNTAIN); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.MOUNTAIN_LOOT); } //Generic Render Hooks registerRenderHook(EntityTroll.class, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.8,0); return renderInfo; })); } public void registerRenderOverrides() { if(JEMConfig.ICE_AND_FIRE.enableRenderFixes) { //Ice and Fire uses the depreciated method to register entity renders. RenderingRegistry.registerEntityRenderingHandler(EntityHippocampus.class, new JERRenderHippocampus(Minecraft.getMinecraft().getRenderManager())); } } private THashSet<Biome> getIaFLinkedBiomes(Type... types) { THashSet<Biome> biomes = new THashSet<>(); for(Type type : types) { if(biomes.isEmpty()) { biomes.addAll(BiomeDictionary.getBiomes(type)); } else { biomes.removeIf(biome -> (!BiomeDictionary.getBiomes(type).contains(biome))); } } return biomes; } private String[] getIaFSpawnBiomesFromTypes(THashSet<Type> validTypes, THashSet<Type> invalidTypes) { THashSet<Biome> validBiomes = new THashSet<>(); for(Type validType : validTypes) { validBiomes.addAll(BiomeDictionary.getBiomes(validType)); } for(Type invalidType : invalidTypes) { validBiomes.removeAll(BiomeDictionary.getBiomes(invalidType)); } return validBiomes.isEmpty() ? new String[] {"jer.any"} : BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])); } private String[] getIaFSpawnBiomes(THashSet<Biome> biomes, THashSet<Type> invalidTypes) { for(Type type : invalidTypes) { biomes.removeAll(BiomeDictionary.getBiomes(type)); } return biomes.isEmpty() ? new String[] {"jer.any"} : BiomeHelper.getBiomeNamesForBiomes(biomes.toArray(new Biome[0])); } private void adjustHumanoidRenderHook(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.4,0); return renderInfo; })); } @Override public void registerModVillagers() { CustomVillagerRegistry registry = CustomVillagerRegistry.getInstance(); THashMap<VillagerProfession,EntityMyrmexBase> desertMyrmexVillagers = new THashMap<>(5); THashMap<VillagerProfession,EntityMyrmexBase> jungleMyrmexVillagers = new THashMap<>(5); if(jerConfig.JER_VILLAGERS.enableMyrmexQueen) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexQueen, setMyrmexTexture(new EntityMyrmexQueen(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexQueen, setMyrmexTexture(new EntityMyrmexQueen(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexRoyal) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexRoyal, setMyrmexTexture(new EntityMyrmexRoyal(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexRoyal, setMyrmexTexture(new EntityMyrmexRoyal(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexSentinel) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexSentinel, setMyrmexTexture(new EntityMyrmexSentinel(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexSentinel, setMyrmexTexture(new EntityMyrmexSentinel(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexSoldier) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexSoldier, setMyrmexTexture(new EntityMyrmexSoldier(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexSoldier, setMyrmexTexture(new EntityMyrmexSoldier(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexWorker) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexWorker, setMyrmexTexture(new EntityMyrmexWorker(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexWorker, setMyrmexTexture(new EntityMyrmexWorker(world), true)); } registerMyrmexVillagers(registry, desertMyrmexVillagers); registerMyrmexVillagers(registry, jungleMyrmexVillagers); if(jerConfig.JER_VILLAGERS.enableSnowVillager) { registerSnowVillagers(registry); } } private EntityMyrmexBase setMyrmexTexture(EntityMyrmexBase entity, boolean isJungle) { entity.setJungleVariant(isJungle); return entity; } private void registerMyrmexVillagers(CustomVillagerRegistry registry, THashMap<VillagerProfession,EntityMyrmexBase> myrmexVillagers) { myrmexVillagers.forEach((profession, villager) -> { try { VillagerCareer career = profession.getCareer(0); List<List<EntityVillager.ITradeList>> trades = (List<List<EntityVillager.ITradeList>>) ReflectionHelper.getFieldObject(career, "trades");
registry.addVillagerEntry(new CustomVanillaVillagerEntry(career.getName(), 0, trades) {
5
2023-11-19 23:09:14+00:00
24k
codingmiao/hppt
cc/src/main/java/org/wowtools/hppt/cc/service/ClientSessionService.java
[ { "identifier": "StartCc", "path": "cc/src/main/java/org/wowtools/hppt/cc/StartCc.java", "snippet": "@Slf4j\npublic class StartCc {\n public static CcConfig config;\n\n public static AesCipherUtil aesCipherUtil;\n\n public static String loginCode;\n\n static {\n Configurator.reconfigu...
import com.google.protobuf.ByteString; import lombok.extern.slf4j.Slf4j; import okhttp3.Response; import org.wowtools.hppt.cc.StartCc; import org.wowtools.hppt.common.protobuf.ProtoMessage; import org.wowtools.hppt.common.util.BytesUtil; import org.wowtools.hppt.common.util.Constant; import org.wowtools.hppt.common.util.HttpUtil; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean;
18,428
package org.wowtools.hppt.cc.service; /** * @author liuyu * @date 2023/12/21 */ @Slf4j public class ClientSessionService { private static final String talkUri = StartCc.config.serverUrl + "/talk?c="; private static long sleepTime = StartCc.config.initSleepTime - StartCc.config.addSleepTime; private static long noSleepLimitTime = 0; private static final AtomicBoolean sleeping = new AtomicBoolean(false); private static final Thread sendThread; static { sendThread = new Thread(() -> { while (true) { try { /* 发请求 */ boolean isEmpty = sendToSs(); /* 睡眠发送线程策略 */ if (noSleepLimitTime > System.currentTimeMillis()) { //线程刚刚被唤醒,不睡眠 sleepTime = StartCc.config.initSleepTime; log.debug("线程刚刚被唤醒 {}", sleepTime); } else if (isEmpty) { //收发数据包都为空,逐步增加睡眠时间 if (sleepTime < StartCc.config.maxSleepTime) { sleepTime += StartCc.config.addSleepTime; } log.debug("收发数据包都为空,逐步增加睡眠时间 {}", sleepTime); } else { sleepTime = StartCc.config.initSleepTime; log.debug("正常包 {}", sleepTime); } if (sleepTime > 0) { sleeping.set(true); try { log.debug("sleep {}", sleepTime); Thread.sleep(sleepTime); } catch (InterruptedException e) { log.info("发送进程被唤醒"); } finally { sleeping.set(false); } } } catch (Exception e) { log.warn("发消息到服务端发生异常", e); sleeping.set(true); try { Thread.sleep(StartCc.config.maxSleepTime); } catch (InterruptedException e1) { log.info("发送进程被唤醒"); } finally { sleeping.set(false); } StartCc.tryLogin(); } } }); } public static void start() { //启动轮询发送http请求线程 sendThread.start(); //起一个线程,定期检查超时session new Thread(() -> { while (true) { try { Thread.sleep(StartCc.config.sessionTimeout); log.debug("定期检查,当前session数 {}", ClientSessionManager.clientSessionMap.size()); for (Map.Entry<Integer, ClientSession> entry : ClientSessionManager.clientSessionMap.entrySet()) { ClientSession session = entry.getValue(); if (session.isTimeOut()) { ClientSessionManager.disposeClientSession(session, "超时不活跃"); } } } catch (Exception e) { log.warn("定期检查超时session异常", e); } } }).start(); } /** * 发请求 * * @return 是否为空包 即发送和接收都是空 * @throws Exception Exception */ private static boolean sendToSs() throws Exception { boolean isEmpty = true; List<ProtoMessage.BytesPb> bytePbList = new LinkedList<>(); //发字节 ClientSessionManager.clientSessionMap.forEach((sessionId, clientSession) -> { byte[] bytes = clientSession.fetchSendSessionBytes(); if (bytes != null) { bytePbList.add(ProtoMessage.BytesPb.newBuilder() .setSessionId(clientSession.getSessionId()) .setBytes(ByteString.copyFrom(bytes)) .build() ); } }); if (!bytePbList.isEmpty()) { isEmpty = false; } //发命令 List<String> commands = new LinkedList<>(); { StringBuilder closeSession = new StringBuilder().append(Constant.CsCommands.CloseSession); StringBuilder checkActiveSession = new StringBuilder().append(Constant.CsCommands.CheckSessionActive); ClientSessionManager.clientSessionMap.forEach((sessionId, session) -> { if (session.isNeedCheckActive()) { checkActiveSession.append(sessionId).append(Constant.sessionIdJoinFlag); } }); List<Integer> closedClientSessions = ClientSessionManager.fetchClosedClientSessions(); if (null != closedClientSessions) { for (Integer sessionId : closedClientSessions) { closeSession.append(sessionId).append(Constant.sessionIdJoinFlag); } } if (closeSession.length() > 1) { commands.add(closeSession.toString()); } if (checkActiveSession.length() > 1) { commands.add(checkActiveSession.toString()); } } cutSendToSs(bytePbList, commands); return isEmpty; } //如果请求体过大,会出现413 Request Entity Too Large,拆分一下发送 private static boolean cutSendToSs(List<ProtoMessage.BytesPb> bytePbs, List<String> commands) throws Exception { List<ProtoMessage.BytesPb> bytesPbList = new LinkedList<>(); List<String> commandList = new LinkedList<>(); int requestBodyLength = 0; while (!bytePbs.isEmpty()) { if (bytePbs.getFirst().getBytes().size() > StartCc.config.maxSendBodySize) { //单个bytePb包含的字节数就超过限制了,那把bytes拆小 ProtoMessage.BytesPb bytePb = bytePbs.removeFirst(); byte[][] splitBytes = BytesUtil.splitBytes(bytePb.getBytes().toByteArray(), StartCc.config.maxSendBodySize); for (int i = splitBytes.length - 1; i >= 0; i--) { bytePbs.addFirst(ProtoMessage.BytesPb.newBuilder() .setBytes(ByteString.copyFrom(splitBytes[i])) .setSessionId(bytePb.getSessionId()) .build()); } } else { requestBodyLength += bytePbs.getFirst().getBytes().size(); if (requestBodyLength > StartCc.config.maxSendBodySize) { break; } bytesPbList.add(bytePbs.removeFirst()); } } while (!commands.isEmpty()) { if (commands.getFirst().length() > StartCc.config.maxSendBodySize) { throw new RuntimeException("maxSendBodySize 的值过小导致无法发送命令,请调整"); } requestBodyLength += commands.getFirst().length();//注意,这里限定了命令只能是ASCII字符 if (requestBodyLength > StartCc.config.maxSendBodySize) { break; } commandList.add(commands.removeFirst()); } log.debug("requestBodyLength {}", requestBodyLength); boolean isEmpty = subSendToSs(bytesPbList, commandList); if (bytePbs.isEmpty() && commands.isEmpty()) { return isEmpty; } else { return cutSendToSs(bytePbs, commands); } } //发送和接收 private static boolean subSendToSs(List<ProtoMessage.BytesPb> bytesPbList, List<String> commandList) throws Exception { boolean isEmpty = true; ProtoMessage.MessagePb.Builder messagePbBuilder = ProtoMessage.MessagePb.newBuilder(); if (!bytesPbList.isEmpty()) { messagePbBuilder.addAllBytesPbList(bytesPbList); } if (!commandList.isEmpty()) { messagePbBuilder.addAllCommandList(commandList); } byte[] requestBody = messagePbBuilder.build().toByteArray(); //压缩、加密 if (StartCc.config.enableCompress) { requestBody = BytesUtil.compress(requestBody); } if (StartCc.config.enableEncrypt) { requestBody = StartCc.aesCipherUtil.encryptor.encrypt(requestBody); } log.debug("发送数据 bytesPbs {} commands {} 字节数 {}", bytesPbList.size(), commandList.size(), requestBody.length); Response response; if (log.isDebugEnabled()) { long t = System.currentTimeMillis();
package org.wowtools.hppt.cc.service; /** * @author liuyu * @date 2023/12/21 */ @Slf4j public class ClientSessionService { private static final String talkUri = StartCc.config.serverUrl + "/talk?c="; private static long sleepTime = StartCc.config.initSleepTime - StartCc.config.addSleepTime; private static long noSleepLimitTime = 0; private static final AtomicBoolean sleeping = new AtomicBoolean(false); private static final Thread sendThread; static { sendThread = new Thread(() -> { while (true) { try { /* 发请求 */ boolean isEmpty = sendToSs(); /* 睡眠发送线程策略 */ if (noSleepLimitTime > System.currentTimeMillis()) { //线程刚刚被唤醒,不睡眠 sleepTime = StartCc.config.initSleepTime; log.debug("线程刚刚被唤醒 {}", sleepTime); } else if (isEmpty) { //收发数据包都为空,逐步增加睡眠时间 if (sleepTime < StartCc.config.maxSleepTime) { sleepTime += StartCc.config.addSleepTime; } log.debug("收发数据包都为空,逐步增加睡眠时间 {}", sleepTime); } else { sleepTime = StartCc.config.initSleepTime; log.debug("正常包 {}", sleepTime); } if (sleepTime > 0) { sleeping.set(true); try { log.debug("sleep {}", sleepTime); Thread.sleep(sleepTime); } catch (InterruptedException e) { log.info("发送进程被唤醒"); } finally { sleeping.set(false); } } } catch (Exception e) { log.warn("发消息到服务端发生异常", e); sleeping.set(true); try { Thread.sleep(StartCc.config.maxSleepTime); } catch (InterruptedException e1) { log.info("发送进程被唤醒"); } finally { sleeping.set(false); } StartCc.tryLogin(); } } }); } public static void start() { //启动轮询发送http请求线程 sendThread.start(); //起一个线程,定期检查超时session new Thread(() -> { while (true) { try { Thread.sleep(StartCc.config.sessionTimeout); log.debug("定期检查,当前session数 {}", ClientSessionManager.clientSessionMap.size()); for (Map.Entry<Integer, ClientSession> entry : ClientSessionManager.clientSessionMap.entrySet()) { ClientSession session = entry.getValue(); if (session.isTimeOut()) { ClientSessionManager.disposeClientSession(session, "超时不活跃"); } } } catch (Exception e) { log.warn("定期检查超时session异常", e); } } }).start(); } /** * 发请求 * * @return 是否为空包 即发送和接收都是空 * @throws Exception Exception */ private static boolean sendToSs() throws Exception { boolean isEmpty = true; List<ProtoMessage.BytesPb> bytePbList = new LinkedList<>(); //发字节 ClientSessionManager.clientSessionMap.forEach((sessionId, clientSession) -> { byte[] bytes = clientSession.fetchSendSessionBytes(); if (bytes != null) { bytePbList.add(ProtoMessage.BytesPb.newBuilder() .setSessionId(clientSession.getSessionId()) .setBytes(ByteString.copyFrom(bytes)) .build() ); } }); if (!bytePbList.isEmpty()) { isEmpty = false; } //发命令 List<String> commands = new LinkedList<>(); { StringBuilder closeSession = new StringBuilder().append(Constant.CsCommands.CloseSession); StringBuilder checkActiveSession = new StringBuilder().append(Constant.CsCommands.CheckSessionActive); ClientSessionManager.clientSessionMap.forEach((sessionId, session) -> { if (session.isNeedCheckActive()) { checkActiveSession.append(sessionId).append(Constant.sessionIdJoinFlag); } }); List<Integer> closedClientSessions = ClientSessionManager.fetchClosedClientSessions(); if (null != closedClientSessions) { for (Integer sessionId : closedClientSessions) { closeSession.append(sessionId).append(Constant.sessionIdJoinFlag); } } if (closeSession.length() > 1) { commands.add(closeSession.toString()); } if (checkActiveSession.length() > 1) { commands.add(checkActiveSession.toString()); } } cutSendToSs(bytePbList, commands); return isEmpty; } //如果请求体过大,会出现413 Request Entity Too Large,拆分一下发送 private static boolean cutSendToSs(List<ProtoMessage.BytesPb> bytePbs, List<String> commands) throws Exception { List<ProtoMessage.BytesPb> bytesPbList = new LinkedList<>(); List<String> commandList = new LinkedList<>(); int requestBodyLength = 0; while (!bytePbs.isEmpty()) { if (bytePbs.getFirst().getBytes().size() > StartCc.config.maxSendBodySize) { //单个bytePb包含的字节数就超过限制了,那把bytes拆小 ProtoMessage.BytesPb bytePb = bytePbs.removeFirst(); byte[][] splitBytes = BytesUtil.splitBytes(bytePb.getBytes().toByteArray(), StartCc.config.maxSendBodySize); for (int i = splitBytes.length - 1; i >= 0; i--) { bytePbs.addFirst(ProtoMessage.BytesPb.newBuilder() .setBytes(ByteString.copyFrom(splitBytes[i])) .setSessionId(bytePb.getSessionId()) .build()); } } else { requestBodyLength += bytePbs.getFirst().getBytes().size(); if (requestBodyLength > StartCc.config.maxSendBodySize) { break; } bytesPbList.add(bytePbs.removeFirst()); } } while (!commands.isEmpty()) { if (commands.getFirst().length() > StartCc.config.maxSendBodySize) { throw new RuntimeException("maxSendBodySize 的值过小导致无法发送命令,请调整"); } requestBodyLength += commands.getFirst().length();//注意,这里限定了命令只能是ASCII字符 if (requestBodyLength > StartCc.config.maxSendBodySize) { break; } commandList.add(commands.removeFirst()); } log.debug("requestBodyLength {}", requestBodyLength); boolean isEmpty = subSendToSs(bytesPbList, commandList); if (bytePbs.isEmpty() && commands.isEmpty()) { return isEmpty; } else { return cutSendToSs(bytePbs, commands); } } //发送和接收 private static boolean subSendToSs(List<ProtoMessage.BytesPb> bytesPbList, List<String> commandList) throws Exception { boolean isEmpty = true; ProtoMessage.MessagePb.Builder messagePbBuilder = ProtoMessage.MessagePb.newBuilder(); if (!bytesPbList.isEmpty()) { messagePbBuilder.addAllBytesPbList(bytesPbList); } if (!commandList.isEmpty()) { messagePbBuilder.addAllCommandList(commandList); } byte[] requestBody = messagePbBuilder.build().toByteArray(); //压缩、加密 if (StartCc.config.enableCompress) { requestBody = BytesUtil.compress(requestBody); } if (StartCc.config.enableEncrypt) { requestBody = StartCc.aesCipherUtil.encryptor.encrypt(requestBody); } log.debug("发送数据 bytesPbs {} commands {} 字节数 {}", bytesPbList.size(), commandList.size(), requestBody.length); Response response; if (log.isDebugEnabled()) { long t = System.currentTimeMillis();
response = HttpUtil.doPost(talkUri + StartCc.loginCode, requestBody);
4
2023-12-22 14:14:27+00:00
24k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/services/BlockPlacer.java
[ { "identifier": "CrystalPosition", "path": "src/main/java/me/earth/phobot/damagecalc/CrystalPosition.java", "snippet": "@Getter\n@Setter\n@RequiredArgsConstructor\npublic class CrystalPosition extends MutPos {\n public static final long MAX_DEATHTIME = 100L;\n private final Entity[] crystals = new...
import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import me.earth.phobot.damagecalc.CrystalPosition; import me.earth.phobot.damagecalc.DamageCalculator; import me.earth.phobot.event.PostMotionPlayerUpdateEvent; import me.earth.phobot.event.PreMotionPlayerUpdateEvent; import me.earth.phobot.modules.ChecksBlockPlacingValidity; import me.earth.phobot.modules.client.anticheat.AntiCheat; import me.earth.phobot.modules.combat.autocrystal.CrystalPlacer; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.services.inventory.InventoryService; import me.earth.phobot.util.math.RaytraceUtil; import me.earth.phobot.util.math.RotationUtil; import me.earth.phobot.util.world.BlockStateLevel; import me.earth.phobot.util.world.PredictionUtil; import me.earth.pingbypass.api.event.SubscriberImpl; import me.earth.pingbypass.commons.event.SafeListener; import net.minecraft.client.Minecraft; 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.ServerboundInteractPacket; import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket; import net.minecraft.network.protocol.game.ServerboundUseItemOnPacket; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.boss.enderdragon.EndCrystal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.NotNull; import java.util.*; import static me.earth.phobot.services.inventory.InventoryContext.*;
15,740
package me.earth.phobot.services; @Getter public class BlockPlacer extends SubscriberImpl { public static final int PRIORITY = 10_000; private final Queue<PlacesBlocks> modules = new PriorityQueue<>(); private final List<Action> actions = new ArrayList<>(); private final LocalPlayerPositionService localPlayerPositionService; private final MotionUpdateService motionUpdateService; private final AntiCheat antiCheat; private final Minecraft minecraft; private CollisionContext collisionContext = CollisionContext.empty(); private BlockStateLevel.Delegating customBlockStateLevel = null; @Setter private EndCrystal crystal; private boolean attacked = false; private boolean completed = false; private volatile boolean inTick = false;
package me.earth.phobot.services; @Getter public class BlockPlacer extends SubscriberImpl { public static final int PRIORITY = 10_000; private final Queue<PlacesBlocks> modules = new PriorityQueue<>(); private final List<Action> actions = new ArrayList<>(); private final LocalPlayerPositionService localPlayerPositionService; private final MotionUpdateService motionUpdateService; private final AntiCheat antiCheat; private final Minecraft minecraft; private CollisionContext collisionContext = CollisionContext.empty(); private BlockStateLevel.Delegating customBlockStateLevel = null; @Setter private EndCrystal crystal; private boolean attacked = false; private boolean completed = false; private volatile boolean inTick = false;
public BlockPlacer(LocalPlayerPositionService localPlayerPositionService, MotionUpdateService motionUpdateService, InventoryService inventoryService, Minecraft minecraft, AntiCheat antiCheat) {
7
2023-12-22 14:32:16+00:00
24k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/commands/DungeonRoomCommand.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"...
import com.google.gson.JsonElement; import io.github.quantizr.DungeonRooms; import io.github.quantizr.core.AutoRoom; import io.github.quantizr.core.Waypoints; import io.github.quantizr.handlers.ConfigHandler; import io.github.quantizr.handlers.OpenLink; import io.github.quantizr.utils.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.GameSettings; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.util.*; import net.minecraft.world.World; import java.awt.*; import java.awt.datatransfer.StringSelection; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.List;
17,360
/* 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.commands; public class DungeonRoomCommand extends CommandBase { @Override public String getCommandName() { return "room"; } @Override public String getCommandUsage(ICommandSender arg0) { return "/" + getCommandName(); } @Override public List<String> getCommandAliases() { return Collections.singletonList("dungeonroom"); } @Override public int getRequiredPermissionLevel() { return 0; } @Override public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) { if (args.length == 1) { return getListOfStringsMatchingLastWord(args, "help", "waypoints", "move", "toggle", "set", "discord"); } if (args.length > 1) { if (args[0].equalsIgnoreCase("toggle")) { return getListOfStringsMatchingLastWord(args, "help", "gui", "chat", "waypointtext", "waypointboundingbox", "waypointbeacon"); } else if (args[0].equalsIgnoreCase("set")) { return getListOfStringsMatchingLastWord(args, "gui", "dsg", "sbp"); } } return null; } @Override public void processCommand(ICommandSender arg0, String[] arg1) { new Thread(() -> { EntityPlayer player = (EntityPlayer) arg0; int x = (int) Math.floor(player.posX); int y = (int) Math.floor(player.posY); int z = (int) Math.floor(player.posZ); if (arg1.length < 1) { if (!Utils.inDungeons) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: Use this command in dungeons or run \"/room help\" for additional options")); return; } int top = Utils.dungeonTop(x,y,z); String blockFrequencies = Utils.blockFrequency(x,top,z,true); if (blockFrequencies == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: Make sure you aren't in a hallway between rooms and that your render distance is high enough.")); return; } List<String> autoText = AutoRoom.autoText(); if (autoText != null) { AutoRoom.autoTextOutput = autoText; } if (AutoRoom.autoTextOutput == null) return; if (AutoRoom.autoTextOutput.isEmpty()) return; for (String message:AutoRoom.autoTextOutput) { player.addChatMessage(new ChatComponentText(message)); } } else { int top = Utils.dungeonTop(x,y,z); String blockFrequencies = Utils.blockFrequency(x,top,z, true); String size = Utils.getSize(x,top,z); String MD5 = Utils.getMD5(blockFrequencies); String floorFrequencies = Utils.floorFrequency(x, top, z); String floorHash = Utils.getMD5(floorFrequencies); switch (arg1[0].toLowerCase()) { case "help": player.addChatMessage(new ChatComponentText(
/* 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.commands; public class DungeonRoomCommand extends CommandBase { @Override public String getCommandName() { return "room"; } @Override public String getCommandUsage(ICommandSender arg0) { return "/" + getCommandName(); } @Override public List<String> getCommandAliases() { return Collections.singletonList("dungeonroom"); } @Override public int getRequiredPermissionLevel() { return 0; } @Override public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) { if (args.length == 1) { return getListOfStringsMatchingLastWord(args, "help", "waypoints", "move", "toggle", "set", "discord"); } if (args.length > 1) { if (args[0].equalsIgnoreCase("toggle")) { return getListOfStringsMatchingLastWord(args, "help", "gui", "chat", "waypointtext", "waypointboundingbox", "waypointbeacon"); } else if (args[0].equalsIgnoreCase("set")) { return getListOfStringsMatchingLastWord(args, "gui", "dsg", "sbp"); } } return null; } @Override public void processCommand(ICommandSender arg0, String[] arg1) { new Thread(() -> { EntityPlayer player = (EntityPlayer) arg0; int x = (int) Math.floor(player.posX); int y = (int) Math.floor(player.posY); int z = (int) Math.floor(player.posZ); if (arg1.length < 1) { if (!Utils.inDungeons) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: Use this command in dungeons or run \"/room help\" for additional options")); return; } int top = Utils.dungeonTop(x,y,z); String blockFrequencies = Utils.blockFrequency(x,top,z,true); if (blockFrequencies == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: Make sure you aren't in a hallway between rooms and that your render distance is high enough.")); return; } List<String> autoText = AutoRoom.autoText(); if (autoText != null) { AutoRoom.autoTextOutput = autoText; } if (AutoRoom.autoTextOutput == null) return; if (AutoRoom.autoTextOutput.isEmpty()) return; for (String message:AutoRoom.autoTextOutput) { player.addChatMessage(new ChatComponentText(message)); } } else { int top = Utils.dungeonTop(x,y,z); String blockFrequencies = Utils.blockFrequency(x,top,z, true); String size = Utils.getSize(x,top,z); String MD5 = Utils.getMD5(blockFrequencies); String floorFrequencies = Utils.floorFrequency(x, top, z); String floorHash = Utils.getMD5(floorFrequencies); switch (arg1[0].toLowerCase()) { case "help": player.addChatMessage(new ChatComponentText(
"\n" + EnumChatFormatting.GOLD + "FakepixelDungeonHelper Mod Version " + DungeonRooms.VERSION + "\n" +
0
2023-12-22 04:44:39+00:00
24k
psobiech/opengr8on
vclu/src/main/java/pl/psobiech/opengr8on/vclu/VirtualSystem.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.io.Closeable; import java.net.Inet4Address; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.luaj.vm2.LuaValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.psobiech.opengr8on.client.CLUClient; import pl.psobiech.opengr8on.client.CipherKey; import pl.psobiech.opengr8on.client.device.CLUDevice; import pl.psobiech.opengr8on.exceptions.UncheckedInterruptedException; import pl.psobiech.opengr8on.util.FileUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.ThreadUtil; import pl.psobiech.opengr8on.vclu.objects.HttpRequest; import pl.psobiech.opengr8on.vclu.objects.MqttTopic; import pl.psobiech.opengr8on.vclu.objects.RemoteCLU; import pl.psobiech.opengr8on.vclu.objects.Storage; import pl.psobiech.opengr8on.vclu.objects.Timer; import pl.psobiech.opengr8on.vclu.util.LuaUtil;
16,781
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.vclu; public class VirtualSystem implements Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(VirtualSystem.class); private static final long LOOP_TIME_NANOS = TimeUnit.MILLISECONDS.toNanos(64); private static final long LOG_LOOP_TIME_NANOS = TimeUnit.MILLISECONDS.toNanos(8); private static final long NANOS_IN_MILLISECOND = TimeUnit.MILLISECONDS.toNanos(1); private final ScheduledExecutorService executors = ThreadUtil.executor("LuaServer"); private final Path aDriveDirectory; private final Inet4Address localAddress; private final CLUDevice device; private final CipherKey cipherKey; private final Map<String, VirtualObject> objectsByName = new HashMap<>(); private VirtualCLU currentClu = null; private ScheduledFuture<?> clientReportFuture = null; public VirtualSystem(Path aDriveDirectory, Inet4Address localAddress, CLUDevice device, CipherKey cipherKey) { this.aDriveDirectory = aDriveDirectory; this.localAddress = localAddress; this.device = device; this.cipherKey = cipherKey; } public VirtualObject getObject(String name) { return objectsByName.get(name); } public VirtualCLU getCurrentClu() { return currentClu; } @SuppressWarnings("resource") public void newObject(int index, String name, int ipAddress) { final VirtualObject virtualObject = switch (index) { // TODO: temporarily we depend that the main CLU is initialized first-ish case VirtualCLU.INDEX -> (currentClu = new VirtualCLU(name)); case RemoteCLU.INDEX -> new RemoteCLU(name, IPv4AddressUtil.parseIPv4(ipAddress), localAddress, cipherKey); case Timer.INDEX -> new Timer(name); case Storage.INDEX -> new Storage(name); case MqttTopic.INDEX -> new MqttTopic(name, currentClu); default -> new VirtualObject(name); }; objectsByName.put(name, virtualObject); } @SuppressWarnings("resource") public void newGate(int index, String name) { final VirtualObject virtualObject = switch (index) { case HttpRequest.INDEX -> new HttpRequest(name); case MqttTopic.INDEX -> new MqttTopic(name, currentClu); default -> new VirtualObject(name); }; objectsByName.put(name, virtualObject); } public void setup() { for (VirtualObject value : objectsByName.values()) { try { value.setup(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } } public void loop() { final long startTime = System.nanoTime(); for (VirtualObject object : objectsByName.values()) { final long objectStartTime = System.nanoTime(); try { object.loop(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } finally { final long objectDeltaNanos = (System.nanoTime() - objectStartTime); if (objectDeltaNanos > LOG_LOOP_TIME_NANOS) { LOGGER.warn("Object {} loop time took {}ms", object.getName(), TimeUnit.NANOSECONDS.toMillis(objectDeltaNanos)); } } Thread.yield(); } // best effort to run loop with fixed rate final long timeLeft = LOOP_TIME_NANOS - (System.nanoTime() - startTime); if (timeLeft < 0) { LOGGER.warn("Exceeded loop time by {}ms", -TimeUnit.NANOSECONDS.toMillis(timeLeft)); } sleepNanos(Math.max(0, timeLeft)); } public void sleep(long millis) { sleepNanos(TimeUnit.MILLISECONDS.toNanos(millis)); } public void sleepNanos(long nanoSeconds) { final long millis = nanoSeconds / NANOS_IN_MILLISECOND; final int nanos = (int) (nanoSeconds % NANOS_IN_MILLISECOND); try { Thread.sleep(millis, nanos); } catch (InterruptedException e) { Thread.currentThread().interrupt();
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.vclu; public class VirtualSystem implements Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(VirtualSystem.class); private static final long LOOP_TIME_NANOS = TimeUnit.MILLISECONDS.toNanos(64); private static final long LOG_LOOP_TIME_NANOS = TimeUnit.MILLISECONDS.toNanos(8); private static final long NANOS_IN_MILLISECOND = TimeUnit.MILLISECONDS.toNanos(1); private final ScheduledExecutorService executors = ThreadUtil.executor("LuaServer"); private final Path aDriveDirectory; private final Inet4Address localAddress; private final CLUDevice device; private final CipherKey cipherKey; private final Map<String, VirtualObject> objectsByName = new HashMap<>(); private VirtualCLU currentClu = null; private ScheduledFuture<?> clientReportFuture = null; public VirtualSystem(Path aDriveDirectory, Inet4Address localAddress, CLUDevice device, CipherKey cipherKey) { this.aDriveDirectory = aDriveDirectory; this.localAddress = localAddress; this.device = device; this.cipherKey = cipherKey; } public VirtualObject getObject(String name) { return objectsByName.get(name); } public VirtualCLU getCurrentClu() { return currentClu; } @SuppressWarnings("resource") public void newObject(int index, String name, int ipAddress) { final VirtualObject virtualObject = switch (index) { // TODO: temporarily we depend that the main CLU is initialized first-ish case VirtualCLU.INDEX -> (currentClu = new VirtualCLU(name)); case RemoteCLU.INDEX -> new RemoteCLU(name, IPv4AddressUtil.parseIPv4(ipAddress), localAddress, cipherKey); case Timer.INDEX -> new Timer(name); case Storage.INDEX -> new Storage(name); case MqttTopic.INDEX -> new MqttTopic(name, currentClu); default -> new VirtualObject(name); }; objectsByName.put(name, virtualObject); } @SuppressWarnings("resource") public void newGate(int index, String name) { final VirtualObject virtualObject = switch (index) { case HttpRequest.INDEX -> new HttpRequest(name); case MqttTopic.INDEX -> new MqttTopic(name, currentClu); default -> new VirtualObject(name); }; objectsByName.put(name, virtualObject); } public void setup() { for (VirtualObject value : objectsByName.values()) { try { value.setup(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } } public void loop() { final long startTime = System.nanoTime(); for (VirtualObject object : objectsByName.values()) { final long objectStartTime = System.nanoTime(); try { object.loop(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } finally { final long objectDeltaNanos = (System.nanoTime() - objectStartTime); if (objectDeltaNanos > LOG_LOOP_TIME_NANOS) { LOGGER.warn("Object {} loop time took {}ms", object.getName(), TimeUnit.NANOSECONDS.toMillis(objectDeltaNanos)); } } Thread.yield(); } // best effort to run loop with fixed rate final long timeLeft = LOOP_TIME_NANOS - (System.nanoTime() - startTime); if (timeLeft < 0) { LOGGER.warn("Exceeded loop time by {}ms", -TimeUnit.NANOSECONDS.toMillis(timeLeft)); } sleepNanos(Math.max(0, timeLeft)); } public void sleep(long millis) { sleepNanos(TimeUnit.MILLISECONDS.toNanos(millis)); } public void sleepNanos(long nanoSeconds) { final long millis = nanoSeconds / NANOS_IN_MILLISECOND; final int nanos = (int) (nanoSeconds % NANOS_IN_MILLISECOND); try { Thread.sleep(millis, nanos); } catch (InterruptedException e) { Thread.currentThread().interrupt();
throw new UncheckedInterruptedException(e);
3
2023-12-23 09:56:14+00:00
24k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/module/impl/player/GiftAura.java
[ { "identifier": "MayOBeesConfig", "path": "src/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java", "snippet": "public class MayOBeesConfig extends Config {\n\n //<editor-fold desc=\"COMBAT\">\n @KeyBind(\n name = \"Shortbow Aura\",\n description = \"Automatica...
import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.handler.GameStateHandler; import com.github.may2beez.mayobees.handler.RotationHandler; import com.github.may2beez.mayobees.module.IModule; import com.github.may2beez.mayobees.module.IModuleActive; import com.github.may2beez.mayobees.util.HeadUtils; import com.github.may2beez.mayobees.util.LogUtils; import com.github.may2beez.mayobees.util.RenderUtils; import com.github.may2beez.mayobees.util.helper.Clock; import com.github.may2beez.mayobees.util.helper.RotationConfiguration; import com.github.may2beez.mayobees.util.helper.Target; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityArmorStand; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.util.ArrayList; import java.util.Comparator; import java.util.List;
18,557
package com.github.may2beez.mayobees.module.impl.player; public class GiftAura implements IModuleActive { private static GiftAura instance; public static GiftAura getInstance() { if (instance == null) { instance = new GiftAura(); } return instance; } @Override public String getName() { return "Gift Aura"; } private final Minecraft mc = Minecraft.getMinecraft(); private final List<EntityArmorStand> openedGifts = new ArrayList<>(); private final Clock delay = new Clock(); @Override public boolean isRunning() { if (mc.thePlayer == null || mc.theWorld == null) return false; if (!MayOBeesConfig.giftAura) return false; if (GameStateHandler.getInstance().getLocation() == GameStateHandler.Location.JERRY_WORKSHOP) return true; return GameStateHandler.getInstance().getLocation() != GameStateHandler.Location.JERRY_WORKSHOP && MayOBeesConfig.giftAuraOpenGiftsOutsideOfJerryWorkshop; } @Override public void onEnable() { MayOBeesConfig.giftAura = true; } @Override public void onDisable() { MayOBeesConfig.giftAura = false; } public void reset() { openedGifts.clear(); } @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (mc.theWorld == null) return; List<Entity> loadedEntities = mc.theWorld.loadedEntityList; for (Entity entity : loadedEntities) { if (entity instanceof EntityArmorStand && shouldOpenGift((EntityArmorStand) entity) && !openedGifts.contains(entity)) {
package com.github.may2beez.mayobees.module.impl.player; public class GiftAura implements IModuleActive { private static GiftAura instance; public static GiftAura getInstance() { if (instance == null) { instance = new GiftAura(); } return instance; } @Override public String getName() { return "Gift Aura"; } private final Minecraft mc = Minecraft.getMinecraft(); private final List<EntityArmorStand> openedGifts = new ArrayList<>(); private final Clock delay = new Clock(); @Override public boolean isRunning() { if (mc.thePlayer == null || mc.theWorld == null) return false; if (!MayOBeesConfig.giftAura) return false; if (GameStateHandler.getInstance().getLocation() == GameStateHandler.Location.JERRY_WORKSHOP) return true; return GameStateHandler.getInstance().getLocation() != GameStateHandler.Location.JERRY_WORKSHOP && MayOBeesConfig.giftAuraOpenGiftsOutsideOfJerryWorkshop; } @Override public void onEnable() { MayOBeesConfig.giftAura = true; } @Override public void onDisable() { MayOBeesConfig.giftAura = false; } public void reset() { openedGifts.clear(); } @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (mc.theWorld == null) return; List<Entity> loadedEntities = mc.theWorld.loadedEntityList; for (Entity entity : loadedEntities) { if (entity instanceof EntityArmorStand && shouldOpenGift((EntityArmorStand) entity) && !openedGifts.contains(entity)) {
RenderUtils.drawHeadBox(entity, MayOBeesConfig.giftAuraESPColor.toJavaColor());
7
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,371
} @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_edit_entry: createCarEditActivity(); return true; case R.id.action_add_picture: createAddPictureActivity(); return true; case R.id.action_view_consumptions: createViewConsumptionsActivity(); return true; case R.id.action_view_chart: createConsumptionPlotActivity(); return true; case R.id.action_remove_entry: removeEntry(); return true; case R.id.action_import_data: createImportDataActivity(); return true; case R.id.action_export_data: // exportData(); storeDriveData(); return true; default: return super.onOptionsItemSelected(item); } } // Create an anonymous implementation of OnClickListener private OnClickListener clickListener = v -> { switch (v.getId()) { case R.id.float_add: createAddConsumptionActivity(); break; } }; private void createCarEditActivity() { Intent intent = new Intent(getActivity(), CarInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("update", true); getActivity().startActivity(intent); } private void createAddConsumptionActivity() { Intent intent = new Intent(getActivity(), ConsumptionInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("kmstate", dataSource.getMileageForCar(carId)); getActivity().startActivity(intent); } private void createAddPictureActivity() { Intent intent = new Intent(getActivity(), PictureImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createImportDataActivity() { Intent intent = new Intent(getActivity(), ImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void removeEntry() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getActivity()); // set title alertDialogBuilder.setTitle("Eintrag löschen?"); TypedValue typedValue = new TypedValue(); getActivity().getTheme().resolveAttribute(android.R.attr.alertDialogIcon, typedValue, true); alertDialogBuilder.setIcon(typedValue.resourceId); // set dialog message alertDialogBuilder .setMessage( "Mit 'Ja' wird der Fahrzeugdatensatz und alle dazugehörigen Verbrauchsdatensätze gelöscht!") .setCancelable(false) .setPositiveButton("Ja", (dialog, id) -> { dataSource.deleteConsumptionsForCar(carId); dataSource.deleteCar(dataSource.getCarForId(carId)); getActivity().finish(); }) .setNegativeButton("Nein", (dialog, id) -> dialog.cancel()); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } private void createViewConsumptionsActivity() { Intent intent = new Intent(getActivity(), ConsumptionListActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createConsumptionPlotActivity() { // Intent intent = new Intent(CarContentActivity.this, PlotActivity.class); // Intent intent = new Intent(CarContentActivity.this, XYPlot.class); Intent intent = new Intent(getActivity(), GraphViewPlot.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void updateView() {
package de.anipe.verbrauchsapp.fragments; /** * */ public class CarContentFragment extends Fragment { private FileSystemAccessor accessor; private ConsumptionDataSource dataSource; private long carId; private View rootView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accessor = FileSystemAccessor.getInstance(); dataSource = ConsumptionDataSource.getInstance(getActivity()); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { carId = getArguments().getLong("carid"); // The last two arguments ensure LayoutParams are inflated properly. rootView = inflater.inflate(R.layout.activity_car_content, container, false); FloatingActionButton btn = rootView.findViewById(R.id.float_add); btn.setOnClickListener(clickListener); return rootView; } @Override public void onResume() { updateView(); super.onResume(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.car_menubar, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_edit_entry: createCarEditActivity(); return true; case R.id.action_add_picture: createAddPictureActivity(); return true; case R.id.action_view_consumptions: createViewConsumptionsActivity(); return true; case R.id.action_view_chart: createConsumptionPlotActivity(); return true; case R.id.action_remove_entry: removeEntry(); return true; case R.id.action_import_data: createImportDataActivity(); return true; case R.id.action_export_data: // exportData(); storeDriveData(); return true; default: return super.onOptionsItemSelected(item); } } // Create an anonymous implementation of OnClickListener private OnClickListener clickListener = v -> { switch (v.getId()) { case R.id.float_add: createAddConsumptionActivity(); break; } }; private void createCarEditActivity() { Intent intent = new Intent(getActivity(), CarInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("update", true); getActivity().startActivity(intent); } private void createAddConsumptionActivity() { Intent intent = new Intent(getActivity(), ConsumptionInputActivity.class); intent.putExtra("carid", carId); intent.putExtra("kmstate", dataSource.getMileageForCar(carId)); getActivity().startActivity(intent); } private void createAddPictureActivity() { Intent intent = new Intent(getActivity(), PictureImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createImportDataActivity() { Intent intent = new Intent(getActivity(), ImportActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void removeEntry() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( getActivity()); // set title alertDialogBuilder.setTitle("Eintrag löschen?"); TypedValue typedValue = new TypedValue(); getActivity().getTheme().resolveAttribute(android.R.attr.alertDialogIcon, typedValue, true); alertDialogBuilder.setIcon(typedValue.resourceId); // set dialog message alertDialogBuilder .setMessage( "Mit 'Ja' wird der Fahrzeugdatensatz und alle dazugehörigen Verbrauchsdatensätze gelöscht!") .setCancelable(false) .setPositiveButton("Ja", (dialog, id) -> { dataSource.deleteConsumptionsForCar(carId); dataSource.deleteCar(dataSource.getCarForId(carId)); getActivity().finish(); }) .setNegativeButton("Nein", (dialog, id) -> dialog.cancel()); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } private void createViewConsumptionsActivity() { Intent intent = new Intent(getActivity(), ConsumptionListActivity.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void createConsumptionPlotActivity() { // Intent intent = new Intent(CarContentActivity.this, PlotActivity.class); // Intent intent = new Intent(CarContentActivity.this, XYPlot.class); Intent intent = new Intent(getActivity(), GraphViewPlot.class); intent.putExtra("carid", carId); getActivity().startActivity(intent); } private void updateView() {
Car car = dataSource.getCarForId(carId);
11
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,190
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());
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());
1
2023-12-31 10:56:59+00:00
24k
HuXin0817/shop_api
buyer-api/src/main/java/cn/lili/controller/passport/connect/ConnectBuyerWebController.java
[ { "identifier": "ResultCode", "path": "framework/src/main/java/cn/lili/common/enums/ResultCode.java", "snippet": "public enum ResultCode {\n\n /**\n * 成功状态码\n */\n SUCCESS(200, \"成功\"),\n\n /**\n * 失败返回码\n */\n ERROR(400, \"服务器繁忙,请稍后重试\"),\n\n /**\n * 失败返回码\n */\n ...
import cn.lili.common.enums.ResultCode; import cn.lili.common.enums.ResultUtil; import cn.lili.common.exception.ServiceException; import cn.lili.common.security.token.Token; import cn.lili.common.utils.UuidUtils; import cn.lili.common.vo.ResultMessage; import cn.lili.modules.connect.entity.dto.AuthCallback; import cn.lili.modules.connect.entity.dto.ConnectAuthUser; import cn.lili.modules.connect.request.AuthRequest; import cn.lili.modules.connect.service.ConnectService; import cn.lili.modules.connect.util.ConnectUtil; import cn.lili.modules.member.service.MemberService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
16,629
package cn.lili.controller.passport.connect; /** * 买家端,web联合登录 * * @author Chopper */ @Slf4j @RestController @Api(tags = "买家端,web联合登录") @RequestMapping("/buyer/passport/connect/connect") public class ConnectBuyerWebController { @Autowired private ConnectService connectService; @Autowired
package cn.lili.controller.passport.connect; /** * 买家端,web联合登录 * * @author Chopper */ @Slf4j @RestController @Api(tags = "买家端,web联合登录") @RequestMapping("/buyer/passport/connect/connect") public class ConnectBuyerWebController { @Autowired private ConnectService connectService; @Autowired
private MemberService memberService;
11
2023-12-24 19:45:18+00:00
24k
huidongyin/kafka-2.7.2
clients/src/main/java/org/apache/kafka/common/security/scram/internals/ScramSaslServer.java
[ { "identifier": "AuthenticationException", "path": "clients/src/main/java/org/apache/kafka/common/errors/AuthenticationException.java", "snippet": "public class AuthenticationException extends ApiException {\n\n private static final long serialVersionUID = 1L;\n\n public AuthenticationException(St...
import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.Set; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; import org.apache.kafka.common.errors.AuthenticationException; import org.apache.kafka.common.errors.IllegalSaslStateException; import org.apache.kafka.common.errors.SaslAuthenticationException; import org.apache.kafka.common.security.authenticator.SaslInternalConfigs; import org.apache.kafka.common.security.scram.ScramCredential; import org.apache.kafka.common.security.scram.ScramCredentialCallback; import org.apache.kafka.common.security.scram.ScramLoginModule; import org.apache.kafka.common.security.scram.internals.ScramMessages.ClientFinalMessage; import org.apache.kafka.common.security.scram.internals.ScramMessages.ClientFirstMessage; import org.apache.kafka.common.security.scram.internals.ScramMessages.ServerFinalMessage; import org.apache.kafka.common.security.scram.internals.ScramMessages.ServerFirstMessage; import org.apache.kafka.common.security.token.delegation.internals.DelegationTokenCredentialCallback; import org.apache.kafka.common.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
16,591
/* * 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.common.security.scram.internals; /** * SaslServer implementation for SASL/SCRAM. This server is configured with a callback * handler for integration with a credential manager. Kafka brokers provide callbacks * based on a Zookeeper-based password store. * * @see <a href="https://tools.ietf.org/html/rfc5802">RFC 5802</a> */ public class ScramSaslServer implements SaslServer { private static final Logger log = LoggerFactory.getLogger(ScramSaslServer.class); private static final Set<String> SUPPORTED_EXTENSIONS = Utils.mkSet(ScramLoginModule.TOKEN_AUTH_CONFIG); enum State { RECEIVE_CLIENT_FIRST_MESSAGE, RECEIVE_CLIENT_FINAL_MESSAGE, COMPLETE, FAILED } private final ScramMechanism mechanism; private final ScramFormatter formatter; private final CallbackHandler callbackHandler; private State state; private String username; private ClientFirstMessage clientFirstMessage; private ServerFirstMessage serverFirstMessage; private ScramExtensions scramExtensions; private ScramCredential scramCredential; private String authorizationId; private Long tokenExpiryTimestamp; public ScramSaslServer(ScramMechanism mechanism, Map<String, ?> props, CallbackHandler callbackHandler) throws NoSuchAlgorithmException { this.mechanism = mechanism; this.formatter = new ScramFormatter(mechanism); this.callbackHandler = callbackHandler; setState(State.RECEIVE_CLIENT_FIRST_MESSAGE); } /** * @throws SaslAuthenticationException if the requested authorization id is not the same as username. * <p> * <b>Note:</b> This method may throw {@link SaslAuthenticationException} to provide custom error messages * to clients. But care should be taken to avoid including any information in the exception message that * should not be leaked to unauthenticated clients. It may be safer to throw {@link SaslException} in * most cases so that a standard error message is returned to clients. * </p> */ @Override public byte[] evaluateResponse(byte[] response) throws SaslException, SaslAuthenticationException { try { switch (state) { case RECEIVE_CLIENT_FIRST_MESSAGE: this.clientFirstMessage = new ClientFirstMessage(response); this.scramExtensions = clientFirstMessage.extensions(); if (!SUPPORTED_EXTENSIONS.containsAll(scramExtensions.map().keySet())) { log.debug("Unsupported extensions will be ignored, supported {}, provided {}", SUPPORTED_EXTENSIONS, scramExtensions.map().keySet()); } String serverNonce = formatter.secureRandomString(); try { String saslName = clientFirstMessage.saslName(); this.username = ScramFormatter.username(saslName); NameCallback nameCallback = new NameCallback("username", username); ScramCredentialCallback credentialCallback; if (scramExtensions.tokenAuthenticated()) { DelegationTokenCredentialCallback tokenCallback = new DelegationTokenCredentialCallback(); credentialCallback = tokenCallback; callbackHandler.handle(new Callback[]{nameCallback, tokenCallback}); if (tokenCallback.tokenOwner() == null) throw new SaslException("Token Authentication failed: Invalid tokenId : " + username); this.authorizationId = tokenCallback.tokenOwner(); this.tokenExpiryTimestamp = tokenCallback.tokenExpiryTimestamp(); } else { credentialCallback = new ScramCredentialCallback(); callbackHandler.handle(new Callback[]{nameCallback, credentialCallback}); this.authorizationId = username; this.tokenExpiryTimestamp = null; } this.scramCredential = credentialCallback.scramCredential(); if (scramCredential == null) throw new SaslException("Authentication failed: Invalid user credentials"); String authorizationIdFromClient = clientFirstMessage.authorizationId(); if (!authorizationIdFromClient.isEmpty() && !authorizationIdFromClient.equals(username)) throw new SaslAuthenticationException("Authentication failed: Client requested an authorization id that is different from username"); if (scramCredential.iterations() < mechanism.minIterations()) throw new SaslException("Iterations " + scramCredential.iterations() + " is less than the minimum " + mechanism.minIterations() + " for " + mechanism); this.serverFirstMessage = new ServerFirstMessage(clientFirstMessage.nonce(), serverNonce, scramCredential.salt(), scramCredential.iterations()); setState(State.RECEIVE_CLIENT_FINAL_MESSAGE); return serverFirstMessage.toBytes(); } catch (SaslException | AuthenticationException e) { throw e; } catch (Throwable e) { throw new SaslException("Authentication failed: Credentials could not be obtained", e); } case RECEIVE_CLIENT_FINAL_MESSAGE: try {
/* * 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.common.security.scram.internals; /** * SaslServer implementation for SASL/SCRAM. This server is configured with a callback * handler for integration with a credential manager. Kafka brokers provide callbacks * based on a Zookeeper-based password store. * * @see <a href="https://tools.ietf.org/html/rfc5802">RFC 5802</a> */ public class ScramSaslServer implements SaslServer { private static final Logger log = LoggerFactory.getLogger(ScramSaslServer.class); private static final Set<String> SUPPORTED_EXTENSIONS = Utils.mkSet(ScramLoginModule.TOKEN_AUTH_CONFIG); enum State { RECEIVE_CLIENT_FIRST_MESSAGE, RECEIVE_CLIENT_FINAL_MESSAGE, COMPLETE, FAILED } private final ScramMechanism mechanism; private final ScramFormatter formatter; private final CallbackHandler callbackHandler; private State state; private String username; private ClientFirstMessage clientFirstMessage; private ServerFirstMessage serverFirstMessage; private ScramExtensions scramExtensions; private ScramCredential scramCredential; private String authorizationId; private Long tokenExpiryTimestamp; public ScramSaslServer(ScramMechanism mechanism, Map<String, ?> props, CallbackHandler callbackHandler) throws NoSuchAlgorithmException { this.mechanism = mechanism; this.formatter = new ScramFormatter(mechanism); this.callbackHandler = callbackHandler; setState(State.RECEIVE_CLIENT_FIRST_MESSAGE); } /** * @throws SaslAuthenticationException if the requested authorization id is not the same as username. * <p> * <b>Note:</b> This method may throw {@link SaslAuthenticationException} to provide custom error messages * to clients. But care should be taken to avoid including any information in the exception message that * should not be leaked to unauthenticated clients. It may be safer to throw {@link SaslException} in * most cases so that a standard error message is returned to clients. * </p> */ @Override public byte[] evaluateResponse(byte[] response) throws SaslException, SaslAuthenticationException { try { switch (state) { case RECEIVE_CLIENT_FIRST_MESSAGE: this.clientFirstMessage = new ClientFirstMessage(response); this.scramExtensions = clientFirstMessage.extensions(); if (!SUPPORTED_EXTENSIONS.containsAll(scramExtensions.map().keySet())) { log.debug("Unsupported extensions will be ignored, supported {}, provided {}", SUPPORTED_EXTENSIONS, scramExtensions.map().keySet()); } String serverNonce = formatter.secureRandomString(); try { String saslName = clientFirstMessage.saslName(); this.username = ScramFormatter.username(saslName); NameCallback nameCallback = new NameCallback("username", username); ScramCredentialCallback credentialCallback; if (scramExtensions.tokenAuthenticated()) { DelegationTokenCredentialCallback tokenCallback = new DelegationTokenCredentialCallback(); credentialCallback = tokenCallback; callbackHandler.handle(new Callback[]{nameCallback, tokenCallback}); if (tokenCallback.tokenOwner() == null) throw new SaslException("Token Authentication failed: Invalid tokenId : " + username); this.authorizationId = tokenCallback.tokenOwner(); this.tokenExpiryTimestamp = tokenCallback.tokenExpiryTimestamp(); } else { credentialCallback = new ScramCredentialCallback(); callbackHandler.handle(new Callback[]{nameCallback, credentialCallback}); this.authorizationId = username; this.tokenExpiryTimestamp = null; } this.scramCredential = credentialCallback.scramCredential(); if (scramCredential == null) throw new SaslException("Authentication failed: Invalid user credentials"); String authorizationIdFromClient = clientFirstMessage.authorizationId(); if (!authorizationIdFromClient.isEmpty() && !authorizationIdFromClient.equals(username)) throw new SaslAuthenticationException("Authentication failed: Client requested an authorization id that is different from username"); if (scramCredential.iterations() < mechanism.minIterations()) throw new SaslException("Iterations " + scramCredential.iterations() + " is less than the minimum " + mechanism.minIterations() + " for " + mechanism); this.serverFirstMessage = new ServerFirstMessage(clientFirstMessage.nonce(), serverNonce, scramCredential.salt(), scramCredential.iterations()); setState(State.RECEIVE_CLIENT_FINAL_MESSAGE); return serverFirstMessage.toBytes(); } catch (SaslException | AuthenticationException e) { throw e; } catch (Throwable e) { throw new SaslException("Authentication failed: Credentials could not be obtained", e); } case RECEIVE_CLIENT_FINAL_MESSAGE: try {
ClientFinalMessage clientFinalMessage = new ClientFinalMessage(response);
7
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,838
}); }); reduceVolume.setOnClickListener(v -> { if (currentVolume <= 4) { return; } currentVolume -= 4; mClingPlayControl.setVolume(currentVolume, new ControlCallback() { @Override public void success(IResponse response) { getVolume(); } @Override public void fail(IResponse response) { } }); }); findViewById(R.id.img_next).setOnClickListener(v -> { ToastMgr.shortCenter(getContext(), "暂不支持此功能"); }); findViewById(R.id.img_previous).setOnClickListener(v -> { ToastMgr.shortCenter(getContext(), "嘿嘿,我是个假按钮~"); }); } private void next() { } @Subscribe(threadMode = ThreadMode.MAIN) public void onDlan(DlanPlayEvent event) { initData(event.getUrl(), event.getTitle(), event.getHeaders()); } private Context getContext() { return this; } private void getVolume() { mClingPlayControl.getVolume(new ControlReceiveCallback() { @Override public void receive(IResponse response) { Object responseResponse = response.getResponse(); if (responseResponse instanceof ClingVolumeResponse) { ClingVolumeResponse resp = (ClingVolumeResponse) response; currentVolume = resp.getResponse(); } } @Override public void success(IResponse response) { } @Override public void fail(IResponse response) { } }); } private void initData(String playUrl, String playTitle, String headers) { tvVideoName.setText(playTitle); playStatus.setText("正在缓冲..."); playNew(playUrl, playTitle, headers); Log.d(TAG, "initData: playUrl==>" + playUrl + ", playTitle==>" + playTitle + ", headers==>" + headers); } private void initListener() { playBt.setOnClickListener(v -> { if (isPlaying) { pause(); playBt.setSelected(false); playStatus.setText("暂停播放..."); } else { continuePlay(); playBt.setSelected(true); playStatus.setText("正在播放"); } }); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int newProgress = (int) (hostLength * (progress * 0.01f)); String time = ModelUtil.toTimeString(newProgress); currTime.setText(time); } @Override public void onStartTrackingTouch(SeekBar seekBar) { isSeeking = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { int currentProgress = seekBar.getProgress(); // 转为毫秒 isSeeking = false; int progress = (int) (hostLength * 1000 * (currentProgress * 0.01f)); mClingPlayControl.seek(progress, new ControlCallback() { @Override public void success(IResponse response) { Log.e(TAG, "seek success"); } @Override public void fail(IResponse response) { Log.e(TAG, "seek fail"); } }); } }); // } private String getPlayUrl(String url, String headers) {
package org.mozilla.xiu.browser.dlan; public class MediaPlayActivity extends AppCompatActivity { private static final String TAG = "MediaPlayActivity"; /** * 连接设备状态: 播放状态 */ public static final int PLAY_ACTION = 0xa1; /** * 连接设备状态: 暂停状态 */ public static final int PAUSE_ACTION = 0xa2; /** * 连接设备状态: 停止状态 */ public static final int STOP_ACTION = 0xa3; /** * 连接设备状态: 转菊花状态 */ public static final int TRANSITIONING_ACTION = 0xa4; /** * 获取进度 */ public static final int EXTRA_POSITION = 0xa5; /** * 投放失败 */ public static final int ERROR_ACTION = 0xa6; /** * tv端播放完成 */ public static final int ACTION_PLAY_COMPLETE = 0xa7; public static final int ACTION_POSITION_CALLBACK = 0xa8; private TextView tvVideoName; private Context mContext; private Handler mHandler = new InnerHandler(); private Timer timer = null; private boolean isPlaying = false; private ClingPlayControl mClingPlayControl = new ClingPlayControl();//投屏控制器 private AppCompatSeekBar seekBar; private ImageView playBt; private TextView currTime; private TextView countTime; private long hostLength; private ImageView plusVolume; private ImageView reduceVolume; private int currentVolume; private TextView playStatus; private boolean isSeeking = false; private int pos = -1; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { BaseActivity.checkForceDarkMode(this); super.onCreate(savedInstanceState); mContext = this; initStatusBar(); setContentView(R.layout.activity_dlan_play_layout); initView(); initListener(); registerReceivers(); String playUrl = getIntent().getStringExtra(DLandataInter.Key.PLAYURL); String playTitle = getIntent().getStringExtra(DLandataInter.Key.PLAY_TITLE); String headers = getIntent().getStringExtra(DLandataInter.Key.HEADER); pos = getIntent().getIntExtra(DLandataInter.Key.PLAY_POS, -1); initData(playUrl, playTitle, headers); if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } } private void initStatusBar() { requestWindowFeature(Window.FEATURE_NO_TITLE); //去除状态栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } private void initView() { tvVideoName = findViewById(R.id.text_content_title); playBt = findViewById(R.id.img_play); findViewById(R.id.backup).setOnClickListener(v -> finish()); seekBar = findViewById(R.id.seek_bar_progress); currTime = findViewById(R.id.text_play_time); countTime = findViewById(R.id.text_play_max_time); playStatus = findViewById(R.id.play_status); plusVolume = findViewById(R.id.plus_volume); reduceVolume = findViewById(R.id.reduce_volume); getVolume(); plusVolume.setOnClickListener(v -> { if (currentVolume >= 96) { return; } currentVolume += 4; mClingPlayControl.setVolume(currentVolume, new ControlCallback() { @Override public void success(IResponse response) { getVolume(); } @Override public void fail(IResponse response) { getVolume(); } }); }); reduceVolume.setOnClickListener(v -> { if (currentVolume <= 4) { return; } currentVolume -= 4; mClingPlayControl.setVolume(currentVolume, new ControlCallback() { @Override public void success(IResponse response) { getVolume(); } @Override public void fail(IResponse response) { } }); }); findViewById(R.id.img_next).setOnClickListener(v -> { ToastMgr.shortCenter(getContext(), "暂不支持此功能"); }); findViewById(R.id.img_previous).setOnClickListener(v -> { ToastMgr.shortCenter(getContext(), "嘿嘿,我是个假按钮~"); }); } private void next() { } @Subscribe(threadMode = ThreadMode.MAIN) public void onDlan(DlanPlayEvent event) { initData(event.getUrl(), event.getTitle(), event.getHeaders()); } private Context getContext() { return this; } private void getVolume() { mClingPlayControl.getVolume(new ControlReceiveCallback() { @Override public void receive(IResponse response) { Object responseResponse = response.getResponse(); if (responseResponse instanceof ClingVolumeResponse) { ClingVolumeResponse resp = (ClingVolumeResponse) response; currentVolume = resp.getResponse(); } } @Override public void success(IResponse response) { } @Override public void fail(IResponse response) { } }); } private void initData(String playUrl, String playTitle, String headers) { tvVideoName.setText(playTitle); playStatus.setText("正在缓冲..."); playNew(playUrl, playTitle, headers); Log.d(TAG, "initData: playUrl==>" + playUrl + ", playTitle==>" + playTitle + ", headers==>" + headers); } private void initListener() { playBt.setOnClickListener(v -> { if (isPlaying) { pause(); playBt.setSelected(false); playStatus.setText("暂停播放..."); } else { continuePlay(); playBt.setSelected(true); playStatus.setText("正在播放"); } }); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int newProgress = (int) (hostLength * (progress * 0.01f)); String time = ModelUtil.toTimeString(newProgress); currTime.setText(time); } @Override public void onStartTrackingTouch(SeekBar seekBar) { isSeeking = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { int currentProgress = seekBar.getProgress(); // 转为毫秒 isSeeking = false; int progress = (int) (hostLength * 1000 * (currentProgress * 0.01f)); mClingPlayControl.seek(progress, new ControlCallback() { @Override public void success(IResponse response) { Log.e(TAG, "seek success"); } @Override public void fail(IResponse response) { Log.e(TAG, "seek fail"); } }); } }); // } private String getPlayUrl(String url, String headers) {
if (StringUtil.isEmpty(headers)) {
11
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": "public class Devotions extends JavaPlugin {\n @Getter private static Devotions instance;\n @Getter private DevotionManager devotionManager;\n @Getter private RitualManager ritualManager;\n ...
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;
15,412
package me.xidentified.devotions.listeners; public class RitualListener implements Listener { private final Devotions plugin; private final RitualManager ritualManager; private final ShrineManager shrineManager; private static RitualListener instance; public RitualListener(Devotions plugin, ShrineManager shrineManager) { this.plugin = plugin; this.ritualManager = RitualManager.getInstance(plugin); this.shrineManager = shrineManager; } public static void initialize(Devotions plugin, ShrineManager shrineManager) { if (instance == null) { instance = new RitualListener(plugin, shrineManager); } } public static RitualListener getInstance() { if (instance == null) { throw new IllegalStateException("RitualObjectiveListener has not been initialized. Call initialize() first."); } return instance; } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); Ritual ritual = ritualManager.getCurrentRitualForPlayer(player); // Return if player is not in a ritual if (ritual == null || ritual.isCompleted()) { return; } // Check if player moved, if in meditation. Reset timer if they moved. if (meditationManager().hasPlayerMovedSince(player) && meditationManager().isPlayerInMeditation(player)) { plugin.debugLog("Player " + player.getName() + " moved during meditation."); plugin.sendMessage(player, Messages.MEDIDATION_CANCELLED); meditationManager().startMeditation(player, ritual, getMeditationObjective(ritual)); } // Check and update gathering objectives for (RitualObjective objective : ritual.getObjectives()) { if (objective.getType() == RitualObjective.Type.GATHERING && !objective.isComplete()) { int itemCount = countItemsInInventory(player.getInventory(), Material.valueOf(objective.getTarget())); if (itemCount >= objective.getCount()) { objective.setCurrentCount(itemCount); } } } // Check if player has returned to shrine with all objectives completed regardless of the objective type if (isPlayerNearShrine(player) && allObjectivesCompleted(ritual)) { plugin.debugLog("Player " + player.getName() + " returned to the shrine with all objectives completed."); plugin.getRitualManager().completeRitual(player, ritual, meditationManager()); } } // Count items in inventory for 'gathering' objective private int countItemsInInventory(Inventory inventory, Material material) { int count = 0; for (ItemStack item : inventory.getContents()) { if (item != null && item.getType() == material) { count += item.getAmount(); } } return count; } private RitualObjective getMeditationObjective(Ritual ritual) { for (RitualObjective objective : ritual.getObjectives()) { if (objective.getType() == RitualObjective.Type.MEDITATION) { return objective; } } return null; } @EventHandler public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity().getKiller() != null) { Player player = event.getEntity().getKiller(); Ritual ritual = ritualManager.getCurrentRitualForPlayer(player); if (ritual == null || ritual.isCompleted()) { return; } List<RitualObjective> objectives = ritual.getObjectives(); for (RitualObjective objective : objectives) { if (objective.getType() == RitualObjective.Type.PURIFICATION && objective.getTarget().equals(event.getEntityType().name())) { objective.incrementCount(); if (objective.isComplete()) { plugin.debugLog("Objective complete for ritual " + ritual.getDisplayName()); plugin.sendMessage(player, Messages.RITUAL_RETURN_TO_RESUME); } } } } } // Check if player has returned to shrine to complete the ritual private boolean isPlayerNearShrine(Player player) { // Check if the player is within the shrine's radius Location shrineLocation = shrineManager.getShrineLocationForPlayer(player); if (shrineLocation != null && player.getWorld().equals(shrineLocation.getWorld())) { double distance = player.getLocation().distance(shrineLocation); return distance <= 5; } return false; } private boolean allObjectivesCompleted(Ritual ritual) { return ritual.getObjectives().stream().allMatch(RitualObjective::isComplete); }
package me.xidentified.devotions.listeners; public class RitualListener implements Listener { private final Devotions plugin; private final RitualManager ritualManager; private final ShrineManager shrineManager; private static RitualListener instance; public RitualListener(Devotions plugin, ShrineManager shrineManager) { this.plugin = plugin; this.ritualManager = RitualManager.getInstance(plugin); this.shrineManager = shrineManager; } public static void initialize(Devotions plugin, ShrineManager shrineManager) { if (instance == null) { instance = new RitualListener(plugin, shrineManager); } } public static RitualListener getInstance() { if (instance == null) { throw new IllegalStateException("RitualObjectiveListener has not been initialized. Call initialize() first."); } return instance; } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); Ritual ritual = ritualManager.getCurrentRitualForPlayer(player); // Return if player is not in a ritual if (ritual == null || ritual.isCompleted()) { return; } // Check if player moved, if in meditation. Reset timer if they moved. if (meditationManager().hasPlayerMovedSince(player) && meditationManager().isPlayerInMeditation(player)) { plugin.debugLog("Player " + player.getName() + " moved during meditation."); plugin.sendMessage(player, Messages.MEDIDATION_CANCELLED); meditationManager().startMeditation(player, ritual, getMeditationObjective(ritual)); } // Check and update gathering objectives for (RitualObjective objective : ritual.getObjectives()) { if (objective.getType() == RitualObjective.Type.GATHERING && !objective.isComplete()) { int itemCount = countItemsInInventory(player.getInventory(), Material.valueOf(objective.getTarget())); if (itemCount >= objective.getCount()) { objective.setCurrentCount(itemCount); } } } // Check if player has returned to shrine with all objectives completed regardless of the objective type if (isPlayerNearShrine(player) && allObjectivesCompleted(ritual)) { plugin.debugLog("Player " + player.getName() + " returned to the shrine with all objectives completed."); plugin.getRitualManager().completeRitual(player, ritual, meditationManager()); } } // Count items in inventory for 'gathering' objective private int countItemsInInventory(Inventory inventory, Material material) { int count = 0; for (ItemStack item : inventory.getContents()) { if (item != null && item.getType() == material) { count += item.getAmount(); } } return count; } private RitualObjective getMeditationObjective(Ritual ritual) { for (RitualObjective objective : ritual.getObjectives()) { if (objective.getType() == RitualObjective.Type.MEDITATION) { return objective; } } return null; } @EventHandler public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity().getKiller() != null) { Player player = event.getEntity().getKiller(); Ritual ritual = ritualManager.getCurrentRitualForPlayer(player); if (ritual == null || ritual.isCompleted()) { return; } List<RitualObjective> objectives = ritual.getObjectives(); for (RitualObjective objective : objectives) { if (objective.getType() == RitualObjective.Type.PURIFICATION && objective.getTarget().equals(event.getEntityType().name())) { objective.incrementCount(); if (objective.isComplete()) { plugin.debugLog("Objective complete for ritual " + ritual.getDisplayName()); plugin.sendMessage(player, Messages.RITUAL_RETURN_TO_RESUME); } } } } } // Check if player has returned to shrine to complete the ritual private boolean isPlayerNearShrine(Player player) { // Check if the player is within the shrine's radius Location shrineLocation = shrineManager.getShrineLocationForPlayer(player); if (shrineLocation != null && player.getWorld().equals(shrineLocation.getWorld())) { double distance = player.getLocation().distance(shrineLocation); return distance <= 5; } return false; } private boolean allObjectivesCompleted(Ritual ritual) { return ritual.getObjectives().stream().allMatch(RitualObjective::isComplete); }
private MeditationManager meditationManager(){
1
2023-11-10 07:03:24+00:00
24k
SplitfireUptown/datalinkx
flinkx/flinkx-hive/flinkx-hive-writer/src/main/java/com/dtstack/flinkx/hive/writer/HiveOutputFormat.java
[ { "identifier": "WriteRecordException", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/exception/WriteRecordException.java", "snippet": "public class WriteRecordException extends Exception {\n\n private int colIndex = -1;\n private Row row;\n\n public int getColIndex() {\n ...
import com.dtstack.flinkx.exception.WriteRecordException; import com.dtstack.flinkx.hdfs.writer.BaseHdfsOutputFormat; import com.dtstack.flinkx.hdfs.writer.HdfsOutputFormatBuilder; import com.dtstack.flinkx.hive.TableInfo; import com.dtstack.flinkx.hive.TimePartitionFormat; import com.dtstack.flinkx.hive.util.HiveDbUtil; import com.dtstack.flinkx.hive.util.HiveUtil; import com.dtstack.flinkx.hive.util.PathConverterUtil; import com.dtstack.flinkx.outputformat.BaseRichOutputFormat; import com.dtstack.flinkx.restore.FormatState; import com.dtstack.flinkx.util.ExceptionUtil; import com.dtstack.flinkx.util.GsonUtil; import com.google.gson.JsonSyntaxException; import org.apache.commons.collections.MapUtils; import org.apache.commons.math3.util.Pair; import org.apache.flink.types.Row; import org.apache.hadoop.conf.Configuration; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import static com.dtstack.flinkx.hive.HiveConfigKeys.KEY_SCHEMA; import static com.dtstack.flinkx.hive.HiveConfigKeys.KEY_TABLE;
18,499
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.hive.writer; /** * @author toutian */ public class HiveOutputFormat extends BaseRichOutputFormat { private static final String SP = "/"; /** * hdfs高可用配置 */ protected Map<String, Object> hadoopConfig; protected String fileType; /** * 写入模式 */ protected String writeMode; /** * 压缩方式 */ protected String compress; protected String defaultFs; protected String delimiter; protected String charsetName = "UTF-8"; protected Configuration conf; protected int rowGroupSize; protected long maxFileSize; /* ----------以上hdfs插件参数----------- */ protected Map<String, TableInfo> tableInfos; protected Map<String, String> distributeTableMapping; protected String partition; protected String partitionType; protected String partitionPath; protected String tbPath; protected long bufferSize; protected String jdbcUrl; protected String username; protected String password; protected String tableBasePath; protected boolean autoCreateTable; protected String schema; private transient HiveUtil hiveUtil; private transient TimePartitionFormat partitionFormat; private org.apache.flink.configuration.Configuration parameters; private int taskNumber; private int numTasks; private Map<String, TableInfo> tableCache; private Map<String, BaseHdfsOutputFormat> outputFormats; private Map<String, FormatState> formatStateMap = new HashMap<>(); @Override public void configure(org.apache.flink.configuration.Configuration parameters) { this.parameters = parameters; partitionFormat = TimePartitionFormat.getInstance(partitionType); tableCache = new HashMap<>(16); outputFormats = new HashMap<>(16); } @Override protected void openInternal(int taskNumber, int numTasks) throws IOException { this.taskNumber = taskNumber; this.numTasks = numTasks; if (null != formatState && null != formatState.getState()) { HiveFormatState hiveFormatState = (HiveFormatState)formatState.getState(); formatStateMap.putAll(hiveFormatState.getFormatStateMap()); } HiveDbUtil.ConnectionInfo connectionInfo = new HiveDbUtil.ConnectionInfo(); connectionInfo.setJdbcUrl(jdbcUrl); connectionInfo.setUsername(username); connectionInfo.setPassword(password); connectionInfo.setHiveConf(hadoopConfig); hiveUtil = new HiveUtil(connectionInfo); primaryCreateTable(); } @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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.hive.writer; /** * @author toutian */ public class HiveOutputFormat extends BaseRichOutputFormat { private static final String SP = "/"; /** * hdfs高可用配置 */ protected Map<String, Object> hadoopConfig; protected String fileType; /** * 写入模式 */ protected String writeMode; /** * 压缩方式 */ protected String compress; protected String defaultFs; protected String delimiter; protected String charsetName = "UTF-8"; protected Configuration conf; protected int rowGroupSize; protected long maxFileSize; /* ----------以上hdfs插件参数----------- */ protected Map<String, TableInfo> tableInfos; protected Map<String, String> distributeTableMapping; protected String partition; protected String partitionType; protected String partitionPath; protected String tbPath; protected long bufferSize; protected String jdbcUrl; protected String username; protected String password; protected String tableBasePath; protected boolean autoCreateTable; protected String schema; private transient HiveUtil hiveUtil; private transient TimePartitionFormat partitionFormat; private org.apache.flink.configuration.Configuration parameters; private int taskNumber; private int numTasks; private Map<String, TableInfo> tableCache; private Map<String, BaseHdfsOutputFormat> outputFormats; private Map<String, FormatState> formatStateMap = new HashMap<>(); @Override public void configure(org.apache.flink.configuration.Configuration parameters) { this.parameters = parameters; partitionFormat = TimePartitionFormat.getInstance(partitionType); tableCache = new HashMap<>(16); outputFormats = new HashMap<>(16); } @Override protected void openInternal(int taskNumber, int numTasks) throws IOException { this.taskNumber = taskNumber; this.numTasks = numTasks; if (null != formatState && null != formatState.getState()) { HiveFormatState hiveFormatState = (HiveFormatState)formatState.getState(); formatStateMap.putAll(hiveFormatState.getFormatStateMap()); } HiveDbUtil.ConnectionInfo connectionInfo = new HiveDbUtil.ConnectionInfo(); connectionInfo.setJdbcUrl(jdbcUrl); connectionInfo.setUsername(username); connectionInfo.setPassword(password); connectionInfo.setHiveConf(hadoopConfig); hiveUtil = new HiveUtil(connectionInfo); primaryCreateTable(); } @Override
protected void writeSingleRecordInternal(Row row) throws WriteRecordException {
0
2023-11-16 02:22:52+00:00
24k
bdmarius/jndarray-toolbox
src/main/java/internals/TensorLogicFunctions.java
[ { "identifier": "NumberUtils", "path": "src/main/java/utils/NumberUtils.java", "snippet": "public class NumberUtils {\n\n public static Map<JNumDataType, Map<JNumDataType, BiFunction<Number, Number, Number>>> ADD = loadAddFunctions();\n public static Map<JNumDataType, Map<JNumDataType, BiFunction<...
import utils.NumberUtils; import utils.TypeUtils; import java.util.function.Function;
19,507
package internals; public class TensorLogicFunctions { /** * Returns true if all elements are lower than the given value */ static boolean lower(Tensor tensor, Number value) { return all(tensor, (x ->
package internals; public class TensorLogicFunctions { /** * Returns true if all elements are lower than the given value */ static boolean lower(Tensor tensor, Number value) { return all(tensor, (x ->
NumberUtils.lower(tensor.getDataType(), x, TypeUtils.parseDataType(value.getClass()), value)));
0
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;
20,942
package com.uroria.betterflowers.menus; public final class FlowerCreationMenu extends BukkitPlayerInventory { private final LanguageManager languageManager; private final List<FlowerData> personalFlower; private final List<Boolean> isGroup; private final List<Boolean> randomizer; private final Player player; private final ItemStack active; private final ItemStack notActive; private final ItemStack wholeCategoryRan; private final ItemStack wholeCategory; private final BetterFlowers betterFlowers; public FlowerCreationMenu(Player player, BetterFlowers betterFlowers) { super(betterFlowers.getLanguageManager().getComponent("gui.flower.title"), 6); this.player = player; this.betterFlowers = betterFlowers; this.languageManager = betterFlowers.getLanguageManager(); this.personalFlower = new ArrayList<>(); this.randomizer = new ArrayList<>(); this.isGroup = new ArrayList<>(); this.active = new ItemBuilder(Material.LIME_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.no")) .build(); this.notActive = new ItemBuilder(Material.RED_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.group.no.no")) .build(); this.wholeCategoryRan = new ItemBuilder(Material.BLUE_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.yes")) .build(); this.wholeCategory = new ItemBuilder(Material.MAGENTA_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.no.yes")) .build(); } public void open() { this.closeActions.add(() -> { personalFlower.clear(); randomizer.clear(); isGroup.clear(); }); generateCategories(); openInventory(player); } private void generateFlowerOverlay() { //generates placeholder for (var index = 27; index < 54; index++) { if (index >= 36 && index <= 44) continue; this.setSlot(index, new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.placeholder")) .build(), this::cancelClick); } //generates the display for the randomizer for (var index = 0; index < 9; index++) { if (index >= randomizer.size() || index >= isGroup.size()) break; if (isGroup.get(index) && randomizer.get(index)) setSlot(45 + index, wholeCategoryRan, this::cancelClick); if (isGroup.get(index) && !randomizer.get(index)) setSlot(45 + index, wholeCategory, this::cancelClick); if (!isGroup.get(index) && randomizer.get(index)) setSlot((45 + index), active, this::cancelClick); if (!isGroup.get(index) && !randomizer.get(index)) setSlot((45 + index), notActive, this::cancelClick); } //generates the chosen list of flowers to display the current flower list for (var index = 0; index < personalFlower.size(); index++) { final var singleFlower = personalFlower.get(index); setSlot((36 + index), new ItemBuilder(singleFlower.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%",singleFlower.getName() + " ID " + index)) .build(), this::cancelClick); } setSlot(29, new ItemBuilder(Material.ECHO_SHARD) .setName(languageManager.getComponent("gui.flower.item.display.create")) .build(), this::onCreateClick); setSlot(30, new ItemBuilder(Material.STRUCTURE_VOID) .setName(languageManager.getComponent("gui.flower.item.display.back")) .build(), this::onBackClick); setSlot(32, new ItemBuilder(Material.BARRIER) .setName(languageManager.getComponent("gui.flower.item.display.delete")) .build(), this::onDeleteClick); setSlot(33, new ItemBuilder(Material.REDSTONE) .setName(languageManager.getComponent("gui.flower.item.display.remove")) .build(), this::onRemoveClick); } private void generateCategories() { clearSlots(); generateFlowerOverlay(); final var flowers = List.copyOf(Arrays.stream(FlowerCollection.values()).toList()); for (int index = 0; index < 28; index++) { if (index > flowers.size()) break; if (index == flowers.size()) { this.setSlot(index, new ItemBuilder(Material.CANDLE) .setName(languageManager.getComponent("gui.flower.item.display.candle")).build(), this::createCandleCategories); break; } final var currentFlowers = flowers.get(index).getFlowerGroup(); setSlot(index, new ItemBuilder(currentFlowers.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%", currentFlowers.getDisplayName())) .setLore(languageManager.getComponents("gui.flower.item.lore.flowers")).build(), inventoryClickEvent -> onCategoryClick(inventoryClickEvent, currentFlowers) ); } } private void createCandleCategories(InventoryClickEvent inventoryClickEvent) { inventoryClickEvent.setCancelled(true); clearSlots(); generateFlowerOverlay();
package com.uroria.betterflowers.menus; public final class FlowerCreationMenu extends BukkitPlayerInventory { private final LanguageManager languageManager; private final List<FlowerData> personalFlower; private final List<Boolean> isGroup; private final List<Boolean> randomizer; private final Player player; private final ItemStack active; private final ItemStack notActive; private final ItemStack wholeCategoryRan; private final ItemStack wholeCategory; private final BetterFlowers betterFlowers; public FlowerCreationMenu(Player player, BetterFlowers betterFlowers) { super(betterFlowers.getLanguageManager().getComponent("gui.flower.title"), 6); this.player = player; this.betterFlowers = betterFlowers; this.languageManager = betterFlowers.getLanguageManager(); this.personalFlower = new ArrayList<>(); this.randomizer = new ArrayList<>(); this.isGroup = new ArrayList<>(); this.active = new ItemBuilder(Material.LIME_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.no")) .build(); this.notActive = new ItemBuilder(Material.RED_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.group.no.no")) .build(); this.wholeCategoryRan = new ItemBuilder(Material.BLUE_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.yes")) .build(); this.wholeCategory = new ItemBuilder(Material.MAGENTA_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.no.yes")) .build(); } public void open() { this.closeActions.add(() -> { personalFlower.clear(); randomizer.clear(); isGroup.clear(); }); generateCategories(); openInventory(player); } private void generateFlowerOverlay() { //generates placeholder for (var index = 27; index < 54; index++) { if (index >= 36 && index <= 44) continue; this.setSlot(index, new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.placeholder")) .build(), this::cancelClick); } //generates the display for the randomizer for (var index = 0; index < 9; index++) { if (index >= randomizer.size() || index >= isGroup.size()) break; if (isGroup.get(index) && randomizer.get(index)) setSlot(45 + index, wholeCategoryRan, this::cancelClick); if (isGroup.get(index) && !randomizer.get(index)) setSlot(45 + index, wholeCategory, this::cancelClick); if (!isGroup.get(index) && randomizer.get(index)) setSlot((45 + index), active, this::cancelClick); if (!isGroup.get(index) && !randomizer.get(index)) setSlot((45 + index), notActive, this::cancelClick); } //generates the chosen list of flowers to display the current flower list for (var index = 0; index < personalFlower.size(); index++) { final var singleFlower = personalFlower.get(index); setSlot((36 + index), new ItemBuilder(singleFlower.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%",singleFlower.getName() + " ID " + index)) .build(), this::cancelClick); } setSlot(29, new ItemBuilder(Material.ECHO_SHARD) .setName(languageManager.getComponent("gui.flower.item.display.create")) .build(), this::onCreateClick); setSlot(30, new ItemBuilder(Material.STRUCTURE_VOID) .setName(languageManager.getComponent("gui.flower.item.display.back")) .build(), this::onBackClick); setSlot(32, new ItemBuilder(Material.BARRIER) .setName(languageManager.getComponent("gui.flower.item.display.delete")) .build(), this::onDeleteClick); setSlot(33, new ItemBuilder(Material.REDSTONE) .setName(languageManager.getComponent("gui.flower.item.display.remove")) .build(), this::onRemoveClick); } private void generateCategories() { clearSlots(); generateFlowerOverlay(); final var flowers = List.copyOf(Arrays.stream(FlowerCollection.values()).toList()); for (int index = 0; index < 28; index++) { if (index > flowers.size()) break; if (index == flowers.size()) { this.setSlot(index, new ItemBuilder(Material.CANDLE) .setName(languageManager.getComponent("gui.flower.item.display.candle")).build(), this::createCandleCategories); break; } final var currentFlowers = flowers.get(index).getFlowerGroup(); setSlot(index, new ItemBuilder(currentFlowers.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%", currentFlowers.getDisplayName())) .setLore(languageManager.getComponents("gui.flower.item.lore.flowers")).build(), inventoryClickEvent -> onCategoryClick(inventoryClickEvent, currentFlowers) ); } } private void createCandleCategories(InventoryClickEvent inventoryClickEvent) { inventoryClickEvent.setCancelled(true); clearSlots(); generateFlowerOverlay();
final var candles = List.copyOf(Arrays.stream(CandleCollection.values()).toList());
5
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,080
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()
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)
26
2023-11-12 01:19:17+00:00
24k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/EntityPhysicsBlock.java
[ { "identifier": "EnumLogVerbosity", "path": "src/main/java/enviromine/core/EM_ConfigHandler.java", "snippet": "public enum EnumLogVerbosity\n{\n\tNONE(0),\n\tLOW(1),\n\tNORMAL(2),\n\tALL(3);\n\n\tprivate final int level;\n\n\tprivate EnumLogVerbosity(int level)\n\t{\n\t\tthis.level = level;\n\t}\n\n\tpu...
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.logging.log4j.Level; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; import enviromine.core.EM_ConfigHandler.EnumLogVerbosity; import enviromine.core.EM_Settings; import enviromine.core.EnviroMine; import enviromine.handlers.EM_PhysManager; import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraft.block.BlockFalling; import net.minecraft.block.BlockFlower; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityFallingBlock; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.World;
15,632
package enviromine; public class EntityPhysicsBlock extends EntityFallingBlock implements IEntityAdditionalSpawnData { public boolean isAnvil2 = true; public boolean isBreakingAnvil2; public int fallHurtMax2; public float fallHurtAmount2; public boolean isLandSlide = false; public boolean earthquake = false; public int fallTime = 0; public Block block; public int meta; public EntityPhysicsBlock(World world) { super(world); this.isAnvil2 = true; this.fallHurtMax2 = 40; this.fallHurtAmount2 = 2.0F; if(EM_Settings.entityFailsafe > 0 && !world.isRemote) { @SuppressWarnings("unchecked") List<EntityPhysicsBlock> entityList = this.worldObj.getEntitiesWithinAABB(EntityPhysicsBlock.class, this.boundingBox.expand(8F, 8F, 8F)); if(entityList.size() >= 1024) { if(EM_Settings.entityFailsafe == 1) { if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) { EnviroMine.logger.log(Level.WARN, "Entity fail safe activated! Canceling new entities!"); EnviroMine.logger.log(Level.WARN, "Location: " + this.posX + "," + this.posY + "," + this.posZ); EnviroMine.logger.log(Level.WARN, "No.: " + entityList.size()); }
package enviromine; public class EntityPhysicsBlock extends EntityFallingBlock implements IEntityAdditionalSpawnData { public boolean isAnvil2 = true; public boolean isBreakingAnvil2; public int fallHurtMax2; public float fallHurtAmount2; public boolean isLandSlide = false; public boolean earthquake = false; public int fallTime = 0; public Block block; public int meta; public EntityPhysicsBlock(World world) { super(world); this.isAnvil2 = true; this.fallHurtMax2 = 40; this.fallHurtAmount2 = 2.0F; if(EM_Settings.entityFailsafe > 0 && !world.isRemote) { @SuppressWarnings("unchecked") List<EntityPhysicsBlock> entityList = this.worldObj.getEntitiesWithinAABB(EntityPhysicsBlock.class, this.boundingBox.expand(8F, 8F, 8F)); if(entityList.size() >= 1024) { if(EM_Settings.entityFailsafe == 1) { if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) { EnviroMine.logger.log(Level.WARN, "Entity fail safe activated! Canceling new entities!"); EnviroMine.logger.log(Level.WARN, "Location: " + this.posX + "," + this.posY + "," + this.posZ); EnviroMine.logger.log(Level.WARN, "No.: " + entityList.size()); }
EM_PhysManager.physSchedule.clear();
3
2023-11-16 18:15:29+00:00
24k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/render/GenericGunRenderer.java
[ { "identifier": "ClientProxy", "path": "src/main/java/sheridan/gunscraft/ClientProxy.java", "snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa...
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.AbstractClientPlayerEntity; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.PlayerRenderer; import net.minecraft.client.renderer.model.ItemCameraTransforms; import net.minecraft.client.renderer.model.ModelRenderer; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.vector.Matrix4f; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.lwjgl.opengl.GL11; import sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationData; import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationHandler; import sheridan.gunscraft.capability.CapabilityHandler; import sheridan.gunscraft.events.PlayerEvents; import sheridan.gunscraft.events.RenderEvents; import sheridan.gunscraft.items.attachments.util.GunAttachmentSlot; import sheridan.gunscraft.items.attachments.util.GunRenderContext; import sheridan.gunscraft.items.attachments.util.NBTAttachmentsMap; import sheridan.gunscraft.items.guns.IGenericGun; import sheridan.gunscraft.model.IGunModel; import sheridan.gunscraft.render.bulletShell.BulletShellRenderer; import sheridan.gunscraft.render.fx.muzzleFlash.CommonMuzzleFlash; import sheridan.gunscraft.render.fx.muzzleFlash.MuzzleFlash; import sheridan.gunscraft.render.fx.muzzleFlash.MuzzleFlashTrans; import static sheridan.gunscraft.ClientProxy.TICK_LEN; import static sheridan.gunscraft.ClientProxy.bulletSpread;
20,311
package sheridan.gunscraft.render; @OnlyIn(Dist.CLIENT) public class GenericGunRenderer implements IGunRender{ private static final Matrix4f DEFAULT_FIRST_PERSON_FOV_MATRIX; public static final float DEFAULT_FIRST_PERSON_FOV = 56.75f; public PlayerEntity player; static { DEFAULT_FIRST_PERSON_FOV_MATRIX = new Matrix4f(); DEFAULT_FIRST_PERSON_FOV_MATRIX.setIdentity(); Minecraft minecraft = Minecraft.getInstance(); DEFAULT_FIRST_PERSON_FOV_MATRIX.mul(Matrix4f.perspective(DEFAULT_FIRST_PERSON_FOV, (float) minecraft.getMainWindow().getFramebufferWidth() / (float) minecraft.getMainWindow().getFramebufferHeight(), 0.05F, (float) minecraft.gameSettings.renderDistanceChunks * 64F)); } public void justRenderModel(ItemStack itemStackIn, ItemCameraTransforms.TransformType transformTypeIn, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int combinedLightIn, int combinedOverlayIn, IGenericGun gun, IGunModel model, TransformData transformData) { if (model != null) { if (transformData != null) { matrixStackIn.push(); transformData.applyTransform(transformTypeIn, matrixStackIn, false, 0); int fireMode = gun.getFireMode(itemStackIn); int ammoLeft = gun.getAmmoLeft(itemStackIn); long fireDis = (gun.getShootDelay() - 1) * TICK_LEN; GunRenderContext context = NBTAttachmentsMap.renderAttachments(matrixStackIn, transformTypeIn, combinedLightIn, combinedOverlayIn, ammoLeft, 0, true, fireMode,itemStackIn, gun); model.render(matrixStackIn, bufferIn.getBuffer(RenderType.getEntityCutoutNoCull(gun.getTexture(gun.getCurrentTextureIndex(itemStackIn)))), transformTypeIn, combinedLightIn, combinedOverlayIn, 1, 1, 1, 1, ammoLeft,0, false, fireMode,context,fireDis); matrixStackIn.pop(); } } } private long tempLastShootMain; private long tempLastShootOff; int delay; Matrix4f temp; public void renderWithLivingEntity(LivingEntity entityIn, MatrixStack stackIn, ItemStack itemStackIn, ItemCameraTransforms.TransformType type, IRenderTypeBuffer bufferIn, IGenericGun gun, int combinedLightIn, int combinedOverlayIn, boolean leftHand, IGunModel model, TransformData transformData) { if (!Gunscraft.proxy.shouldRenderCustom(itemStackIn, gun, entityIn, !leftHand)) { return; } int ammoLeft = gun.getAmmoLeft(itemStackIn); if (entityIn == null) { justRenderModel(itemStackIn,type,stackIn,bufferIn,combinedLightIn,combinedOverlayIn,gun,model,transformData); return; } delay ++; if (model != null) { if (transformData != null) { stackIn.push();
package sheridan.gunscraft.render; @OnlyIn(Dist.CLIENT) public class GenericGunRenderer implements IGunRender{ private static final Matrix4f DEFAULT_FIRST_PERSON_FOV_MATRIX; public static final float DEFAULT_FIRST_PERSON_FOV = 56.75f; public PlayerEntity player; static { DEFAULT_FIRST_PERSON_FOV_MATRIX = new Matrix4f(); DEFAULT_FIRST_PERSON_FOV_MATRIX.setIdentity(); Minecraft minecraft = Minecraft.getInstance(); DEFAULT_FIRST_PERSON_FOV_MATRIX.mul(Matrix4f.perspective(DEFAULT_FIRST_PERSON_FOV, (float) minecraft.getMainWindow().getFramebufferWidth() / (float) minecraft.getMainWindow().getFramebufferHeight(), 0.05F, (float) minecraft.gameSettings.renderDistanceChunks * 64F)); } public void justRenderModel(ItemStack itemStackIn, ItemCameraTransforms.TransformType transformTypeIn, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int combinedLightIn, int combinedOverlayIn, IGenericGun gun, IGunModel model, TransformData transformData) { if (model != null) { if (transformData != null) { matrixStackIn.push(); transformData.applyTransform(transformTypeIn, matrixStackIn, false, 0); int fireMode = gun.getFireMode(itemStackIn); int ammoLeft = gun.getAmmoLeft(itemStackIn); long fireDis = (gun.getShootDelay() - 1) * TICK_LEN; GunRenderContext context = NBTAttachmentsMap.renderAttachments(matrixStackIn, transformTypeIn, combinedLightIn, combinedOverlayIn, ammoLeft, 0, true, fireMode,itemStackIn, gun); model.render(matrixStackIn, bufferIn.getBuffer(RenderType.getEntityCutoutNoCull(gun.getTexture(gun.getCurrentTextureIndex(itemStackIn)))), transformTypeIn, combinedLightIn, combinedOverlayIn, 1, 1, 1, 1, ammoLeft,0, false, fireMode,context,fireDis); matrixStackIn.pop(); } } } private long tempLastShootMain; private long tempLastShootOff; int delay; Matrix4f temp; public void renderWithLivingEntity(LivingEntity entityIn, MatrixStack stackIn, ItemStack itemStackIn, ItemCameraTransforms.TransformType type, IRenderTypeBuffer bufferIn, IGenericGun gun, int combinedLightIn, int combinedOverlayIn, boolean leftHand, IGunModel model, TransformData transformData) { if (!Gunscraft.proxy.shouldRenderCustom(itemStackIn, gun, entityIn, !leftHand)) { return; } int ammoLeft = gun.getAmmoLeft(itemStackIn); if (entityIn == null) { justRenderModel(itemStackIn,type,stackIn,bufferIn,combinedLightIn,combinedOverlayIn,gun,model,transformData); return; } delay ++; if (model != null) { if (transformData != null) { stackIn.push();
ClientProxy.mainHandStatus.handleAiming(RenderEvents.delta);
0
2023-11-14 14:00:55+00:00
24k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/service/impl/UserServiceImpl.java
[ { "identifier": "FileProperties", "path": "dimple-common/src/main/java/com/dimple/config/FileProperties.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"file\")\npublic class FileProperties {\n\n /**\n * 文件大小限制\n */\n private Long maxSize;\n\n /**\n * 头像...
import com.dimple.config.FileProperties; import com.dimple.exception.EntityExistException; import com.dimple.exception.EntityNotFoundException; import com.dimple.modules.system.domain.User; import com.dimple.modules.system.repository.UserRepository; import com.dimple.modules.system.service.UserService; import com.dimple.modules.system.service.dto.JobSmallDto; import com.dimple.modules.system.service.dto.RoleSmallDTO; import com.dimple.modules.system.service.dto.UserDTO; import com.dimple.modules.system.service.dto.UserQueryCriteria; import com.dimple.modules.system.service.mapstruct.UserMapper; import com.dimple.utils.FileUtil; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.RedisUtils; import com.dimple.utils.SecurityUtils; import com.dimple.utils.StringUtils; import com.dimple.utils.ValidationUtil; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors;
14,684
package com.dimple.modules.system.service.impl; /** * @className: UserServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "user") public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final UserMapper userMapper; private final FileProperties properties; private final RedisUtils redisUtils; @Override public Object queryAll(UserQueryCriteria criteria, Pageable pageable) { Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable); return PageUtil.toPage(page.map(userMapper::toDto)); } @Override public List<UserDTO> queryAll(UserQueryCriteria criteria) { List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); return userMapper.toDto(users); } @Override @Cacheable(key = "'id:' + #p0") @Transactional(rollbackFor = Exception.class) public UserDTO findById(long id) { User user = userRepository.findById(id).orElseGet(User::new); ValidationUtil.isNull(user.getId(), "User", "id", id); return userMapper.toDto(user); } @Override @Transactional(rollbackFor = Exception.class) public void create(User resources) { if (userRepository.findByUsername(resources.getUsername()) != null) { throw new EntityExistException(User.class, "username", resources.getUsername()); } if (userRepository.findByEmail(resources.getEmail()) != null) { throw new EntityExistException(User.class, "email", resources.getEmail()); } userRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(User resources) { User user = userRepository.findById(resources.getId()).orElseGet(User::new); ValidationUtil.isNull(user.getId(), "User", "id", resources.getId()); User user1 = userRepository.findByUsername(resources.getUsername()); User user2 = userRepository.findByEmail(resources.getEmail()); if (user1 != null && !user.getId().equals(user1.getId())) { throw new EntityExistException(User.class, "username", resources.getUsername()); } if (user2 != null && !user.getId().equals(user2.getId())) { throw new EntityExistException(User.class, "email", resources.getEmail()); } // 如果用户的角色改变 if (!resources.getRoles().equals(user.getRoles())) { redisUtils.del("data::user:" + resources.getId()); redisUtils.del("menu::user:" + resources.getId()); redisUtils.del("role::auth:" + resources.getId()); } // 如果用户名称修改 if (!resources.getUsername().equals(user.getUsername())) { redisUtils.del("user::username:" + user.getUsername()); } user.setUsername(resources.getUsername()); user.setEmail(resources.getEmail()); user.setEnabled(resources.getEnabled()); user.setRoles(resources.getRoles()); user.setPhone(resources.getPhone()); user.setNickName(resources.getNickName()); user.setGender(resources.getGender()); userRepository.save(user); // 清除缓存 delCaches(user.getId(), user.getUsername()); } @Override @Transactional(rollbackFor = Exception.class) public void updateCenter(User resources) { User user = userRepository.findById(resources.getId()).orElseGet(User::new); user.setNickName(resources.getNickName()); user.setPhone(resources.getPhone()); user.setGender(resources.getGender()); userRepository.save(user); // 清理缓存 delCaches(user.getId(), user.getUsername()); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Long> ids) { for (Long id : ids) { // 清理缓存 UserDTO user = findById(id); delCaches(user.getId(), user.getUsername()); } userRepository.deleteAllByIdIn(ids); } @Override @Cacheable(key = "'username:' + #p0") public UserDTO findByName(String userName) { User user = userRepository.findByUsername(userName); if (user == null) { throw new EntityNotFoundException(User.class, "name", userName); } else { return userMapper.toDto(user); } } @Override @Transactional(rollbackFor = Exception.class) public void updatePass(String username, String pass) { userRepository.updatePass(username, pass, new Date()); redisUtils.del("user::username:" + username); } @Override @Transactional(rollbackFor = Exception.class) public Map<String, String> updateAvatar(MultipartFile multipartFile) { User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername()); String oldPath = user.getAvatarPath();
package com.dimple.modules.system.service.impl; /** * @className: UserServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "user") public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final UserMapper userMapper; private final FileProperties properties; private final RedisUtils redisUtils; @Override public Object queryAll(UserQueryCriteria criteria, Pageable pageable) { Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable); return PageUtil.toPage(page.map(userMapper::toDto)); } @Override public List<UserDTO> queryAll(UserQueryCriteria criteria) { List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); return userMapper.toDto(users); } @Override @Cacheable(key = "'id:' + #p0") @Transactional(rollbackFor = Exception.class) public UserDTO findById(long id) { User user = userRepository.findById(id).orElseGet(User::new); ValidationUtil.isNull(user.getId(), "User", "id", id); return userMapper.toDto(user); } @Override @Transactional(rollbackFor = Exception.class) public void create(User resources) { if (userRepository.findByUsername(resources.getUsername()) != null) { throw new EntityExistException(User.class, "username", resources.getUsername()); } if (userRepository.findByEmail(resources.getEmail()) != null) { throw new EntityExistException(User.class, "email", resources.getEmail()); } userRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(User resources) { User user = userRepository.findById(resources.getId()).orElseGet(User::new); ValidationUtil.isNull(user.getId(), "User", "id", resources.getId()); User user1 = userRepository.findByUsername(resources.getUsername()); User user2 = userRepository.findByEmail(resources.getEmail()); if (user1 != null && !user.getId().equals(user1.getId())) { throw new EntityExistException(User.class, "username", resources.getUsername()); } if (user2 != null && !user.getId().equals(user2.getId())) { throw new EntityExistException(User.class, "email", resources.getEmail()); } // 如果用户的角色改变 if (!resources.getRoles().equals(user.getRoles())) { redisUtils.del("data::user:" + resources.getId()); redisUtils.del("menu::user:" + resources.getId()); redisUtils.del("role::auth:" + resources.getId()); } // 如果用户名称修改 if (!resources.getUsername().equals(user.getUsername())) { redisUtils.del("user::username:" + user.getUsername()); } user.setUsername(resources.getUsername()); user.setEmail(resources.getEmail()); user.setEnabled(resources.getEnabled()); user.setRoles(resources.getRoles()); user.setPhone(resources.getPhone()); user.setNickName(resources.getNickName()); user.setGender(resources.getGender()); userRepository.save(user); // 清除缓存 delCaches(user.getId(), user.getUsername()); } @Override @Transactional(rollbackFor = Exception.class) public void updateCenter(User resources) { User user = userRepository.findById(resources.getId()).orElseGet(User::new); user.setNickName(resources.getNickName()); user.setPhone(resources.getPhone()); user.setGender(resources.getGender()); userRepository.save(user); // 清理缓存 delCaches(user.getId(), user.getUsername()); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Long> ids) { for (Long id : ids) { // 清理缓存 UserDTO user = findById(id); delCaches(user.getId(), user.getUsername()); } userRepository.deleteAllByIdIn(ids); } @Override @Cacheable(key = "'username:' + #p0") public UserDTO findByName(String userName) { User user = userRepository.findByUsername(userName); if (user == null) { throw new EntityNotFoundException(User.class, "name", userName); } else { return userMapper.toDto(user); } } @Override @Transactional(rollbackFor = Exception.class) public void updatePass(String username, String pass) { userRepository.updatePass(username, pass, new Date()); redisUtils.del("user::username:" + username); } @Override @Transactional(rollbackFor = Exception.class) public Map<String, String> updateAvatar(MultipartFile multipartFile) { User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername()); String oldPath = user.getAvatarPath();
File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar());
11
2023-11-10 03:30:36+00:00
24k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/moduleedit/commandinput/UseModuleFunctionEditPane.java
[ { "identifier": "GeneralHolder", "path": "service/src/main/java/com/lazycoder/service/GeneralHolder.java", "snippet": "public class GeneralHolder {\n\n\t//临时错误信息记录\n\tpublic static ArrayList<String> temporaryErrorList = new ArrayList<>();\n\n\t/**\n\t * 数据库名\n\t */\n\tpublic static DataSourceLabel curre...
import com.lazycoder.service.GeneralHolder; import com.lazycoder.service.fileStructure.DatabaseFileStructure; import com.lazycoder.service.fileStructure.SysFileStructure; import com.lazycoder.service.vo.datasourceedit.general.AbstractEditContainerModel; import com.lazycoder.uidatasourceedit.DataSourceEditHolder; import com.lazycoder.uidatasourceedit.ModuleEditPaneHolder; import com.lazycoder.uidatasourceedit.moduleedit.commandinput.function.ModuleFunctionEditPane; import com.lazycoder.uidatasourceedit.moduleedit.commandinput.moduleinit.InitPane; import com.lazycoder.uidatasourceedit.moduleedit.commandinput.moduleset.ModuleSetCodeEditPane; import java.io.File; import java.util.ArrayList; import javax.swing.JScrollPane; import javax.swing.JTabbedPane;
17,404
package com.lazycoder.uidatasourceedit.moduleedit.commandinput; public class UseModuleFunctionEditPane extends JTabbedPane { /** * */ private static final long serialVersionUID = 9022479016863745004L; private InitPane moduleInitPane; private ModuleSetCodeEditPane moduleSetCodePane;
package com.lazycoder.uidatasourceedit.moduleedit.commandinput; public class UseModuleFunctionEditPane extends JTabbedPane { /** * */ private static final long serialVersionUID = 9022479016863745004L; private InitPane moduleInitPane; private ModuleSetCodeEditPane moduleSetCodePane;
private ModuleFunctionEditPane moduleFunctionEditPane;
6
2023-11-16 11:55:06+00:00
24k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506_ex/KSBatchSwitch2.java
[ { "identifier": "PropertyMap", "path": "app/src/main/java/kr/or/kashi/hde/base/PropertyMap.java", "snippet": "public abstract class PropertyMap {\n /** Get the value of a property */\n public <E> E get(String name, Class<E> clazz) {\n return (E) get(name).getValue();\n }\n\n /** Put n...
import android.util.Log; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.base.PropertyValue; import kr.or.kashi.hde.MainContext; import kr.or.kashi.hde.device.BatchSwitch; import kr.or.kashi.hde.ksx4506.KSAddress; import kr.or.kashi.hde.ksx4506.KSBatchSwitch; import kr.or.kashi.hde.ksx4506.KSPacket; import java.util.Map;
16,500
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506_ex; /** * Extended implementation of [KS X 4506] the batch-switch */ public class KSBatchSwitch2 extends KSBatchSwitch { private static final String TAG = "KSBatchSwitch2"; private static final boolean DBG = true; public static final int CMD_LIFE_INFORMATION_DISPLAY_REQ = 0x51; public static final int CMD_3WAYLIGHT_STATUS_UPDATE_REQ = 0x52; public static final int CMD_PARKING_LOCATION_DISPLAY_REQ = 0x53; public static final int CMD_COOKTOP_STATUS_UPDATE_REQ = 0x55; public static final int CMD_COOKTOP_SETTING_RESULT_REQ = 0x56; public static final int CMD_ELEVATOR_ARRIVAL_UPDATE_REQ = 0x57; private boolean mCooktopOffReqReceived = false; private boolean mHeaterSavingReqReceived = false; private boolean mHeaterSavingOffReceived = false;
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506_ex; /** * Extended implementation of [KS X 4506] the batch-switch */ public class KSBatchSwitch2 extends KSBatchSwitch { private static final String TAG = "KSBatchSwitch2"; private static final boolean DBG = true; public static final int CMD_LIFE_INFORMATION_DISPLAY_REQ = 0x51; public static final int CMD_3WAYLIGHT_STATUS_UPDATE_REQ = 0x52; public static final int CMD_PARKING_LOCATION_DISPLAY_REQ = 0x53; public static final int CMD_COOKTOP_STATUS_UPDATE_REQ = 0x55; public static final int CMD_COOKTOP_SETTING_RESULT_REQ = 0x56; public static final int CMD_ELEVATOR_ARRIVAL_UPDATE_REQ = 0x57; private boolean mCooktopOffReqReceived = false; private boolean mHeaterSavingReqReceived = false; private boolean mHeaterSavingOffReceived = false;
public KSBatchSwitch2(MainContext mainContext, Map defaultProps) {
2
2023-11-10 01:19:44+00:00
24k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/ui/pluginMenu/PluginMenu.java
[ { "identifier": "ScreenWidget", "path": "src/main/java/io/xlorey/FluxLoader/client/ui/ScreenWidget.java", "snippet": "public class ScreenWidget implements IWidget {\n /**\n * Flag indicating whether the mouse cursor is inside the widget\n */\n private boolean isWidgetHovered = false;\n\n ...
import imgui.ImGui; import imgui.flag.ImGuiCol; import imgui.flag.ImGuiStyleVar; import imgui.flag.ImGuiWindowFlags; import imgui.type.ImBoolean; import io.xlorey.FluxLoader.client.ui.ScreenWidget; import io.xlorey.FluxLoader.interfaces.IControlsWidget; import io.xlorey.FluxLoader.plugin.Metadata; import io.xlorey.FluxLoader.plugin.Plugin; import io.xlorey.FluxLoader.shared.PluginManager; import io.xlorey.FluxLoader.utils.Constants; import zombie.GameWindow; import zombie.core.textures.Texture; import zombie.gameStates.MainScreenState; import java.util.HashSet; import java.util.List; import java.util.Map;
19,483
package io.xlorey.FluxLoader.client.ui.pluginMenu; /** * Plugin management menu */ public class PluginMenu extends ScreenWidget { /** * Flag indicating whether the window is open */ private static final ImBoolean isOpened = new ImBoolean(false); /** * ID of the selected plugin in the menu */ private String selectedPluginId; /** * Loaded client plugins */ private final Map<String, Plugin> loadedPlugins = PluginManager.getLoadedClientPlugins(); /** * Initializing the widget */ public PluginMenu(){ if (!loadedPlugins.isEmpty()) { selectedPluginId = loadedPlugins.keySet().iterator().next(); } } /** * Update window state */ @Override public void update() { super.update(); setVisible((GameWindow.states.current instanceof MainScreenState) && isOpened()); } /** * Sets the visibility state of the plugin's menu. * This method allows you to programmatically open or close the plugin menu. * @param open true to open the plugins menu; false to close. */ public static void setOpen(boolean open) { isOpened.set(open); } /** * Returns the current visibility state of the plugin's menu. * This method allows you to determine whether the plugins menu is currently open. * @return true if the plugins menu is open; false if closed. */ public static boolean isOpened() { return isOpened.get(); } /** * Rendering the plugin menu */ @Override public void render() { ImGui.setNextWindowSize(650, 400); ImGui.pushStyleVar(ImGuiStyleVar.WindowRounding, 8); ImGui.pushStyleVar(ImGuiStyleVar.FramePadding, 10, 10); ImGui.pushStyleVar(ImGuiStyleVar.ScrollbarSize, 3); ImGui.pushStyleColor(ImGuiCol.WindowBg, 12, 12, 12, 255); ImGui.pushStyleColor(ImGuiCol.TitleBg, 30, 30, 30, 255); ImGui.pushStyleColor(ImGuiCol.TitleBgActive, 30, 30, 30, 255); int emeraldActive = ImGui.getColorU32(0.0f, 0.55f, 0.55f, 1.0f); int emeraldHovered = ImGui.getColorU32(0.0f, 0.65f, 0.65f, 1.0f); int emeraldNormal = ImGui.getColorU32(0.0f, 0.60f, 0.60f, 1.0f); ImGui.pushStyleColor(ImGuiCol.ButtonActive, emeraldActive); ImGui.pushStyleColor(ImGuiCol.ButtonHovered, emeraldHovered); ImGui.pushStyleColor(ImGuiCol.Button, emeraldNormal); ImGui.begin(Constants.FLUX_NAME + " - Plugins", isOpened, ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoCollapse); captureMouseFocus(); if(loadedPlugins.isEmpty()) { String text = "No client plugins found"; float windowWidth = ImGui.getWindowWidth(); float windowHeight = ImGui.getWindowHeight(); float textWidth = ImGui.calcTextSize(text).x; float textHeight = ImGui.calcTextSize(text).y; ImGui.setCursorPosX((windowWidth - textWidth) * 0.5f); ImGui.setCursorPosY((windowHeight - textHeight) * 0.5f); ImGui.text(text); } else { renderPluginsInfo(); } ImGui.end(); ImGui.popStyleColor(6); ImGui.popStyleVar(3); } /** * Rendering information about plugins */ private void renderPluginsInfo() { ImGui.columns(2); ImGui.setColumnWidth(0, 256); ImGui.beginChild("#LeftPluginMenuColumn", -1, -1, false); HashSet<String> displayedPlugin = new HashSet<>(); for (Map.Entry<String, Plugin> entry : loadedPlugins.entrySet()) { Plugin plugin = entry.getValue();
package io.xlorey.FluxLoader.client.ui.pluginMenu; /** * Plugin management menu */ public class PluginMenu extends ScreenWidget { /** * Flag indicating whether the window is open */ private static final ImBoolean isOpened = new ImBoolean(false); /** * ID of the selected plugin in the menu */ private String selectedPluginId; /** * Loaded client plugins */ private final Map<String, Plugin> loadedPlugins = PluginManager.getLoadedClientPlugins(); /** * Initializing the widget */ public PluginMenu(){ if (!loadedPlugins.isEmpty()) { selectedPluginId = loadedPlugins.keySet().iterator().next(); } } /** * Update window state */ @Override public void update() { super.update(); setVisible((GameWindow.states.current instanceof MainScreenState) && isOpened()); } /** * Sets the visibility state of the plugin's menu. * This method allows you to programmatically open or close the plugin menu. * @param open true to open the plugins menu; false to close. */ public static void setOpen(boolean open) { isOpened.set(open); } /** * Returns the current visibility state of the plugin's menu. * This method allows you to determine whether the plugins menu is currently open. * @return true if the plugins menu is open; false if closed. */ public static boolean isOpened() { return isOpened.get(); } /** * Rendering the plugin menu */ @Override public void render() { ImGui.setNextWindowSize(650, 400); ImGui.pushStyleVar(ImGuiStyleVar.WindowRounding, 8); ImGui.pushStyleVar(ImGuiStyleVar.FramePadding, 10, 10); ImGui.pushStyleVar(ImGuiStyleVar.ScrollbarSize, 3); ImGui.pushStyleColor(ImGuiCol.WindowBg, 12, 12, 12, 255); ImGui.pushStyleColor(ImGuiCol.TitleBg, 30, 30, 30, 255); ImGui.pushStyleColor(ImGuiCol.TitleBgActive, 30, 30, 30, 255); int emeraldActive = ImGui.getColorU32(0.0f, 0.55f, 0.55f, 1.0f); int emeraldHovered = ImGui.getColorU32(0.0f, 0.65f, 0.65f, 1.0f); int emeraldNormal = ImGui.getColorU32(0.0f, 0.60f, 0.60f, 1.0f); ImGui.pushStyleColor(ImGuiCol.ButtonActive, emeraldActive); ImGui.pushStyleColor(ImGuiCol.ButtonHovered, emeraldHovered); ImGui.pushStyleColor(ImGuiCol.Button, emeraldNormal); ImGui.begin(Constants.FLUX_NAME + " - Plugins", isOpened, ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoCollapse); captureMouseFocus(); if(loadedPlugins.isEmpty()) { String text = "No client plugins found"; float windowWidth = ImGui.getWindowWidth(); float windowHeight = ImGui.getWindowHeight(); float textWidth = ImGui.calcTextSize(text).x; float textHeight = ImGui.calcTextSize(text).y; ImGui.setCursorPosX((windowWidth - textWidth) * 0.5f); ImGui.setCursorPosY((windowHeight - textHeight) * 0.5f); ImGui.text(text); } else { renderPluginsInfo(); } ImGui.end(); ImGui.popStyleColor(6); ImGui.popStyleVar(3); } /** * Rendering information about plugins */ private void renderPluginsInfo() { ImGui.columns(2); ImGui.setColumnWidth(0, 256); ImGui.beginChild("#LeftPluginMenuColumn", -1, -1, false); HashSet<String> displayedPlugin = new HashSet<>(); for (Map.Entry<String, Plugin> entry : loadedPlugins.entrySet()) { Plugin plugin = entry.getValue();
Metadata metadata = plugin.getMetadata();
2
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;
16,280
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);
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());
11
2023-11-15 15:05:58+00:00
24k
Hikaito/Fox-Engine
src/system/gui/editorPane/GuiFieldControls.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 system.Program; import system.gui.GuiOperations; import system.layerTree.data.LayerManager; import system.layerTree.data.SelectionManager; import system.layerTree.data.Folder; import system.layerTree.data.Layer; import system.layerTree.data.LayerCore; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
14,404
}); return clipBox; } //generate clipping label public static JLabel makeClippingLabel(LayerCore layer){ if (layer.getClipToParent()) return new JLabel("clipped"); else return null; } //endregion //region visibility ---------------------- //make toggle to visibility public static JCheckBox makeVisibleToggle(LayerCore layer){ //create toggle; set value to existing values JCheckBox clipBox = new JCheckBox("Visible", layer.getVisible()); //on selection, toggle visibility clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setViewAlpha()); layer.setVisible(); //Program.redrawAllRegions(); //layer.signalRedraw(); //redraw canvas } }); return clipBox; } //endregion //region visibilty toggle button------------------------- //add duplicate button public static JButton makeVisibilityToggleButton(LayerCore layer){ // text String text; if (layer.getVisible() == false) text = "-"; else text = "\uD83D\uDC41"; //👁 //add button JButton button = new JButton(text); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ layer.setVisible(); //Program.redrawAllRegions(); } }); return button; } //endregion //region alpha ------------------------- //add alpha edit box public static JPanel makeAlpha(LayerCore layer){ //add alpha box JPanel alphaPanel = new JPanel(); //create field for alpha text entering with a label JFormattedTextField alphaInput = new JFormattedTextField(layer.getAlpha()); //creates field with default alpha JLabel alphaLabel = new JLabel("alpha"); //creates label alphaPanel.add(alphaLabel); alphaPanel.add(alphaInput); //when change is detected, adjust alpha alphaInput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //if input is valid, set input to alpha. Otherwise, set alpha to input. try{ //parse double; if a valid number, establish range Double input = Double.parseDouble(alphaInput.getText()); layer.setAlpha(input); //setAlpha performs validity checking //layer.signalRedraw(); //redraw canvas } catch(Exception ee){ alphaInput.setValue(layer.getAlpha()); } // Program.redrawAllRegions(); } }); alphaInput.setColumns(3); return alphaPanel; } //endregion //endregion //region layer only manipulation ======================================== //region color ------------------------------ //generate color toggle for layer public static JCheckBox makeColorToggle(Layer layer){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("use color", layer.getUseColor()); //on selection, toggle using original color clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setUseColor()); layer.setUseColor(); //Program.redrawAllRegions(); //redraw editor and canvas } }); return clipBox; } //add color chooser to field (and helper) public static void addColorChooser(JPanel innerField, Layer layer){addColorChooser(innerField, 1, Color.BLACK, layer);} //text positions: 0 = none, 1 = left, 2 = right public static void addColorChooser(JPanel innerField, int textPosition, Color textColor, Layer layer){ //create button with image color JButton colorButton = new JButton(" "); colorButton.setBackground(layer.getColor()); //set color //make label for color text NOTE: text field is selectable
package system.gui.editorPane; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== // field controls for Layer objects public class GuiFieldControls { //region core unit manipulation ======================================== //region clone and delete-------------------------------------- //add delete button: adds deletion button to field public static JButton makeDelete(LayerCore layer){ //add button JButton button = new JButton("delete"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.deleteTreeUnit(layer, false); } }); return button; } //add delete all button: adds deletion of children button to field public static JButton makeDeleteAll(LayerCore layer){ //add button JButton button = new JButton("delete (deep)"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.deleteTreeUnit(layer, true); } }); return button; } //add duplicate button public static JButton makeDuplicate(LayerCore layer){ //add button JButton button = new JButton("clone"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.duplicateTreeUnit(layer); } }); return button; } //endregion //region movement control --------------------------- //function for adding location controls to panel [adds buttons to field] public static void addLocationControls(JPanel innerField, LayerCore layer){ //generate panel for holding buttons JPanel buttonBox = new JPanel(); innerField.add(buttonBox); //add buttons for location movement----------- buttonBox.add(makeButtonOut(layer)); //register button buttonBox.add(makeButtonUp(layer)); //label for level //JLabel levelLabel = new JLabel("level " + 0); //fixme 0 was level //buttonBox.add(levelLabel); buttonBox.add(makeButtonDown(layer)); buttonBox.add(makeButtonIn(layer)); } //get button for in public static JButton makeButtonIn(LayerCore layer){ //in: button to signal moving deeper in hierarchy JButton buttonIn = new JButton("->"); buttonIn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.IN); } }); return buttonIn; } //get button for down public static JButton makeButtonDown(LayerCore layer){ //down: button to signal moving down in hierarchy JButton buttonDown = new JButton("v"); buttonDown.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.DOWN); } }); return buttonDown; } //get button for up public static JButton makeButtonUp(LayerCore layer){ //up: button to signal moving up in hierarchy JButton buttonUp = new JButton("^"); buttonUp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.UP); } }); return buttonUp; } ///get button for out public static JButton makeButtonOut(LayerCore layer){ //out: button to signal moving out of the hierarchy JButton buttonOut = new JButton("<-"); //generate button buttonOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.OUT); } }); return buttonOut; } //endregion //region selection --------------------------- // function for selection public static JButton makeSelectionButton(LayerCore layer){ // pick text String text = "Deselect"; // test for selection: selection type is select if not selected if (Program.checkSelection(layer) == SelectionManager.selectionPriority.NONE) text = "Select"; //out: button to signal moving out of the hierarchy JButton buttonOut = new JButton(text); //generate button buttonOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //check selection value // select if unselected if (Program.checkSelection(layer) == SelectionManager.selectionPriority.NONE) Program.addSelection(layer); //otherwise unselect if selected else Program.removeSelection(layer); //on click, move out in hierarchy Program.redrawLayerEditor(); //redraw layer map //Program.redrawLayerEditor(); //layer.signalRedraw(); //redraw canvas //fixme idk about this } }); return buttonOut; } //endregion //endregion //region common element manipulation ======================================== //region title------------------------ //generate title label public static JLabel makeTitle(LayerCore layer){ return new JLabel(layer.getTitle()); } // generate title text field public static JTextField makeTitleField(LayerCore layer){ JTextField title = new JTextField(10); //generate text field with preferred size title.setText(layer.getTitle()); // action title.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setTitle(title.getText())); layer.setTitle(title.getText()); Program.redrawLayerEditor(); } }); return title; } //endregion- //region clipping------------------------------- //add clipping toggle to field public static JCheckBox makeClippingToggle(LayerCore layer){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("clip", layer.getClipToParent()); //on selection, toggle clipping in layer clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setClipToParent()); layer.setClipToParent(); // Program.redrawAllRegions(); } }); return clipBox; } //generate clipping label public static JLabel makeClippingLabel(LayerCore layer){ if (layer.getClipToParent()) return new JLabel("clipped"); else return null; } //endregion //region visibility ---------------------- //make toggle to visibility public static JCheckBox makeVisibleToggle(LayerCore layer){ //create toggle; set value to existing values JCheckBox clipBox = new JCheckBox("Visible", layer.getVisible()); //on selection, toggle visibility clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setViewAlpha()); layer.setVisible(); //Program.redrawAllRegions(); //layer.signalRedraw(); //redraw canvas } }); return clipBox; } //endregion //region visibilty toggle button------------------------- //add duplicate button public static JButton makeVisibilityToggleButton(LayerCore layer){ // text String text; if (layer.getVisible() == false) text = "-"; else text = "\uD83D\uDC41"; //👁 //add button JButton button = new JButton(text); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ layer.setVisible(); //Program.redrawAllRegions(); } }); return button; } //endregion //region alpha ------------------------- //add alpha edit box public static JPanel makeAlpha(LayerCore layer){ //add alpha box JPanel alphaPanel = new JPanel(); //create field for alpha text entering with a label JFormattedTextField alphaInput = new JFormattedTextField(layer.getAlpha()); //creates field with default alpha JLabel alphaLabel = new JLabel("alpha"); //creates label alphaPanel.add(alphaLabel); alphaPanel.add(alphaInput); //when change is detected, adjust alpha alphaInput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //if input is valid, set input to alpha. Otherwise, set alpha to input. try{ //parse double; if a valid number, establish range Double input = Double.parseDouble(alphaInput.getText()); layer.setAlpha(input); //setAlpha performs validity checking //layer.signalRedraw(); //redraw canvas } catch(Exception ee){ alphaInput.setValue(layer.getAlpha()); } // Program.redrawAllRegions(); } }); alphaInput.setColumns(3); return alphaPanel; } //endregion //endregion //region layer only manipulation ======================================== //region color ------------------------------ //generate color toggle for layer public static JCheckBox makeColorToggle(Layer layer){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("use color", layer.getUseColor()); //on selection, toggle using original color clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setUseColor()); layer.setUseColor(); //Program.redrawAllRegions(); //redraw editor and canvas } }); return clipBox; } //add color chooser to field (and helper) public static void addColorChooser(JPanel innerField, Layer layer){addColorChooser(innerField, 1, Color.BLACK, layer);} //text positions: 0 = none, 1 = left, 2 = right public static void addColorChooser(JPanel innerField, int textPosition, Color textColor, Layer layer){ //create button with image color JButton colorButton = new JButton(" "); colorButton.setBackground(layer.getColor()); //set color //make label for color text NOTE: text field is selectable
JTextField colorLabel = new JTextField(GuiOperations.formatColor(layer.getColor())); //get color label from unit color
1
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,569
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())){
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!");
0
2023-11-11 19:40:43+00:00
24k
shizotoaster/thaumon
fabric/src/main/java/jdlenl/thaumon/itemgroup/fabric/ThaumonItemGroupFabric.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.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.text.Text; import net.minecraft.util.Identifier;
14,651
package jdlenl.thaumon.itemgroup.fabric; public class ThaumonItemGroupFabric { public static final ItemGroup THAUMON_GROUP = Registry.register(Registries.ITEM_GROUP, new Identifier(Thaumon.MOD_ID, "thaumon_item_group"),
package jdlenl.thaumon.itemgroup.fabric; public class ThaumonItemGroupFabric { public static final ItemGroup THAUMON_GROUP = Registry.register(Registries.ITEM_GROUP, new Identifier(Thaumon.MOD_ID, "thaumon_item_group"),
FabricItemGroup.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/predictionengine/MovementCheckRunner.java
[ { "identifier": "EntityControl", "path": "src/main/java/ac/grim/grimac/checks/impl/movement/EntityControl.java", "snippet": "@CheckData(name = \"Entity control\", buffer = 10, maxBuffer = 15)\npublic class EntityControl extends PostPredictionCheck {\n public EntityControl(GrimPlayer player) {\n ...
import ac.grim.grimac.checks.impl.movement.EntityControl; import ac.grim.grimac.checks.type.PositionCheck; import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.predictionengine.movementtick.MovementTickerHorse; import ac.grim.grimac.predictionengine.movementtick.MovementTickerPig; import ac.grim.grimac.predictionengine.movementtick.MovementTickerPlayer; import ac.grim.grimac.predictionengine.movementtick.MovementTickerStrider; import ac.grim.grimac.predictionengine.predictions.PredictionEngineNormal; import ac.grim.grimac.predictionengine.predictions.rideable.BoatPredictionEngine; import ac.grim.grimac.utils.anticheat.update.PositionUpdate; import ac.grim.grimac.utils.anticheat.update.PredictionComplete; import ac.grim.grimac.utils.collisions.datatypes.SimpleCollisionBox; import ac.grim.grimac.utils.data.SetBackData; import ac.grim.grimac.utils.data.VectorData; import ac.grim.grimac.utils.data.packetentity.PacketEntityHorse; import ac.grim.grimac.utils.data.packetentity.PacketEntityRideable; import ac.grim.grimac.utils.enums.EntityType; import ac.grim.grimac.utils.enums.Pose; import ac.grim.grimac.utils.math.GrimMath; import ac.grim.grimac.utils.math.VectorUtils; import ac.grim.grimac.utils.nmsutil.*; import io.github.retrooper.packetevents.utils.player.ClientVersion; import io.github.retrooper.packetevents.utils.server.ServerVersion; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector;
20,308
package ac.grim.grimac.predictionengine; // This class is how we manage to safely do everything async // AtomicInteger allows us to make decisions safely - we can get and set values in one processor instruction // This is the meaning of GrimPlayer.tasksNotFinished // Stage 0 - All work is done // Stage 1 - There is more work, number = number of jobs in the queue and running // // After finishing doing the predictions: // If stage 0 - Do nothing // If stage 1 - Subtract by 1, and add another to the queue // // When the player sends a packet and we have to add him to the queue: // If stage 0 - Add one and add the data to the workers // If stage 1 - Add the data to the queue and add one public class MovementCheckRunner extends PositionCheck { private static final Material CARROT_ON_A_STICK = XMaterial.CARROT_ON_A_STICK.parseMaterial(); private static final Material WARPED_FUNGUS_ON_A_STICK = XMaterial.WARPED_FUNGUS_ON_A_STICK.parseMaterial(); private static final Material BUBBLE_COLUMN = XMaterial.BUBBLE_COLUMN.parseMaterial();
package ac.grim.grimac.predictionengine; // This class is how we manage to safely do everything async // AtomicInteger allows us to make decisions safely - we can get and set values in one processor instruction // This is the meaning of GrimPlayer.tasksNotFinished // Stage 0 - All work is done // Stage 1 - There is more work, number = number of jobs in the queue and running // // After finishing doing the predictions: // If stage 0 - Do nothing // If stage 1 - Subtract by 1, and add another to the queue // // When the player sends a packet and we have to add him to the queue: // If stage 0 - Add one and add the data to the workers // If stage 1 - Add the data to the queue and add one public class MovementCheckRunner extends PositionCheck { private static final Material CARROT_ON_A_STICK = XMaterial.CARROT_ON_A_STICK.parseMaterial(); private static final Material WARPED_FUNGUS_ON_A_STICK = XMaterial.WARPED_FUNGUS_ON_A_STICK.parseMaterial(); private static final Material BUBBLE_COLUMN = XMaterial.BUBBLE_COLUMN.parseMaterial();
public MovementCheckRunner(GrimPlayer player) {
2
2023-11-11 05:14:12+00:00
24k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/activity/CommentActivity.java
[ { "identifier": "DataBaseHelper", "path": "app/src/main/java/com/buaa/food/DataBaseHelper.java", "snippet": "public class DataBaseHelper extends SQLiteOpenHelper {\n private static final String DB_NAME = \"BuaaFood.db\";\n private Context context;\n\n private ByteArrayOutputStream byteArrayOutp...
import android.view.KeyEvent; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.TextView; import androidx.appcompat.widget.AppCompatButton; import androidx.viewpager.widget.ViewPager; import com.buaa.food.DataBaseHelper; import com.buaa.food.R; import com.buaa.food.UserAuth; import com.buaa.food.aop.SingleClick; import com.buaa.food.app.AppActivity; import com.buaa.food.app.AppFragment; import com.buaa.food.ui.dialog.InputDialog; import com.buaa.food.ui.fragment.CommentsFragment; import com.hjq.bar.TitleBar; import com.hjq.base.FragmentPagerAdapter;
18,324
package com.buaa.food.ui.activity; public class CommentActivity extends AppActivity implements TextView.OnEditorActionListener{ private int dishId; private int commentId; private TitleBar mTitleBar; private LinearLayout mLinearLayout; private LinearLayout mCommentLinearLayout; private TextView commentView; private TextView userView; private ViewPager mViewPager; private FragmentPagerAdapter<AppFragment<?>> mPagerAdapter; private DataBaseHelper dataBaseHelper; private AppCompatButton mCommentButton; protected int getLayoutId() { return R.layout.comment_activity; } protected void initView() { dataBaseHelper = new DataBaseHelper(this); dishId = getIntent().getIntExtra("dishId", 0); commentId = getIntent().getIntExtra("commentId", 0); mLinearLayout = findViewById(R.id.comment_activity); mCommentLinearLayout = findViewById(R.id.one_comment); mTitleBar = findViewById(R.id.comment); mViewPager = findViewById(R.id.vp_comment_pager); mPagerAdapter = new FragmentPagerAdapter<>(this); if (dishId != 0 && commentId == 0) { mTitleBar.setTitle("一级评论");
package com.buaa.food.ui.activity; public class CommentActivity extends AppActivity implements TextView.OnEditorActionListener{ private int dishId; private int commentId; private TitleBar mTitleBar; private LinearLayout mLinearLayout; private LinearLayout mCommentLinearLayout; private TextView commentView; private TextView userView; private ViewPager mViewPager; private FragmentPagerAdapter<AppFragment<?>> mPagerAdapter; private DataBaseHelper dataBaseHelper; private AppCompatButton mCommentButton; protected int getLayoutId() { return R.layout.comment_activity; } protected void initView() { dataBaseHelper = new DataBaseHelper(this); dishId = getIntent().getIntExtra("dishId", 0); commentId = getIntent().getIntExtra("commentId", 0); mLinearLayout = findViewById(R.id.comment_activity); mCommentLinearLayout = findViewById(R.id.one_comment); mTitleBar = findViewById(R.id.comment); mViewPager = findViewById(R.id.vp_comment_pager); mPagerAdapter = new FragmentPagerAdapter<>(this); if (dishId != 0 && commentId == 0) { mTitleBar.setTitle("一级评论");
mPagerAdapter.addFragment(CommentsFragment.newInstance(dishId, CommentsFragment.StatusType.CommentOne));
5
2023-11-14 10:04:26+00:00
24k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/block/processed/BlockFace.java
[ { "identifier": "FaceData", "path": "src/main/java/useless/dragonfly/model/block/data/FaceData.java", "snippet": "public class FaceData {\n\t@SerializedName(\"uv\")\n\tpublic double[] uv = null;\n\t@SerializedName(\"texture\")\n\tpublic String texture = null;\n\t@SerializedName(\"cullface\")\n\tpublic S...
import net.minecraft.client.render.TextureFX; import net.minecraft.core.Global; import net.minecraft.core.util.helper.Side; import useless.dragonfly.model.block.data.FaceData; import useless.dragonfly.model.block.data.ModelData; import useless.dragonfly.registries.TextureRegistry; import useless.dragonfly.utilities.vector.Vector3f; import static useless.dragonfly.DragonFly.terrainAtlasWidth;
17,341
package useless.dragonfly.model.block.processed; public class BlockFace { protected FaceData faceData; protected double[] uvScaled; protected Side side; protected Side cullFace = null; public final Vector3f[] vertices; protected final String[] vertexUVMap; protected String[] vertexKeyMap = new String[4]; protected double[][] vertexUVs; public BlockCube parentCube; public BlockFace(BlockCube cube, String key){ this.faceData = cube.cubeData.faces.get(key);
package useless.dragonfly.model.block.processed; public class BlockFace { protected FaceData faceData; protected double[] uvScaled; protected Side side; protected Side cullFace = null; public final Vector3f[] vertices; protected final String[] vertexUVMap; protected String[] vertexKeyMap = new String[4]; protected double[][] vertexUVs; public BlockCube parentCube; public BlockFace(BlockCube cube, String key){ this.faceData = cube.cubeData.faces.get(key);
this.side = ModelData.keyToSide.get(key);
1
2023-11-16 01:10:52+00:00
24k
Shushandr/offroad
src/net/sourceforge/offroad/actions/OffRoadAction.java
[ { "identifier": "PlatformUtil", "path": "src/net/osmand/PlatformUtil.java", "snippet": "public class PlatformUtil {\n\t\n\tpublic static Log getLog(Class<?> cl){\n\t\treturn LogFactory.getLog(cl);\n\t}\n\t\n\tpublic static XmlPullParser newXMLPullParser() throws XmlPullParserException{\n\t\treturn new o...
import java.awt.Cursor; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JMenu; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.WindowConstants; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import org.apache.commons.logging.Log; import net.osmand.PlatformUtil; import net.sourceforge.offroad.OsmWindow; import net.sourceforge.offroad.data.persistence.ComponentLocationStorage; import net.sourceforge.offroad.ui.StayOpenCheckBoxMenuItem;
19,735
/** OffRoad Copyright (C) 2016 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 09.04.2016 */ public abstract class OffRoadAction extends AbstractAction { protected final static Log log = PlatformUtil.getLog(OffRoadAction.class); public interface SelectableAction { } protected OsmWindow mContext; protected JDialog mDialog; public OffRoadAction(OsmWindow pContext) { this(pContext, null, null); } public OffRoadAction(OsmWindow pContext, String name, Icon icon) { super(name, icon); mContext = pContext; } public static void addEscapeActionToDialog(JDialog dialog, Action action) { addKeyActionToDialog(dialog, action, "ESCAPE", "end_dialog"); } public static void addKeyActionToDialog(JDialog dialog, Action action, String keyStroke, String actionId) { action.putValue(Action.NAME, actionId); // Register keystroke dialog.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(keyStroke), action.getValue(Action.NAME)); // Register action dialog.getRootPane().getActionMap().put(action.getValue(Action.NAME), action); } protected void setWaitingCursor() { mDialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); mContext.setWaitingCursor(true); } protected void removeWaitingCursor() { mDialog.setCursor(Cursor.getDefaultCursor()); mContext.setWaitingCursor(false); } protected void disposeDialog() { save(); mDialog.setVisible(false); mDialog.dispose(); } public void save() { if (mDialog != null) {
/** OffRoad Copyright (C) 2016 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 09.04.2016 */ public abstract class OffRoadAction extends AbstractAction { protected final static Log log = PlatformUtil.getLog(OffRoadAction.class); public interface SelectableAction { } protected OsmWindow mContext; protected JDialog mDialog; public OffRoadAction(OsmWindow pContext) { this(pContext, null, null); } public OffRoadAction(OsmWindow pContext, String name, Icon icon) { super(name, icon); mContext = pContext; } public static void addEscapeActionToDialog(JDialog dialog, Action action) { addKeyActionToDialog(dialog, action, "ESCAPE", "end_dialog"); } public static void addKeyActionToDialog(JDialog dialog, Action action, String keyStroke, String actionId) { action.putValue(Action.NAME, actionId); // Register keystroke dialog.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(keyStroke), action.getValue(Action.NAME)); // Register action dialog.getRootPane().getActionMap().put(action.getValue(Action.NAME), action); } protected void setWaitingCursor() { mDialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); mContext.setWaitingCursor(true); } protected void removeWaitingCursor() { mDialog.setCursor(Cursor.getDefaultCursor()); mContext.setWaitingCursor(false); } protected void disposeDialog() { save(); mDialog.setVisible(false); mDialog.dispose(); } public void save() { if (mDialog != null) {
ComponentLocationStorage.storeDialogPositions(mContext, mDialog, createComponentLocationStorage(),
2
2023-11-15 05:04:55+00:00
24k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/service/actionrecord/impl/EmployeeActionRecordServiceImpl.java
[ { "identifier": "Content", "path": "common/common-log/src/main/java/com/kakarote/common/log/entity/Content.java", "snippet": "@Getter\n@AllArgsConstructor\n@Builder\npublic class Content {\n\n private String subModel;\n\n private String object;\n\n private String detail;\n\n private String t...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DateUtil; import cn.hutool.core.lang.Dict; import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.kakarote.common.log.entity.Content; import com.kakarote.common.log.enums.BehaviorEnum; import com.kakarote.core.common.Const; import com.kakarote.core.common.enums.FieldEnum; import com.kakarote.core.common.enums.LanguageFieldEnum; import com.kakarote.core.servlet.ApplicationContextHolder; import com.kakarote.hrm.common.LanguageFieldUtil; import com.kakarote.hrm.constant.*; import com.kakarote.hrm.entity.BO.DeleteLeaveInformationBO; import com.kakarote.hrm.entity.BO.HrmActionRecordListBO; import com.kakarote.hrm.entity.BO.UpdateInformationBO; import com.kakarote.hrm.entity.PO.*; import com.kakarote.hrm.entity.VO.HrmModelFiledVO; import com.kakarote.hrm.service.*; import com.kakarote.hrm.service.actionrecord.AbstractHrmActionRecordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors;
15,531
if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = QuitReasonEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } break; case SOCIAL_SECURITY: String isFirstSocialSecurity = "isFirstSocialSecurity"; String isFirstAccumulationFund = "isFirstAccumulationFund"; String schemeId = "schemeId"; if (isFirstSocialSecurity.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (isFirstAccumulationFund.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (schemeId.equals(newFieldKey)) { HrmInsuranceScheme oldScheme = insuranceSchemeService.getById(oldValue); HrmInsuranceScheme newScheme = insuranceSchemeService.getById(newValue); if (oldScheme != null) { oldValue = oldScheme.getSchemeName(); } if (newScheme != null) { newValue = newScheme.getSchemeName(); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } break; case CONTRACT: String contractType = "contractType"; String status = "status"; String isExpireRemind = "isExpireRemind"; if (contractType.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = EmployeeContractType.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = EmployeeContractType.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (status.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = EmployeeContractStatus.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = EmployeeContractStatus.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (isExpireRemind.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } break; default: break; } return content; } public Content cancelLeave(DeleteLeaveInformationBO deleteLeaveInformationBO) { StringBuilder content = new StringBuilder(); StringBuilder transContent = new StringBuilder(); content.append("取消了离职"); transContent.append(HrmLanguageEnum.CANCEL.getFieldFormat() + " " + HrmLanguageEnum.RESIGNATION.getFieldFormat()); if (StrUtil.isNotEmpty(deleteLeaveInformationBO.getRemarks())) { content.append(",原因:").append(deleteLeaveInformationBO.getRemarks()); transContent.append("," + HrmLanguageEnum.REASON.getFieldFormat() + ":").append(deleteLeaveInformationBO.getRemarks()); } actionRecordService.saveRecord(actionTypeEnum, HrmActionBehaviorEnum.UPDATE, Collections.singletonList(content.toString()), Collections.singletonList(transContent.toString()), deleteLeaveInformationBO.getEmployeeId()); HrmEmployee employee = employeeService.getById(deleteLeaveInformationBO.getEmployeeId()); return new Content(employee.getEmployeeName(), content.toString(), transContent.toString(), BehaviorEnum.UPDATE); } /** * 保存固定字段记录 * * @param oldObj * @param newObj * @param labelGroupEnum * @param employeeId */ public Content employeeFixedFieldRecord(Map<String, Object> oldObj, Map<String, Object> newObj, LabelGroupEnum labelGroupEnum, Long employeeId) { HrmEmployee employee = employeeService.getById(employeeId); try { textList.clear(); transList.clear(); searchChange(textList, transList, oldObj, newObj, labelGroupEnum); if (textList.size() > 0) { actionRecordService.saveRecord(actionTypeEnum, HrmActionBehaviorEnum.UPDATE, textList, transList, employeeId); return new Content(employee.getEmployeeName(), CollUtil.join(textList, ","), CollUtil.join(transList, ","), BehaviorEnum.UPDATE); } } finally { textList.clear(); transList.clear(); } return new Content(employee.getEmployeeName(), "", BehaviorEnum.UPDATE); } /** * 保存非固定字段记录 * * @param newFieldList * @param oldFieldList */
package com.kakarote.hrm.service.actionrecord.impl; /** * 员工操作记录 * * @author hmb */ @Service("employeeActionRecordService") public class EmployeeActionRecordServiceImpl extends AbstractHrmActionRecordService { @Autowired private IHrmEmployeeService employeeService; @Autowired private IHrmDeptService deptService; @Autowired private IHrmEmployeeFieldService employeeFieldService; @Autowired private IHrmInsuranceSchemeService insuranceSchemeService; private static HrmActionTypeEnum actionTypeEnum = HrmActionTypeEnum.EMPLOYEE; private static final String NULL = "空"; private static final String TRANSNULL = LanguageFieldEnum.ACTIONRECORD_EMPTY.getFieldFormat(); /** * 属性kv */ public static Map<LabelGroupEnum, Dict> propertiesMap = new HashMap<>(); static { propertiesMap.put(LabelGroupEnum.EDUCATIONAL_EXPERIENCE, Dict.create().set("education", "学历").set("graduateSchool", "毕业院校").set("major", "专业").set("admissionTime", "入学时间").set("graduationTime", "毕业时间").set("teachingMethods", "教学方式").set("isFirstDegree", "是否第一学历")); propertiesMap.put(LabelGroupEnum.WORK_EXPERIENCE, Dict.create().set("workUnit", "工作单位").set("post", "职务").set("workStartTime", "工作开始时间").set("workEndTime", "工作结束时间").set("leavingReason", "离职原因").set("witness", "证明人").set("witnessPhone", "证明人手机号").set("workRemarks", "工作备注")); propertiesMap.put(LabelGroupEnum.CERTIFICATE, Dict.create().set("certificateName", "证书名称").set("certificateLevel", "证书级别").set("certificateNum", "证书编号").set("startTime", "有效起始日期").set("endTime", "有效结束日期").set("issuingAuthority", "发证机构").set("issuingTime", "发证日期").set("remarks", "证书备注")); propertiesMap.put(LabelGroupEnum.TRAINING_EXPERIENCE, Dict.create().set("trainingCourse", "培训课程").set("trainingOrganName", "培训机构名称").set("startTime", "培训开始时间").set("endTime", "培训结束时间").set("trainingDuration", "培训时长").set("trainingResults", "培训成绩").set("trainingCertificateName", "培训课程名称").set("remarks", "培训备注")); propertiesMap.put(LabelGroupEnum.QUIT, Dict.create().set("planQuitTime", "计划离职日期").set("applyQuitTime", "申请离职日期").set("salarySettlementTime", "薪资结算日期").set("quitType", "离职类型").set("quitReason", "离职原因").set("remarks", "备注")); propertiesMap.put(LabelGroupEnum.SALARY_CARD, Dict.create().set("salaryCardNum", "工资卡卡号").set("accountOpeningCity", "开户城市").set("bankName", "银行名称").set("openingBank", "工资卡开户行")); propertiesMap.put(LabelGroupEnum.SOCIAL_SECURITY, Dict.create().set("isFirstSocialSecurity", "是否首次缴纳社保").set("isFirstAccumulationFund", "是否首次缴纳公积金").set("socialSecurityNum", "社保号").set("accumulationFundNum", "公积金账号").set("socialSecurityStartMonth", "参保起始月份").set("schemeId", "参保方案")); propertiesMap.put(LabelGroupEnum.CONTRACT, Dict.create().set("contractNum", "合同编号").set("contractType", "合同类型").set("startTime", "合同开始日期").set("endTime", "合同结束日期").set("term", "期限").set("status", "合同状态").set("signCompany", "签约公司").set("signTime", "合同签订日期").set("remarks", "备注").set("isExpireRemind", "是否到期提醒")); propertiesMap.put(LabelGroupEnum.PERSONAL, Dict.create().set("employeeName", "姓名").set("mobile", "手机").set("country", "国家地区").set("nation", "民族").set("idType", "证件类型").set("idNumber", "证件号码").set("sex", "性别").set("dateOfBirth", "出生日期").set("birthdayType", "生日类型").set("birthday", "生日").set("nativePlace", "籍贯").set("address", "户籍所在地").set("highestEducation", "最高学历")); propertiesMap.put(LabelGroupEnum.COMMUNICATION, Dict.create().set("email", "邮箱")); propertiesMap.put(LabelGroupEnum.POST, Dict.create().set("jobNumber", "工号").set("entryTime", "入职时间").set("deptId", "部门").set("post", "岗位").set("parentId", "直属上级").set("postLevel", "职级").set("workCity", "工作城市").set("workAddress", "工作地点").set("workDetailAddress", "详细工作地点").set("employmentForms", "聘用形式").set("probation", "试用期").set("becomeTime", "转正日期").set("companyAgeStartTime", "司龄开始日期").set("channelId", "招聘渠道")); propertiesMap.put(LabelGroupEnum.CONTACT_PERSON, Dict.create().set("contactsName", "联系人姓名").set("email", "邮箱").set("relation", "关系").set("contactsPhone", "联系人电话").set("contactsWorkUnit", "联系人工作单位").set("contactsPost", "联系人职务").set("contactsAddress", "联系人地址")); } private List<String> textList = new ArrayList<>(); private List<String> transList = new ArrayList<>(); /** * 新建/删除操作记录 */ public Content addOrDeleteRecord(HrmActionBehaviorEnum behaviorEnum, LabelGroupEnum labelGroupEnum, Long employeeId) { String content = behaviorEnum.getName() + "了" + labelGroupEnum.getDesc(); String transContent = behaviorEnum.getFieldFormat() + " " + labelGroupEnum.getFieldFormat(); actionRecordService.saveRecord(actionTypeEnum, behaviorEnum, Collections.singletonList(content), Collections.singletonList(transContent), employeeId); HrmEmployee employee = employeeService.getById(employeeId); if (HrmActionBehaviorEnum.ADD.equals(behaviorEnum)) { return new Content(employee.getEmployeeName(), content, transContent, BehaviorEnum.SAVE); } else { return new Content(employee.getEmployeeName(), content, transContent, BehaviorEnum.DELETE); } } /** * 员工附件附件 * * @param employeeFile */ public Content addFileRecord(HrmEmployeeFile employeeFile, HrmActionBehaviorEnum behaviorEnum) { String content; String transContent; if (behaviorEnum.equals(HrmActionBehaviorEnum.ADD)) { content = "上传了" + EmployeeFileType.parseName(employeeFile.getSubType()) + "附件"; transContent = HrmLanguageEnum.UPLOAD.getFieldFormat() + EmployeeFileType.parseName(employeeFile.getSubType()) + HrmLanguageEnum.FILE.getFieldFormat(); } else { content = behaviorEnum.getName() + "了" + EmployeeFileType.parseName(employeeFile.getSubType()) + "附件"; transContent = behaviorEnum.getName() + " " + EmployeeFileType.parseName(employeeFile.getSubType()) + HrmLanguageEnum.FILE.getFieldFormat(); } actionRecordService.saveRecord(actionTypeEnum, behaviorEnum, Collections.singletonList(content), Collections.singletonList(transContent), employeeFile.getEmployeeId()); HrmEmployee employee = employeeService.getById(employeeFile.getEmployeeId()); return new Content(employee.getEmployeeName(), content, transContent, BehaviorEnum.SAVE); } /** * 员工转正/调岗/晋升 */ public Content changeRecord(HrmEmployeeChangeRecord changeRecord) { HrmEmployee employee = employeeService.getById(changeRecord.getEmployeeId()); StringBuilder content = new StringBuilder(); StringBuilder transContent = new StringBuilder(); HrmActionBehaviorEnum changeTypeEnum = HrmActionBehaviorEnum.parse(changeRecord.getChangeType()); content.append("为").append(employee.getEmployeeName()); transContent.append(" ").append(employee.getEmployeeName()); switch (changeTypeEnum) { case CHANGE_POST: case PROMOTED: case DEGRADE: case CHANGE_FULL_TIME_EMPLOYEE: content .append("添加了一条人事异动【").append(changeTypeEnum.getName()).append("】,异动原因:") .append(ChangeReasonEnum.parseName(changeRecord.getChangeReason())) .append(",生效日期为:").append(DateUtil.format(changeRecord.getEffectTime().atStartOfDay(), DatePattern.NORM_DATE_PATTERN)); transContent .append(LanguageFieldEnum.ACTIONRECORD_ADD.getFieldFormat() + HrmLanguageEnum.PERSONNEL_CHANGE.getFieldFormat() + "【").append(changeTypeEnum.getName()).append("】," + HrmLanguageEnum.CHANGE_REASON.getFieldFormat() + ":") .append(ChangeReasonEnum.parseName(changeRecord.getChangeReason())) .append("," + HrmLanguageEnum.EFFECTIVE_DATE.getFieldFormat() + ":").append(DateUtil.format(changeRecord.getEffectTime().atStartOfDay(), DatePattern.NORM_DATE_PATTERN)); String transOldDeptValue = LanguageFieldEnum.ACTIONRECORD_EMPTY.getFieldFormat(); String transNewDeptValue = LanguageFieldEnum.ACTIONRECORD_EMPTY.getFieldFormat(); if (changeRecord.getOldDept() != null) { transOldDeptValue = deptService.getById(changeRecord.getOldDept()).getName(); } if (changeRecord.getNewDept() != null) { transNewDeptValue = deptService.getById(changeRecord.getNewDept()).getName(); } if (!transOldDeptValue.equals(transNewDeptValue)) { transContent.append(",").append(HrmLanguageEnum.DEPT.getFieldFormat()).append(" ").append(transOldDeptValue).append(LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat()).append(transOldDeptValue); } if (changeRecord.getOldPost() == null) { changeRecord.setOldPost("无"); } if (!changeRecord.getOldPost().equals(changeRecord.getNewPostLevel())) { content.append(",岗位由").append(changeRecord.getOldPost()).append("变更为").append(changeRecord.getNewPost()); transContent.append(",").append(HrmLanguageEnum.POST.getFieldFormat()).append(" ").append(changeRecord.getOldPost()).append(LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat()).append(changeRecord.getNewPost()); } if (changeRecord.getOldPostLevel() == null) { changeRecord.setOldPostLevel("无"); } if (!changeRecord.getOldPostLevel().equals(changeRecord.getNewPostLevel())) { content.append(",职级由").append(changeRecord.getOldPostLevel()).append("变更为").append(changeRecord.getNewPostLevel()); transContent.append(",").append(HrmLanguageEnum.RANK.getFieldFormat()).append(" ").append(changeRecord.getOldPostLevel()).append(LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat()).append(changeRecord.getNewPostLevel()); } if (changeRecord.getOldWorkAddress() == null) { changeRecord.setOldWorkAddress("无"); } if (!changeRecord.getOldWorkAddress().equals(changeRecord.getNewWorkAddress())) { content.append(",工作地址由").append(changeRecord.getOldWorkAddress()).append("变更为").append(changeRecord.getNewWorkAddress()); transContent.append(",").append(HrmLanguageEnum.WORKING_ADDRESS.getFieldFormat()).append(" ").append(changeRecord.getOldWorkAddress()).append(LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat()).append(changeRecord.getNewWorkAddress()); } if (changeTypeEnum.equals(HrmActionBehaviorEnum.CHANGE_FULL_TIME_EMPLOYEE)) { content.append(",试用期:").append(changeRecord.getProbation()).append("个月"); transContent.append(",").append(HrmLanguageEnum.PROBATION_PERIOD.getFieldFormat()).append(":").append(changeRecord.getProbation()).append(HrmLanguageEnum.MONTH.getFieldFormat()); } break; case BECOME: content .append("办理了转正,转正日期").append(DateUtil.format(changeRecord.getEffectTime().atStartOfDay(), DatePattern.NORM_DATE_PATTERN)); transContent .append(HrmLanguageEnum.CONFIRMATION_DATE.getFieldFormat()).append(DateUtil.format(changeRecord.getEffectTime().atStartOfDay(), DatePattern.NORM_DATE_PATTERN)); break; default: break; } if (StrUtil.isNotEmpty(changeRecord.getRemarks())) { content.append(",备注:").append(changeRecord.getRemarks()); transContent.append(",").append(HrmLanguageEnum.REMARK.getFieldFormat()).append(":").append(changeRecord.getRemarks()); } actionRecordService.saveRecord(actionTypeEnum, changeTypeEnum, Collections.singletonList(content.toString()), Collections.singletonList(transContent.toString()), changeRecord.getEmployeeId()); return new Content(employee.getEmployeeName(), content.toString(), transContent.toString(), BehaviorEnum.UPDATE); } /** * 离职操作记录 * * @param quitInfo */ public Content quitRecord(HrmEmployeeQuitInfo quitInfo) { HrmEmployee employee = employeeService.getById(quitInfo.getEmployeeId()); StringBuilder content = new StringBuilder(); StringBuilder transContent = new StringBuilder(); content .append("为").append(employee.getEmployeeName()); transContent .append(" ").append(employee.getEmployeeName()); if (quitInfo.getQuitReason() == null) { content.append("办理了退休"); transContent.append(HrmLanguageEnum.RETIRE.getFieldFormat()); } else { QuitReasonEnum reasonEnum = QuitReasonEnum.parse(quitInfo.getQuitReason()); content.append("添加了离职申请,于").append(DateUtil.format(quitInfo.getApplyQuitTime().atStartOfDay(), DatePattern.NORM_DATE_PATTERN)) .append("提出离职,计划离职日期:").append(DateUtil.format(quitInfo.getPlanQuitTime().atStartOfDay(), DatePattern.NORM_DATE_PATTERN)) .append("原因:").append(reasonEnum.getQuitType().getName()).append("-").append(reasonEnum.getName()); transContent.append(HrmLanguageEnum.RESIGNATION_APPLY.getFieldFormat() + ":").append(DateUtil.format(quitInfo.getApplyQuitTime().atStartOfDay(), DatePattern.NORM_DATE_PATTERN)) .append(HrmLanguageEnum.PLANNED_TERMINATION_DATE.getFieldFormat() + ":").append(DateUtil.format(quitInfo.getPlanQuitTime().atStartOfDay(), DatePattern.NORM_DATE_PATTERN)) .append(HrmLanguageEnum.REASON.getFieldFormat() + ":").append(reasonEnum.getQuitType().getName()).append("-").append(reasonEnum.getName()); } if (StrUtil.isNotEmpty(quitInfo.getRemarks())) { content.append(",备注:").append(quitInfo.getRemarks()); transContent.append("," + HrmLanguageEnum.REMARK.getFieldFormat() + ":").append(quitInfo.getRemarks()); } actionRecordService.saveRecord(actionTypeEnum, HrmActionBehaviorEnum.QUIT, Collections.singletonList(content.toString()), Collections.singletonList(transContent.toString()), quitInfo.getEmployeeId()); return new Content(employee.getEmployeeName(), content.toString(), transContent.toString(), BehaviorEnum.UPDATE); } /** * 员工个人信息其他表更新 具体看 labelGroupEnum * * @param labelGroupEnum * @param oldRecord * @param newRecord * @param employeeId */ public Content entityUpdateRecord(LabelGroupEnum labelGroupEnum, Map<String, Object> oldRecord, Map<String, Object> newRecord, Long employeeId) { Dict properties = propertiesMap.get(labelGroupEnum); HrmActionRecordListBO recordListBO = entityCommonUpdateRecord(labelGroupEnum, properties, oldRecord, newRecord); actionRecordService.saveRecord(actionTypeEnum, HrmActionBehaviorEnum.UPDATE, recordListBO.getContentList(), recordListBO.getTransContentList(), employeeId); HrmEmployee employee = employeeService.getById(employeeId); return new Content(employee.getEmployeeName(), CollUtil.join(recordListBO.getContentList(), ","), CollUtil.join(recordListBO.getTransContentList(), ","), BehaviorEnum.UPDATE); } /** * 修改参保方案 */ public Content updateSchemeRecord(HrmInsuranceScheme oldInsuranceScheme, HrmInsuranceScheme newInsuranceScheme, HrmEmployee employee) { String oldSchemeName; String newSchemeName; String transOldSchemeName; String transNewSchemeName; if (oldInsuranceScheme == null) { oldSchemeName = "空"; transOldSchemeName = LanguageFieldEnum.ACTIONRECORD_EMPTY.getFieldFormat(); } else { oldSchemeName = oldInsuranceScheme.getSchemeName(); transOldSchemeName = oldInsuranceScheme.getSchemeName(); } if (newInsuranceScheme == null) { newSchemeName = "空"; transNewSchemeName = LanguageFieldEnum.ACTIONRECORD_EMPTY.getFieldFormat(); } else { newSchemeName = newInsuranceScheme.getSchemeName(); transNewSchemeName = newInsuranceScheme.getSchemeName(); } String content = "为" + employee.getEmployeeName() + "修改了参保方案,由【" + oldSchemeName + "】修改为【" + " " + employee.getEmployeeName() + newSchemeName + "】"; String transContent = " " + employee.getEmployeeName() + HrmActionBehaviorEnum.UPDATE.getFieldFormat() + " " + HrmLanguageEnum.INSURANCE_SCHEME.getFieldFormat() + ", 【" + transOldSchemeName + "】" + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + "【" + transNewSchemeName + "】"; actionRecordService.saveRecord(actionTypeEnum, HrmActionBehaviorEnum.UPDATE, Collections.singletonList(content), Collections.singletonList(transContent), employee.getEmployeeId()); return new Content(employee.getEmployeeName(), content, transContent, BehaviorEnum.UPDATE); } @Override protected String compare(LabelGroupEnum labelGroupEnum, Dict properties, String newFieldKey, String oldValue, String newValue) { String content = super.compare(labelGroupEnum, properties, newFieldKey, oldValue, newValue); switch (labelGroupEnum) { case EDUCATIONAL_EXPERIENCE: String education = "education"; String teachingMethods = "teachingMethods"; String isFirstDegree = "isFirstDegree"; if (education.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = EmployeeEducationEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = EmployeeEducationEnum.parseName(Integer.parseInt(newValue)); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } else if (teachingMethods.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = TeachingMethodsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = TeachingMethodsEnum.parseName(Integer.parseInt(newValue)); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } else if (isFirstDegree.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } break; case QUIT: String quitType = "quitType"; String quitReason = "quitReason"; if (quitType.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = QuitTypeEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = QuitTypeEnum.parseName(Integer.parseInt(newValue)); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } else if (quitReason.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = QuitReasonEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = QuitReasonEnum.parseName(Integer.parseInt(newValue)); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } break; case SOCIAL_SECURITY: String isFirstSocialSecurity = "isFirstSocialSecurity"; String isFirstAccumulationFund = "isFirstAccumulationFund"; String schemeId = "schemeId"; if (isFirstSocialSecurity.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && !NULL.equals(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && !NULL.equals(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } else if (isFirstAccumulationFund.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } else if (schemeId.equals(newFieldKey)) { HrmInsuranceScheme oldScheme = insuranceSchemeService.getById(oldValue); HrmInsuranceScheme newScheme = insuranceSchemeService.getById(newValue); if (oldScheme != null) { oldValue = oldScheme.getSchemeName(); } if (newScheme != null) { newValue = newScheme.getSchemeName(); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } break; case CONTRACT: String contractType = "contractType"; String status = "status"; String isExpireRemind = "isExpireRemind"; if (contractType.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = EmployeeContractType.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = EmployeeContractType.parseName(Integer.parseInt(newValue)); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } else if (status.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = EmployeeContractStatus.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = EmployeeContractStatus.parseName(Integer.parseInt(newValue)); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } else if (isExpireRemind.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = "将" + properties.getStr(newFieldKey) + "由" + oldValue + "改为" + newValue; } break; default: break; } return content; } @Override protected String transCompare(LabelGroupEnum labelGroupEnum, Dict properties, String newFieldKey, String oldValue, String newValue) { String content = super.transCompare(labelGroupEnum, properties, newFieldKey, oldValue, newValue); switch (labelGroupEnum) { case EDUCATIONAL_EXPERIENCE: String education = "education"; String teachingMethods = "teachingMethods"; String isFirstDegree = "isFirstDegree"; if (education.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = EmployeeEducationEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = EmployeeEducationEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (teachingMethods.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = TeachingMethodsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = TeachingMethodsEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (isFirstDegree.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } break; case QUIT: String quitType = "quitType"; String quitReason = "quitReason"; if (quitType.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = QuitTypeEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = QuitTypeEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (quitReason.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = QuitReasonEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = QuitReasonEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } break; case SOCIAL_SECURITY: String isFirstSocialSecurity = "isFirstSocialSecurity"; String isFirstAccumulationFund = "isFirstAccumulationFund"; String schemeId = "schemeId"; if (isFirstSocialSecurity.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (isFirstAccumulationFund.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (schemeId.equals(newFieldKey)) { HrmInsuranceScheme oldScheme = insuranceSchemeService.getById(oldValue); HrmInsuranceScheme newScheme = insuranceSchemeService.getById(newValue); if (oldScheme != null) { oldValue = oldScheme.getSchemeName(); } if (newScheme != null) { newValue = newScheme.getSchemeName(); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } break; case CONTRACT: String contractType = "contractType"; String status = "status"; String isExpireRemind = "isExpireRemind"; if (contractType.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = EmployeeContractType.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = EmployeeContractType.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (status.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = EmployeeContractStatus.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = EmployeeContractStatus.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } else if (isExpireRemind.equals(newFieldKey)) { if (!TRANSNULL.equals(oldValue) && StrUtil.isNumeric(oldValue)) { oldValue = IsEnum.parseName(Integer.parseInt(oldValue)); } if (!TRANSNULL.equals(newValue) && StrUtil.isNumeric(newValue)) { newValue = IsEnum.parseName(Integer.parseInt(newValue)); } content = " " + properties.getStr(newFieldKey) + " " + oldValue + LanguageFieldEnum.ACTIONRECORD_UPDATE.getFieldFormat() + newValue; } break; default: break; } return content; } public Content cancelLeave(DeleteLeaveInformationBO deleteLeaveInformationBO) { StringBuilder content = new StringBuilder(); StringBuilder transContent = new StringBuilder(); content.append("取消了离职"); transContent.append(HrmLanguageEnum.CANCEL.getFieldFormat() + " " + HrmLanguageEnum.RESIGNATION.getFieldFormat()); if (StrUtil.isNotEmpty(deleteLeaveInformationBO.getRemarks())) { content.append(",原因:").append(deleteLeaveInformationBO.getRemarks()); transContent.append("," + HrmLanguageEnum.REASON.getFieldFormat() + ":").append(deleteLeaveInformationBO.getRemarks()); } actionRecordService.saveRecord(actionTypeEnum, HrmActionBehaviorEnum.UPDATE, Collections.singletonList(content.toString()), Collections.singletonList(transContent.toString()), deleteLeaveInformationBO.getEmployeeId()); HrmEmployee employee = employeeService.getById(deleteLeaveInformationBO.getEmployeeId()); return new Content(employee.getEmployeeName(), content.toString(), transContent.toString(), BehaviorEnum.UPDATE); } /** * 保存固定字段记录 * * @param oldObj * @param newObj * @param labelGroupEnum * @param employeeId */ public Content employeeFixedFieldRecord(Map<String, Object> oldObj, Map<String, Object> newObj, LabelGroupEnum labelGroupEnum, Long employeeId) { HrmEmployee employee = employeeService.getById(employeeId); try { textList.clear(); transList.clear(); searchChange(textList, transList, oldObj, newObj, labelGroupEnum); if (textList.size() > 0) { actionRecordService.saveRecord(actionTypeEnum, HrmActionBehaviorEnum.UPDATE, textList, transList, employeeId); return new Content(employee.getEmployeeName(), CollUtil.join(textList, ","), CollUtil.join(transList, ","), BehaviorEnum.UPDATE); } } finally { textList.clear(); transList.clear(); } return new Content(employee.getEmployeeName(), "", BehaviorEnum.UPDATE); } /** * 保存非固定字段记录 * * @param newFieldList * @param oldFieldList */
public Content employeeNOFixedFieldRecord(List<UpdateInformationBO.InformationFieldBO> newFieldList, List<HrmModelFiledVO> oldFieldList, Long employeeId) {
9
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,353
private GroupItem getParent(int currentLevel) { GroupItem parent = this.possibleParent; while (parent != null && parent.getLevel() >= currentLevel) { parent = parent.getParent(); } return parent; } @Override public CopybookNode visitDataDescriptionEntryFormat2(DataDescriptionEntryFormat2Context ctx) { return null; } @Override public CopybookNode visitDataDescriptionEntryFormat3(DataDescriptionEntryFormat3Context ctx) { return null; } @Override public CopybookNode visitDataBlankWhenZeroClause(DataBlankWhenZeroClauseContext ctx) { return null; } @Override public CopybookNode visitDataExternalClause(DataExternalClauseContext ctx) { return null; } @Override public CopybookNode visitDataGlobalClause(DataGlobalClauseContext ctx) { return null; } @Override public CopybookNode visitDataJustifiedClause(DataJustifiedClauseContext ctx) { return null; } @Override public CopybookNode visitDataOccursClause(DataOccursClauseContext ctx) { return null; } @Override public CopybookNode visitDataOccursTo(DataOccursToContext ctx) { return null; } @Override public CopybookNode visitDataOccursSort(DataOccursSortContext ctx) { return null; } @Override public CopybookNode visitDataPictureClause(DataPictureClauseContext ctx) { return null; } @Override public CopybookNode visitPictureString(PictureStringContext ctx) { return null; } @Override public CopybookNode visitPictureChars(PictureCharsContext ctx) { return null; } @Override public CopybookNode visitPictureCardinality(PictureCardinalityContext ctx) { return null; } @Override public CopybookNode visitDataRedefinesClause(DataRedefinesClauseContext ctx) { return null; } @Override public CopybookNode visitDataRenamesClause(DataRenamesClauseContext ctx) { return null; } @Override public CopybookNode visitDataSignClause(DataSignClauseContext ctx) { return null; } @Override public CopybookNode visitDataSynchronizedClause(DataSynchronizedClauseContext ctx) { return null; } @Override public CopybookNode visitDataUsageClause(DataUsageClauseContext ctx) { return null; } @Override public CopybookNode visitDataValueClause(DataValueClauseContext ctx) { return null; } @Override public CopybookNode visitDataValueInterval(DataValueIntervalContext ctx) { return null; } @Override public CopybookNode visitDataValueIntervalFrom(DataValueIntervalFromContext ctx) { return null; } @Override public CopybookNode visitDataValueIntervalTo(DataValueIntervalToContext ctx) { return null; } @Override
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.copybook.commons.schema; class SchemaBuilder implements CopybookVisitor<CopybookNode> { private final Schema schema = new Schema(); private GroupItem possibleParent; private final Set<String> redefinedItemNames = new HashSet<>(); private final List<String> errors = new ArrayList<>(); Schema getSchema() { return this.schema; } @Override public CopybookNode visitStartRule(StartRuleContext ctx) { this.possibleParent = null; visitDataDescription(ctx.dataDescription()); for (CopybookNode typedef : this.schema.getTypeDefinitions()) { addRedefinedItems(typedef); } this.schema.addErrors(this.errors); return null; } private void addRedefinedItems(CopybookNode item) { if (this.redefinedItemNames.contains(item.getName())) { this.schema.addRedefinedItem(item); return; } if (item instanceof GroupItem groupItem) { groupItem.getChildren().forEach(this::addRedefinedItems); } } @Override public CopybookNode visitDataDescription(DataDescriptionContext ctx) { for (int i = 0; i < ctx.getChildCount(); i++) { CopybookNode copybookNode = visitDataDescriptionEntry(ctx.dataDescriptionEntry(i)); if (copybookNode instanceof GroupItem groupItem) { this.possibleParent = groupItem; } if (isRootLevelNode(copybookNode)) { this.schema.addTypeDefinition(copybookNode); } } return null; } private boolean isRootLevelNode(CopybookNode copybookNode) { return copybookNode != null && copybookNode.getLevel() == 1; } @Override public CopybookNode visitDataDescriptionEntry(DataDescriptionEntryContext ctx) { if (ctx.dataDescriptionEntryFormat1() != null) { return visitDataDescriptionEntryFormat1(ctx.dataDescriptionEntryFormat1()); } // skipping level 66 and 88 return null; } @Override public CopybookNode visitDataDescriptionEntryFormat1(DataDescriptionEntryFormat1Context ctx) { if (ctx.LEVEL_NUMBER_77() != null) { // skipping level 77 return null; } boolean redefines = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0) != null; String redefinedItemName = null; if (redefines) { redefinedItemName = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0).dataName().getText(); this.redefinedItemNames.add(redefinedItemName); } int level = Integer.parseInt(ctx.INTEGERLITERAL().getText()); String name = ctx.dataName() != null ? ctx.dataName().getText() : ctx.FILLER().getText(); DataPictureClauseContext pictureClause = ctx.dataDescriptionEntryClauses().dataPictureClause(0); DataOccursClauseContext occursClause = ctx.dataDescriptionEntryClauses().dataOccursClause(0); int occurs = Utils.getOccurringCount(occursClause); if (pictureClause == null || pictureClause.pictureString() == null) { return new GroupItem(level, name, occurs, redefinedItemName, getParent(level)); } PictureStringContext pictureType = pictureClause.pictureString(); validatePicture(pictureType); return new DataItem(level, name, Utils.getPictureString(pictureType), Utils.isNumeric(pictureType), Utils.getReadLength(pictureType), occurs, Utils.getFloatingPointLength(pictureType), redefinedItemName, getParent(level)); } private void validatePicture(PictureStringContext pictureType) { String pictureString = Utils.getPictureString(pictureType); if (PictureStringValidator.isSupportedPictureString(pictureString)) { return; } String errorMsg = "Unsupported picture string '" + pictureString + "' found in copybook schema"; this.addError(pictureType.start.getLine(), pictureType.start.getCharPositionInLine(), errorMsg); } private void addError(int line, int charPositionInLine, String msg) { this.errors.add("Error at line " + line + ", column " + charPositionInLine + ": " + msg); } @Override public CopybookNode visitDataDescriptionEntryClauses(DataDescriptionEntryClausesContext ctx) { return null; } private GroupItem getParent(int currentLevel) { GroupItem parent = this.possibleParent; while (parent != null && parent.getLevel() >= currentLevel) { parent = parent.getParent(); } return parent; } @Override public CopybookNode visitDataDescriptionEntryFormat2(DataDescriptionEntryFormat2Context ctx) { return null; } @Override public CopybookNode visitDataDescriptionEntryFormat3(DataDescriptionEntryFormat3Context ctx) { return null; } @Override public CopybookNode visitDataBlankWhenZeroClause(DataBlankWhenZeroClauseContext ctx) { return null; } @Override public CopybookNode visitDataExternalClause(DataExternalClauseContext ctx) { return null; } @Override public CopybookNode visitDataGlobalClause(DataGlobalClauseContext ctx) { return null; } @Override public CopybookNode visitDataJustifiedClause(DataJustifiedClauseContext ctx) { return null; } @Override public CopybookNode visitDataOccursClause(DataOccursClauseContext ctx) { return null; } @Override public CopybookNode visitDataOccursTo(DataOccursToContext ctx) { return null; } @Override public CopybookNode visitDataOccursSort(DataOccursSortContext ctx) { return null; } @Override public CopybookNode visitDataPictureClause(DataPictureClauseContext ctx) { return null; } @Override public CopybookNode visitPictureString(PictureStringContext ctx) { return null; } @Override public CopybookNode visitPictureChars(PictureCharsContext ctx) { return null; } @Override public CopybookNode visitPictureCardinality(PictureCardinalityContext ctx) { return null; } @Override public CopybookNode visitDataRedefinesClause(DataRedefinesClauseContext ctx) { return null; } @Override public CopybookNode visitDataRenamesClause(DataRenamesClauseContext ctx) { return null; } @Override public CopybookNode visitDataSignClause(DataSignClauseContext ctx) { return null; } @Override public CopybookNode visitDataSynchronizedClause(DataSynchronizedClauseContext ctx) { return null; } @Override public CopybookNode visitDataUsageClause(DataUsageClauseContext ctx) { return null; } @Override public CopybookNode visitDataValueClause(DataValueClauseContext ctx) { return null; } @Override public CopybookNode visitDataValueInterval(DataValueIntervalContext ctx) { return null; } @Override public CopybookNode visitDataValueIntervalFrom(DataValueIntervalFromContext ctx) { return null; } @Override public CopybookNode visitDataValueIntervalTo(DataValueIntervalToContext ctx) { return null; } @Override
public CopybookNode visitIdentifier(IdentifierContext ctx) {
31
2023-10-24 04:51:53+00:00
24k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/CommonProxy.java
[ { "identifier": "DamageEventHandler", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/combat/DamageEventHandler.java", "snippet": "public class DamageEventHandler {\n\n public static final DamageEventHandler instance = new DamageEventHandler();\n\n @SubscribeEvent(priority = EventPriority.HIG...
import net.minecraftforge.common.MinecraftForge; import com.Nxer.TwistSpaceTechnology.combat.DamageEventHandler; import com.Nxer.TwistSpaceTechnology.combat.PlayerEventHandler; import com.Nxer.TwistSpaceTechnology.command.CombatRework_Command; import com.Nxer.TwistSpaceTechnology.command.TST_Command; import com.Nxer.TwistSpaceTechnology.config.Config; import com.Nxer.TwistSpaceTechnology.event.StartServerEvent; import com.Nxer.TwistSpaceTechnology.event.TickingEvent; import com.Nxer.TwistSpaceTechnology.system.DysonSphereProgram.logic.DSP_WorldSavedData; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartedEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent;
15,424
package com.Nxer.TwistSpaceTechnology; public class CommonProxy { // preInit "Run before anything else. Read your config, create blocks, items, etc, and register them with the // GameRegistry." (Remove if not needed) public void preInit(FMLPreInitializationEvent event) { Config.synchronizeConfiguration(event.getSuggestedConfigurationFile()); if (Config.activateCombatStats) {
package com.Nxer.TwistSpaceTechnology; public class CommonProxy { // preInit "Run before anything else. Read your config, create blocks, items, etc, and register them with the // GameRegistry." (Remove if not needed) public void preInit(FMLPreInitializationEvent event) { Config.synchronizeConfiguration(event.getSuggestedConfigurationFile()); if (Config.activateCombatStats) {
MinecraftForge.EVENT_BUS.register(new PlayerEventHandler());
1
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;
15,628
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); } /** * 获取路由注册模式 * * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file] */ public boolean isRouteRegisterMode() { return RouteModuleCenter.isRegisterByPlugin(); } public static synchronized void openDebug() { isDebug = true; logger.showLog(isDebug); logger.info(null, "[openDebug]"); } public static void setApplication(Application application) { mApplication = application; } public static boolean isDebug() { return isDebug; } public static synchronized void printStackTrace() { logger.showStackTrace(true); logger.info(null, "[printStackTrace]"); } public static synchronized void setExecutor(ThreadPoolExecutor tpe) { executor = tpe; } public ThreadPoolExecutor getExecutor() { return executor; } public static void setLogger(ILogger userLogger) { if (userLogger != null) { logger = userLogger; } } /** * 获取模块application注册模式 * * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file] */ public boolean isAMRegisterMode() { return ApplicationModuleCenter.isRegisterByPlugin(); } public static void callAMOnCreate(Application application) { setApplication(application); ApplicationModuleCenter.callOnCreate(application); } public static void callAMOnTerminate() { ApplicationModuleCenter.callOnTerminate(); } public static void callAMOnConfigurationChanged(@NonNull Configuration newConfig) { ApplicationModuleCenter.callOnConfigurationChanged(newConfig); } public static void callAMOnLowMemory() { ApplicationModuleCenter.callOnLowMemory(); } public static void callAMOnTrimMemory(int level) { ApplicationModuleCenter.callOnTrimMemory(level); } /** * 动态注册模块application * * @param am */ public static void registerAM(Class<? extends IApplicationModule> am) { ApplicationModuleCenter.register(am); } /** * 实现相同接口的service会被覆盖(更新) * * @param service 实现类.class */ public void addService(Class<? extends IService> service) { ServiceCenter.addService(service); } /** * 实现相同接口的service会被覆盖(更新) * * @param service 实现类.class * @param alias 别名 */ public void addService(Class<? extends IService> service, String alias) { ServiceCenter.addService(service, alias); } /** * 获取service接口的实现 * * @param service 接口.class * @param <T> * @return */ @Nullable public <T> T getService(Class<? extends T> service) { return ServiceCenter.getService(service); } /** * 获取service接口的实现 * * @param service * @param alias 别名 * @param <T> * @return */ @Nullable public <T> T getService(Class<? extends T> service, String alias) { return ServiceCenter.getService(service, alias); } /** * 重复添加相同序号会catch * * @param ordinal * @param interceptor */
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); } /** * 获取路由注册模式 * * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file] */ public boolean isRouteRegisterMode() { return RouteModuleCenter.isRegisterByPlugin(); } public static synchronized void openDebug() { isDebug = true; logger.showLog(isDebug); logger.info(null, "[openDebug]"); } public static void setApplication(Application application) { mApplication = application; } public static boolean isDebug() { return isDebug; } public static synchronized void printStackTrace() { logger.showStackTrace(true); logger.info(null, "[printStackTrace]"); } public static synchronized void setExecutor(ThreadPoolExecutor tpe) { executor = tpe; } public ThreadPoolExecutor getExecutor() { return executor; } public static void setLogger(ILogger userLogger) { if (userLogger != null) { logger = userLogger; } } /** * 获取模块application注册模式 * * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file] */ public boolean isAMRegisterMode() { return ApplicationModuleCenter.isRegisterByPlugin(); } public static void callAMOnCreate(Application application) { setApplication(application); ApplicationModuleCenter.callOnCreate(application); } public static void callAMOnTerminate() { ApplicationModuleCenter.callOnTerminate(); } public static void callAMOnConfigurationChanged(@NonNull Configuration newConfig) { ApplicationModuleCenter.callOnConfigurationChanged(newConfig); } public static void callAMOnLowMemory() { ApplicationModuleCenter.callOnLowMemory(); } public static void callAMOnTrimMemory(int level) { ApplicationModuleCenter.callOnTrimMemory(level); } /** * 动态注册模块application * * @param am */ public static void registerAM(Class<? extends IApplicationModule> am) { ApplicationModuleCenter.register(am); } /** * 实现相同接口的service会被覆盖(更新) * * @param service 实现类.class */ public void addService(Class<? extends IService> service) { ServiceCenter.addService(service); } /** * 实现相同接口的service会被覆盖(更新) * * @param service 实现类.class * @param alias 别名 */ public void addService(Class<? extends IService> service, String alias) { ServiceCenter.addService(service, alias); } /** * 获取service接口的实现 * * @param service 接口.class * @param <T> * @return */ @Nullable public <T> T getService(Class<? extends T> service) { return ServiceCenter.getService(service); } /** * 获取service接口的实现 * * @param service * @param alias 别名 * @param <T> * @return */ @Nullable public <T> T getService(Class<? extends T> service, String alias) { return ServiceCenter.getService(service, alias); } /** * 重复添加相同序号会catch * * @param ordinal * @param interceptor */
public void addInterceptor(int ordinal, Class<? extends IInterceptor> interceptor) {
15
2023-10-18 13:52:07+00:00
24k
trpc-group/trpc-java
trpc-core/src/main/java/com/tencent/trpc/core/cluster/def/DefClusterInvokerMockWrapper.java
[ { "identifier": "ClusterInvoker", "path": "trpc-core/src/main/java/com/tencent/trpc/core/cluster/ClusterInvoker.java", "snippet": "public interface ClusterInvoker<T> extends Invoker<T> {\n\n Class<T> getInterface();\n\n ConsumerConfig<T> getConfig();\n\n BackendConfig getBackendConfig();\n\n}" ...
import com.tencent.trpc.core.cluster.ClusterInvoker; import com.tencent.trpc.core.common.config.BackendConfig; import com.tencent.trpc.core.common.config.ConsumerConfig; import com.tencent.trpc.core.logger.Logger; import com.tencent.trpc.core.logger.LoggerFactory; 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.RpcInvocation; import com.tencent.trpc.core.rpc.common.RpcMethodInfo; import com.tencent.trpc.core.utils.RpcUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils;
14,491
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.core.cluster.def; public class DefClusterInvokerMockWrapper<T> implements ClusterInvoker<T> { private static final Logger logger = LoggerFactory.getLogger(DefClusterInvokerMockWrapper.class); private final ClusterInvoker<T> invoker; public DefClusterInvokerMockWrapper(ClusterInvoker<T> invoker) { this.invoker = invoker; } @Override public Class<T> getInterface() { return invoker.getInterface(); } @Override public CompletionStage<Response> invoke(Request request) {
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.core.cluster.def; public class DefClusterInvokerMockWrapper<T> implements ClusterInvoker<T> { private static final Logger logger = LoggerFactory.getLogger(DefClusterInvokerMockWrapper.class); private final ClusterInvoker<T> invoker; public DefClusterInvokerMockWrapper(ClusterInvoker<T> invoker) { this.invoker = invoker; } @Override public Class<T> getInterface() { return invoker.getInterface(); } @Override public CompletionStage<Response> invoke(Request request) {
ConsumerConfig<T> consumerConfig = invoker.getConfig();
2
2023-10-19 10:54:11+00:00
24k
eclipse-jgit/jgit
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Archive.java
[ { "identifier": "ArchiveCommand", "path": "org.eclipse.jgit/src/org/eclipse/jgit/api/ArchiveCommand.java", "snippet": "public class ArchiveCommand extends GitCommand<OutputStream> {\n\t/**\n\t * Archival format.\n\t *\n\t * Usage:\n\t *\tRepository repo = git.getRepository();\n\t *\tT out = format.creat...
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import org.eclipse.jgit.api.ArchiveCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.archive.ArchiveFormats; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.pgm.internal.CLIText; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option;
16,827
/* * Copyright (C) 2012 Google Inc. 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(common = true, usage = "usage_archive") class Archive extends TextBuiltin { static { ArchiveFormats.registerAll(); } @Argument(index = 0, metaVar = "metaVar_treeish") private ObjectId tree; @Option(name = "--format", metaVar = "metaVar_archiveFormat", usage = "usage_archiveFormat") private String format; @Option(name = "--prefix", metaVar = "metaVar_archivePrefix", usage = "usage_archivePrefix") private String prefix; @Option(name = "--output", aliases = { "-o" }, metaVar = "metaVar_file", usage = "usage_archiveOutput") private String output; @Override protected void run() throws Exception { if (tree == null) throw die(CLIText.get().treeIsRequired); OutputStream stream = null; try { if (output != null) stream = new FileOutputStream(output); else stream = outs;
/* * Copyright (C) 2012 Google Inc. 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(common = true, usage = "usage_archive") class Archive extends TextBuiltin { static { ArchiveFormats.registerAll(); } @Argument(index = 0, metaVar = "metaVar_treeish") private ObjectId tree; @Option(name = "--format", metaVar = "metaVar_archiveFormat", usage = "usage_archiveFormat") private String format; @Option(name = "--prefix", metaVar = "metaVar_archivePrefix", usage = "usage_archivePrefix") private String prefix; @Option(name = "--output", aliases = { "-o" }, metaVar = "metaVar_file", usage = "usage_archiveOutput") private String output; @Override protected void run() throws Exception { if (tree == null) throw die(CLIText.get().treeIsRequired); OutputStream stream = null; try { if (output != null) stream = new FileOutputStream(output); else stream = outs;
try (Git git = new Git(db)) {
1
2023-10-20 15:09:17+00:00
24k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/HandleDialogFragment.java
[ { "identifier": "DBHelper", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/DBHelper.java", "snippet": "public class DBHelper extends SQLiteOpenHelper {\n\tprivate static final String DB_NAME = \"actions.db\";\n\tprivate static final int DB_VERSION = 10;\n\tpublic static final String ACTION_TA...
import android.annotation.TargetApi; import android.app.Activity; import android.app.Dialog; import android.app.usage.StorageStats; import android.app.usage.StorageStatsManager; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.AdaptiveIconDrawable; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.Process; import android.os.storage.StorageManager; import android.os.storage.StorageVolume; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.format.Formatter; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.tencent.mars.xlog.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.UUID; import cn.wq.myandroidtoolspro.BuildConfig; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.DBHelper; import cn.wq.myandroidtoolspro.helper.ShizukuUtil; import cn.wq.myandroidtoolspro.helper.Utils; 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.Consumer; import io.reactivex.schedulers.Schedulers; import moe.shizuku.api.ShizukuPackageManagerV26;
15,560
new PkgSizeObserver()); } catch (Exception e) { e.printStackTrace(); } } else { loadUsageDataForO(); } if (BuildConfig.isFree) { clearCacheBtn.setVisibility(View.GONE); clearDataBtn.setVisibility(View.GONE); } ///////////////////////////////////////////// ///////////////////////////////////////////// AlertDialog.Builder builder = new AlertDialog.Builder(getContext()) .setCustomTitle(dialog_title) .setView(dialog_content); return builder.create(); } //android 8.0+之后获取使用大小 //https://stackoverflow.com/questions/43472398/how-to-use-storagestatsmanager-querystatsforpackage-on-android-o @TargetApi(Build.VERSION_CODES.O) private void loadUsageDataForO() { Disposable disposable = Observable.create(new ObservableOnSubscribe<DataModel>() { @Override public void subscribe(ObservableEmitter<DataModel> emitter) { StorageStatsManager storageStatsManager = (StorageStatsManager) getContext().getSystemService(Context.STORAGE_STATS_SERVICE); StorageManager storageManager = (StorageManager) getContext().getSystemService(Context.STORAGE_SERVICE); List<StorageVolume> volumes = storageManager.getStorageVolumes(); long cacheBytes = 0; long dataBytes = 0; for (StorageVolume vol : volumes) { try { //sony 有问题,https://play.google.com/apps/publish/?hl=zh-CN&account=7732266320238141460#AndroidMetricsErrorsPlace:p=cn.wq.myandroidtools&appVersion=PRODUCTION&lastReportedRange=LAST_24_HRS&showHidden=true&clusterName=apps/cn.wq.myandroidtools/clusters/f6372709&detailsSpan=1 UUID uuid = vol.getUuid() == null ? StorageManager.UUID_DEFAULT : UUID.fromString(vol.getUuid()); // Log.d("AppLog", "storage:" + uuid + " : " + vol.getDescription(getContext()) + " : " + vol.getState()); // Log.d("AppLog", "getFreeBytes:" + Formatter.formatShortFileSize(getContext(), storageStatsManager.getFreeBytes(uuid))); // Log.d("AppLog", "getTotalBytes:" + Formatter.formatShortFileSize(getContext(), storageStatsManager.getTotalBytes(uuid))); // Log.d("AppLog", "storage stats for app of package name:" + packageNameString + " : "); final StorageStats storageStats = storageStatsManager.queryStatsForPackage(uuid, packageNameString, Process.myUserHandle()); cacheBytes += storageStats.getCacheBytes(); dataBytes += storageStats.getDataBytes(); // Log.d("AppLog", "getAppBytes:" + Formatter.formatShortFileSize(getContext(), storageStats.getAppBytes()) + // " getCacheBytes:" + Formatter.formatShortFileSize(getContext(), storageStats.getCacheBytes()) + // " getDataBytes:" + Formatter.formatShortFileSize(getContext(), storageStats.getDataBytes())); } catch (Exception e) { e.printStackTrace(); } } emitter.onNext(new DataModel(cacheBytes, dataBytes)); emitter.onComplete(); } }) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<DataModel>() { @Override public void accept(DataModel dataModel) { updateUsageViews(dataModel.dataBytes, dataModel.cacheBytes); } }); compositeDisposable.add(disposable); } class DataModel { long cacheBytes = 0; long dataBytes = 0; DataModel(long cacheBytes, long dataBytes) { this.cacheBytes = cacheBytes; this.dataBytes = dataBytes; } } class PkgInfo { String sourceDir, version; boolean isSystem; } private void toAppDetailInSystemSettings(String packageName) { Intent intent = new Intent(); if (Build.VERSION.SDK_INT >= 9) { intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = // Uri.fromParts("package", packageName, null) Uri.parse("package:" + packageName); intent.setData(uri); } else { String appPkgName = Build.VERSION.SDK_INT == 8 ? "pkg" : "com.android.settings.ApplicationPkgName"; intent.setAction(Intent.ACTION_VIEW); intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); intent.putExtra(appPkgName, packageName); } startActivity(intent); } private void uninstall() { new AsyncTask<String, Void, Boolean>() { private byte[] bitmapToBytes(Bitmap bitmap) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bout); return bout.toByteArray(); } @Override protected Boolean doInBackground(String... param) { if (sourceDir == null) { return Utils.runRootCommand("pm uninstall " + packageNameString); } boolean result; if (sourceDir.startsWith("/data/app")) { result = Utils.runRootCommand("pm uninstall " + packageNameString); if (result) {
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class HandleDialogFragment extends DialogFragment { private static final String TAG = "HandleDialogFragment"; private boolean isDisabled; private String packageNameString; private String labelString; private Context mContext; private String sourceDir; private final LoadUsageHandler mHandler = new LoadUsageHandler(); private TextView dataTv, cacheTv, apkPath, packageNameTitle, version; private Button clearDataBtn, clearCacheBtn; private View storageParent; private static final int REQUEST_CODE_UNINSTALL = 1001; private CompositeDisposable compositeDisposable = new CompositeDisposable(); private class PkgSizeObserver extends IPackageStatsObserver.Stub { public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) { // android o(8.0会返回 false 和 null) // http://blog.leanote.com/post/svenpaper/Android-O-%E7%89%88%E6%9C%AC%E5%AE%89%E8%A3%85%E5%8C%85%E5%A4%A7%E5%B0%8F%E8%8E%B7%E5%8F%96%E5%A4%B1%E8%B4%A5%E9%97%AE%E9%A2%98%E5%88%86%E6%9E%90%E5%8F%8A%E8%A7%A3%E5%86%B3 if (!succeeded || pStats == null) { Utils.debug("package size return:" + succeeded + "," + (pStats == null)); return; } Message msg = mHandler.obtainMessage(1); Bundle data = new Bundle(); // data.putLong("codeSize",pStats.codeSize); data.putLong("dataSize", pStats.dataSize); data.putLong("cacheSize", pStats.cacheSize); msg.setData(data); mHandler.sendMessage(msg); } } @Override public void onDestroy() { super.onDestroy(); if (compositeDisposable != null) { compositeDisposable.clear(); } } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { mContext = getContext(); Bundle args = getArguments(); packageNameString = args.getString("packageName"); isDisabled = args.getBoolean("isDisabled"); labelString = args.getString("label"); LayoutInflater inflater = LayoutInflater.from(mContext); View dialog_title = inflater.inflate(R.layout.dialog_app_manage_handle_title, null); View dialog_content = inflater.inflate(R.layout.dialog_app_manage_handle, null); ImageView icon = (ImageView) dialog_title.findViewById(R.id.icon); TextView label = (TextView) dialog_title.findViewById(R.id.label); version = (TextView) dialog_title.findViewById(R.id.version); ImageView info = (ImageView) dialog_title.findViewById(R.id.info); TextView last_update_time = (TextView) dialog_content.findViewById(R.id.last_update_time); TextView packageName = (TextView) dialog_content.findViewById(R.id.package_name); apkPath = (TextView) dialog_content.findViewById(R.id.apk_path); packageNameTitle = (TextView) dialog_content.findViewById(R.id.package_name_title); Utils.loadApkIcon(this, packageNameString, icon); Disposable disposable = Observable.create(new ObservableOnSubscribe<PkgInfo>() { @Override public void subscribe(ObservableEmitter<PkgInfo> emitter) throws Exception { PackageManager pm = mContext.getPackageManager(); PkgInfo pkgInfo = new PkgInfo(); ApplicationInfo aInfo = pm.getApplicationInfo(packageNameString, 0); pkgInfo.sourceDir = aInfo.sourceDir; pkgInfo.isSystem = (aInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0; PackageInfo pInfo = pm.getPackageInfo(packageNameString, 0); if (pInfo != null) { long verionCode; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) { verionCode = pInfo.getLongVersionCode(); } else { verionCode = pInfo.versionCode; } pkgInfo.version = verionCode + " (" + pInfo.versionName + ")"; } emitter.onNext(pkgInfo); emitter.onComplete(); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<PkgInfo>() { @Override public void accept(PkgInfo pkgInfo) { apkPath.setText(pkgInfo.sourceDir); sourceDir = pkgInfo.sourceDir; if (pkgInfo.isSystem) { packageNameTitle.setText(R.string.package_name_system); } else { packageNameTitle.setText(R.string.package_name_third_party); } version.setText(pkgInfo.version); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { throwable.printStackTrace(); } }); compositeDisposable.add(disposable); PackageManager pm = mContext.getPackageManager(); label.setText(labelString); packageName.setText(packageNameString); last_update_time.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(new Date(args.getLong("time")))); info.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toAppDetailInSystemSettings(packageNameString); } }); final Button disableBtn = (Button) dialog_content.findViewById(R.id.disable); Button all_infos = (Button) dialog_content.findViewById(R.id.all_infos); Button uninstall = (Button) dialog_content.findViewById(R.id.uninstall); Button openBtn = (Button) dialog_content.findViewById(R.id.open); disableBtn.setText(isDisabled ? R.string.enable : R.string.disable); disableBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { disable(false); } }); all_infos.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Fragment targetFragment = getTargetFragment(); if (targetFragment instanceof AppForManageRecyclerFragment) { //currentFocus是SearchView$SearchAutoComplete,不是SearchView,但是只有后者clearFocus才有效 ((AppForManageRecyclerFragment) targetFragment).clearSearchViewFocus(); } dismissAllowingStateLoss(); Bundle args = new Bundle(); args.putString("packageName", packageNameString); args.putString("title", labelString); args.putBoolean("part", true); AppInfoForManageFragment2 fragment = AppInfoForManageFragment2.newInstance(args); AppCompatActivity activity = (AppCompatActivity) getActivity(); FragmentTransaction ft = activity.getSupportFragmentManager() .beginTransaction(); ft.replace(R.id.content, fragment); ft.setTransition(FragmentTransaction.TRANSIT_NONE); ft.addToBackStack(null); ft.commit(); } }); if (BuildConfig.isFree) { uninstall.setVisibility(View.GONE); openBtn.setVisibility(View.GONE); } else { uninstall.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EnsureDialogFragment dialog = EnsureDialogFragment.newInstance(getString(R.string.warning), getString(R.string.uninstall_message, labelString)); dialog.setTargetFragment(HandleDialogFragment.this, REQUEST_CODE_UNINSTALL); // dialog.show(getChildFragmentManager(), "uninstall"); dialog.show(getFragmentManager(), "uninstall"); } }); if (!isDisabled) { final Intent startIntent = getContext().getPackageManager().getLaunchIntentForPackage(packageNameString); if (startIntent != null) { openBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(startIntent); } }); } else { openBtn.setEnabled(false); } } else { openBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { disable(true); } }); } } ///////////////////////////////////////////// /// get cache ///////////////////////////////////////////// dataTv = (TextView) dialog_content.findViewById(R.id.data_size); cacheTv = (TextView) dialog_content.findViewById(R.id.cache_size); storageParent = dialog_content.findViewById(R.id.storage_parent); clearDataBtn = (Button) dialog_content.findViewById(R.id.clear_data); clearCacheBtn = (Button) dialog_content.findViewById(R.id.clear_cache); // handlerThread = new HandlerThread("calculate", Process.THREAD_PRIORITY_BACKGROUND); // handlerThread.start(); // mHandler = new LoadUsageHandler(handlerThread.getLooper()); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { //8.0 try { Method getPackageSizeInfo = pm.getClass() .getMethod("getPackageSizeInfo", String.class, IPackageStatsObserver.class); getPackageSizeInfo.invoke(pm, packageNameString, new PkgSizeObserver()); } catch (Exception e) { e.printStackTrace(); } } else { loadUsageDataForO(); } if (BuildConfig.isFree) { clearCacheBtn.setVisibility(View.GONE); clearDataBtn.setVisibility(View.GONE); } ///////////////////////////////////////////// ///////////////////////////////////////////// AlertDialog.Builder builder = new AlertDialog.Builder(getContext()) .setCustomTitle(dialog_title) .setView(dialog_content); return builder.create(); } //android 8.0+之后获取使用大小 //https://stackoverflow.com/questions/43472398/how-to-use-storagestatsmanager-querystatsforpackage-on-android-o @TargetApi(Build.VERSION_CODES.O) private void loadUsageDataForO() { Disposable disposable = Observable.create(new ObservableOnSubscribe<DataModel>() { @Override public void subscribe(ObservableEmitter<DataModel> emitter) { StorageStatsManager storageStatsManager = (StorageStatsManager) getContext().getSystemService(Context.STORAGE_STATS_SERVICE); StorageManager storageManager = (StorageManager) getContext().getSystemService(Context.STORAGE_SERVICE); List<StorageVolume> volumes = storageManager.getStorageVolumes(); long cacheBytes = 0; long dataBytes = 0; for (StorageVolume vol : volumes) { try { //sony 有问题,https://play.google.com/apps/publish/?hl=zh-CN&account=7732266320238141460#AndroidMetricsErrorsPlace:p=cn.wq.myandroidtools&appVersion=PRODUCTION&lastReportedRange=LAST_24_HRS&showHidden=true&clusterName=apps/cn.wq.myandroidtools/clusters/f6372709&detailsSpan=1 UUID uuid = vol.getUuid() == null ? StorageManager.UUID_DEFAULT : UUID.fromString(vol.getUuid()); // Log.d("AppLog", "storage:" + uuid + " : " + vol.getDescription(getContext()) + " : " + vol.getState()); // Log.d("AppLog", "getFreeBytes:" + Formatter.formatShortFileSize(getContext(), storageStatsManager.getFreeBytes(uuid))); // Log.d("AppLog", "getTotalBytes:" + Formatter.formatShortFileSize(getContext(), storageStatsManager.getTotalBytes(uuid))); // Log.d("AppLog", "storage stats for app of package name:" + packageNameString + " : "); final StorageStats storageStats = storageStatsManager.queryStatsForPackage(uuid, packageNameString, Process.myUserHandle()); cacheBytes += storageStats.getCacheBytes(); dataBytes += storageStats.getDataBytes(); // Log.d("AppLog", "getAppBytes:" + Formatter.formatShortFileSize(getContext(), storageStats.getAppBytes()) + // " getCacheBytes:" + Formatter.formatShortFileSize(getContext(), storageStats.getCacheBytes()) + // " getDataBytes:" + Formatter.formatShortFileSize(getContext(), storageStats.getDataBytes())); } catch (Exception e) { e.printStackTrace(); } } emitter.onNext(new DataModel(cacheBytes, dataBytes)); emitter.onComplete(); } }) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<DataModel>() { @Override public void accept(DataModel dataModel) { updateUsageViews(dataModel.dataBytes, dataModel.cacheBytes); } }); compositeDisposable.add(disposable); } class DataModel { long cacheBytes = 0; long dataBytes = 0; DataModel(long cacheBytes, long dataBytes) { this.cacheBytes = cacheBytes; this.dataBytes = dataBytes; } } class PkgInfo { String sourceDir, version; boolean isSystem; } private void toAppDetailInSystemSettings(String packageName) { Intent intent = new Intent(); if (Build.VERSION.SDK_INT >= 9) { intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = // Uri.fromParts("package", packageName, null) Uri.parse("package:" + packageName); intent.setData(uri); } else { String appPkgName = Build.VERSION.SDK_INT == 8 ? "pkg" : "com.android.settings.ApplicationPkgName"; intent.setAction(Intent.ACTION_VIEW); intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); intent.putExtra(appPkgName, packageName); } startActivity(intent); } private void uninstall() { new AsyncTask<String, Void, Boolean>() { private byte[] bitmapToBytes(Bitmap bitmap) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bout); return bout.toByteArray(); } @Override protected Boolean doInBackground(String... param) { if (sourceDir == null) { return Utils.runRootCommand("pm uninstall " + packageNameString); } boolean result; if (sourceDir.startsWith("/data/app")) { result = Utils.runRootCommand("pm uninstall " + packageNameString); if (result) {
SQLiteDatabase db = DBHelper.getInstance(mContext).getWritableDatabase();
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;
20,630
throw new IllegalStateException("createNewFile: " + traceFile); } traceHookRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(traceFile.toPath())), true); traceHookRedirectStream.printf("[%s]Start traceCode: 0x%x-0x%x%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), begin, end); System.out.printf("Set trace 0x%x->0x%x instructions success with trace file: %s.%n", begin, end, traceFile.getAbsolutePath()); } else { System.out.printf("Set trace 0x%x->0x%x instructions success.%n", begin, end); } } } else { String redirect = null; Module module = memory.findModuleByAddress(address); { int index = line.indexOf(' '); if (index != -1) { redirect = line.substring(index + 1).trim(); } } File traceFile = null; if (redirect != null && redirect.trim().length() > 0) { Module check = memory.findModule(redirect); if (check != null) { module = check; } else { File outFile = new File(redirect.trim()); try { if (!outFile.exists() && !outFile.createNewFile()) { throw new IllegalStateException("createNewFile: " + outFile); } traceHookRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(outFile.toPath())), true); traceHookRedirectStream.printf("[%s]Start trace %s%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), module == null ? "all" : module); traceFile = outFile; } catch (IOException e) { System.err.println("Set trace redirect out file failed: " + outFile); return false; } } } begin = module == null ? 1 : module.base; end = module == null ? 0 : (module.base + module.size); System.out.println("Set trace " + (module == null ? "all" : module) + " instructions success" + (traceFile == null ? "." : (" with trace file: " + traceFile.getAbsolutePath()))); } traceHook = new AssemblyCodeDumper(emulator, begin, end, null); if (traceHookRedirectStream != null) { traceHook.setRedirect(traceHookRedirectStream); } emulator.getBackend().hook_add_new(traceHook, begin, end, emulator); return false; } if (line.startsWith("vm")) { Memory memory = emulator.getMemory(); String maxLengthSoName = memory.getMaxLengthLibraryName(); StringBuilder sb = new StringBuilder(); String filter = null; { int index = line.indexOf(' '); if (index != -1) { filter = line.substring(index + 1).trim(); } } int index = 0; long filterAddress = -1; if (filter != null && filter.startsWith("0x")) { filterAddress = Utils.parseNumber(filter); } for (Module module : memory.getLoadedModules()) { if (filter == null || module.getPath().toLowerCase().contains(filter.toLowerCase()) || (filterAddress >= module.base && filterAddress < module.base + module.size)) { sb.append(String.format("[%3s][%" + maxLengthSoName.length() + "s] ", index++, FilenameUtils.getName(module.name))); sb.append(String.format("[0x%0" + Long.toHexString(memory.getMaxSizeOfLibrary()).length() + "x-0x%x]", module.getBaseHeader(), module.base + module.size)); sb.append(module.getPath()); sb.append("\n"); } } if (index == 0) { System.err.println("Find loaded library failed with filter: " + filter); } else { System.out.println(sb); } return false; } if ("vbs".equals(line)) { // view breakpoints Memory memory = emulator.getMemory(); StringBuilder sb = new StringBuilder("* means temporary bp:\n"); String maxLengthSoName = memory.getMaxLengthLibraryName(); for (Map.Entry<Long, BreakPoint> entry : breakMap.entrySet()) { address = entry.getKey(); BreakPoint bp = entry.getValue(); Instruction ins = null; try { byte[] code = backend.mem_read(address, 4); Instruction[] insns = emulator.disassemble(address, code, bp.isThumb(), 1); if (insns != null && insns.length > 0) { ins = insns[0]; } } catch(Exception ignored) {} if (ins == null) { sb.append(String.format("[%" + String.valueOf(maxLengthSoName).length() + "s]", "0x" + Long.toHexString(address))); if (bp.isTemporary()) { sb.append('*'); } } else { sb.append(ARM.assembleDetail(emulator, ins, address, bp.isThumb(), bp.isTemporary(), memory.getMaxLengthLibraryName().length())); } sb.append("\n"); } System.out.println(sb); return false; } if ("stop".equals(line)) { backend.emu_stop(); return true; } if ("s".equals(line) || "si".equals(line)) { setSingleStep(1); return true; } if ("nb".equals(line)) { if (!blockHooked) { blockHooked = true;
package com.github.unidbg.arm; public abstract class AbstractARMDebugger implements Debugger { private static final Log log = LogFactory.getLog(AbstractARMDebugger.class); private final Map<Long, BreakPoint> breakMap = new LinkedHashMap<>(); protected final Emulator<?> emulator; protected AbstractARMDebugger(Emulator<?> emulator) { this.emulator = emulator; } private final List<UnHook> unHookList = new ArrayList<>(); @Override public void onAttach(UnHook unHook) { unHookList.add(unHook); } @Override public void detach() { for (Iterator<UnHook> iterator = unHookList.iterator(); iterator.hasNext(); ) { iterator.next().unhook(); iterator.remove(); } } @Override public final BreakPoint addBreakPoint(Module module, String symbol) { Symbol sym = module.findSymbolByName(symbol, false); if (sym == null) { throw new IllegalStateException("find symbol failed: " + symbol); } return addBreakPoint(module, sym.getValue()); } @Override public final BreakPoint addBreakPoint(Module module, String symbol, BreakPointCallback callback) { Symbol sym = module.findSymbolByName(symbol, false); if (sym == null) { throw new IllegalStateException("find symbol failed: " + symbol); } return addBreakPoint(module, sym.getValue(), callback); } @Override public final BreakPoint addBreakPoint(Module module, long offset) { long address = module == null ? offset : module.base + offset; return addBreakPoint(address); } @Override public final BreakPoint addBreakPoint(Module module, long offset, BreakPointCallback callback) { long address = module == null ? offset : module.base + offset; return addBreakPoint(address, callback); } @Override public BreakPoint addBreakPoint(long address) { return addBreakPoint(address, null); } @Override public BreakPoint addBreakPoint(long address, BreakPointCallback callback) { boolean thumb = (address & 1) != 0; address &= (~1); if (log.isDebugEnabled()) { log.debug("addBreakPoint address=0x" + Long.toHexString(address)); } BreakPoint breakPoint = emulator.getBackend().addBreakPoint(address, callback, thumb); breakMap.put(address, breakPoint); return breakPoint; } @Override public void traceFunctionCall(FunctionCallListener listener) { traceFunctionCall(null, listener); } @Override public void traceFunctionCall(Module module, FunctionCallListener listener) { throw new UnsupportedOperationException(); } protected abstract Keystone createKeystone(boolean isThumb); public final boolean removeBreakPoint(long address) { address &= (~1); if (breakMap.containsKey(address)) { breakMap.remove(address); return emulator.getBackend().removeBreakPoint(address); } else { return false; } } private DebugListener listener; @Override public void setDebugListener(DebugListener listener) { this.listener = listener; } @Override public void onBreak(Backend backend, long address, int size, Object user) { BreakPoint breakPoint = breakMap.get(address); if (breakPoint != null && breakPoint.isTemporary()) { removeBreakPoint(address); } BreakPointCallback callback; if (breakPoint != null && (callback = breakPoint.getCallback()) != null && callback.onHit(emulator, address)) { return; } try { if (listener == null || listener.canDebug(emulator, new CodeHistory(address, size, ARM.isThumb(backend)))) { cancelTrace(); debugging = true; loop(emulator, address, size, null); } } catch (Exception e) { log.warn("process loop failed", e); } finally { debugging = false; } } private void cancelTrace() { if (traceHook != null) { traceHook.detach(); traceHook = null; } if (traceHookRedirectStream != null) { com.alibaba.fastjson.util.IOUtils.close(traceHookRedirectStream); traceHookRedirectStream = null; } if (traceRead != null) { traceRead.detach(); traceRead = null; } if (traceReadRedirectStream != null) { com.alibaba.fastjson.util.IOUtils.close(traceReadRedirectStream); traceReadRedirectStream = null; } if (traceWrite != null) { traceWrite.detach(); traceWrite = null; } if (traceWriteRedirectStream != null) { com.alibaba.fastjson.util.IOUtils.close(traceWriteRedirectStream); traceWriteRedirectStream = null; } } private boolean debugging; @Override public boolean isDebugging() { return debugging; } private boolean blockHooked; private boolean breakNextBlock; @Override public void hookBlock(Backend backend, long address, int size, Object user) { if (breakNextBlock) { onBreak(backend, address, size, user); breakNextBlock = false; } } @Override public final void hook(Backend backend, long address, int size, Object user) { Emulator<?> emulator = (Emulator<?>) user; try { if (breakMnemonic != null) { CodeHistory history = new CodeHistory(address, size, ARM.isThumb(backend)); Instruction[] instructions = history.disassemble(emulator); if (instructions.length > 0 && breakMnemonic.equals(instructions[0].getMnemonic())) { breakMnemonic = null; backend.setFastDebug(true); cancelTrace(); debugging = true; loop(emulator, address, size, null); } } } catch (Exception e) { log.warn("process hook failed", e); } finally { debugging = false; } } @Override public void debug() { Backend backend = emulator.getBackend(); long address; if (emulator.is32Bit()) { address = backend.reg_read(ArmConst.UC_ARM_REG_PC).intValue() & 0xffffffffL; } else { address = backend.reg_read(Arm64Const.UC_ARM64_REG_PC).longValue(); } try { cancelTrace(); debugging = true; loop(emulator, address, 4, null); } catch (Exception e) { log.warn("debug failed", e); } finally { debugging = false; } } protected final void setSingleStep(int singleStep) { emulator.getBackend().setSingleStep(singleStep); } private String breakMnemonic; protected abstract void loop(Emulator<?> emulator, long address, int size, DebugRunnable<?> runnable) throws Exception; protected boolean callbackRunning; @Override public <T> T run(DebugRunnable<T> runnable) throws Exception { if (runnable == null) { throw new NullPointerException(); } T ret; try { callbackRunning = true; ret = runnable.runWithArgs(null); } finally { callbackRunning = false; } try { cancelTrace(); debugging = true; loop(emulator, -1, 0, runnable); } finally { debugging = false; } return ret; } protected enum StringType { nullTerminated, std_string } final void dumpMemory(Pointer pointer, int _length, String label, StringType stringType) { if (stringType != null) { if (stringType == StringType.nullTerminated) { long addr = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean foundTerminated = false; while (true) { byte[] data = pointer.getByteArray(addr, 0x10); int length = data.length; for (int i = 0; i < data.length; i++) { if (data[i] == 0) { length = i; break; } } baos.write(data, 0, length); addr += length; if (length < data.length) { // reach zero foundTerminated = true; break; } if (baos.size() > 0x10000) { // 64k break; } } if (foundTerminated) { Inspector.inspect(baos.toByteArray(), baos.size() >= 1024 ? (label + ", hex=" + Hex.encodeHexString(baos.toByteArray())) : (label + ", str=" + new String(baos.toByteArray(), StandardCharsets.UTF_8))); } else { Inspector.inspect(pointer.getByteArray(0, _length), label + ", find NULL-terminated failed"); } } else if (stringType == StringType.std_string) { StdString string = StdString.createStdString(emulator, pointer); long size = string.getDataSize(); byte[] data = string.getData(emulator); Inspector.inspect(data, size >= 1024 ? (label + ", hex=" + Hex.encodeHexString(data) + ", std=" + new String(data, StandardCharsets.UTF_8)) : label); } else { throw new UnsupportedOperationException("stringType=" + stringType); } } else { StringBuilder sb = new StringBuilder(label); byte[] data = pointer.getByteArray(0, _length); if (_length == 4) { ByteBuffer buffer = ByteBuffer.wrap(data); buffer.order(ByteOrder.LITTLE_ENDIAN); int value = buffer.getInt(); sb.append(", value=0x").append(Integer.toHexString(value)); } else if (_length == 8) { ByteBuffer buffer = ByteBuffer.wrap(data); buffer.order(ByteOrder.LITTLE_ENDIAN); long value = buffer.getLong(); sb.append(", value=0x").append(Long.toHexString(value)); } else if (_length == 16) { byte[] tmp = Arrays.copyOf(data, 16); for (int i = 0; i < 8; i++) { byte b = tmp[i]; tmp[i] = tmp[15 - i]; tmp[15 - i] = b; } byte[] bytes = new byte[tmp.length + 1]; System.arraycopy(tmp, 0, bytes, 1, tmp.length); // makePositive sb.append(", value=0x").append(new BigInteger(bytes).toString(16)); } if (data.length >= 1024) { sb.append(", hex=").append(Hex.encodeHexString(data)); } Inspector.inspect(data, sb.toString()); } } private void searchStack(byte[] data) { if (data == null || data.length < 1) { System.err.println("search stack failed as empty data"); return; } UnidbgPointer stack = emulator.getContext().getStackPointer(); Backend backend = emulator.getBackend(); Collection<Pointer> pointers = searchMemory(backend, stack.peer, emulator.getMemory().getStackBase(), data); System.out.println("Search stack from " + stack + " matches " + pointers.size() + " count"); for (Pointer pointer : pointers) { System.out.println("Stack matches: " + pointer); } } private void searchHeap(byte[] data, int prot) { if (data == null || data.length < 1) { System.err.println("search heap failed as empty data"); return; } List<Pointer> list = new ArrayList<>(); Backend backend = emulator.getBackend(); for (MemoryMap map : emulator.getMemory().getMemoryMap()) { if ((map.prot & prot) != 0) { Collection<Pointer> pointers = searchMemory(backend, map.base, map.base + map.size, data); list.addAll(pointers); } } System.out.println("Search heap matches " + list.size() + " count"); for (Pointer pointer : list) { System.out.println("Heap matches: " + pointer); } } private Collection<Pointer> searchMemory(Backend backend, long start, long end, byte[] data) { List<Pointer> pointers = new ArrayList<>(); for (long i = start, m = end - data.length; i < m; i++) { byte[] oneByte = backend.mem_read(i, 1); if (data[0] != oneByte[0]) { continue; } if (Arrays.equals(data, backend.mem_read(i, data.length))) { pointers.add(UnidbgPointer.pointer(emulator, i)); i += (data.length - 1); } } return pointers; } private AssemblyCodeDumper traceHook; private PrintStream traceHookRedirectStream; private TraceMemoryHook traceRead; private PrintStream traceReadRedirectStream; private TraceMemoryHook traceWrite; private PrintStream traceWriteRedirectStream; final boolean handleCommon(Backend backend, String line, long address, int size, long nextAddress, DebugRunnable<?> runnable) throws Exception { if ("exit".equals(line) || "quit".equals(line) || "q".equals(line)) { // continue return true; } if ("gc".equals(line)) { System.out.println("Run System.gc();"); System.gc(); return false; } if ("threads".equals(line)) { for (Task task : emulator.getThreadDispatcher().getTaskList()) { System.out.println(task.getId() + ": " + task); } return false; } if (runnable == null || callbackRunning) { if ("c".equals(line)) { // continue return true; } } else { if ("c".equals(line)) { try { callbackRunning = true; runnable.runWithArgs(null); cancelTrace(); return false; } finally { callbackRunning = false; } } } if ("n".equals(line)) { if (nextAddress == 0) { System.out.println("Next address failed."); return false; } else { addBreakPoint(nextAddress).setTemporary(true); return true; } } if (line.startsWith("st")) { // search stack int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchStack(data); return false; } } } if (line.startsWith("shw")) { // search writable heap int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchHeap(data, UnicornConst.UC_PROT_WRITE); return false; } } } if (line.startsWith("shr")) { // search readable heap int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchHeap(data, UnicornConst.UC_PROT_READ); return false; } } } if (line.startsWith("shx")) { // search executable heap int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchHeap(data, UnicornConst.UC_PROT_EXEC); return false; } } } if (emulator.getFamily() == Family.iOS && !emulator.isRunning() && line.startsWith("dump ")) { String className = line.substring(5).trim(); if (className.length() > 0) { dumpClass(className); return false; } } if (emulator.getFamily() == Family.iOS && !emulator.isRunning() && line.startsWith("gpb ")) { String className = line.substring(4).trim(); if (className.length() > 0) { dumpGPBProtobufMsg(className); return false; } } if (emulator.getFamily() == Family.iOS && !emulator.isRunning() && line.startsWith("search ")) { String keywords = line.substring(7).trim(); if (keywords.length() > 0) { searchClass(keywords); return false; } } final int traceSize = 0x10000; if (line.startsWith("traceRead")) { // start trace memory read Pattern pattern = Pattern.compile("traceRead\\s+(\\w+)\\s+(\\w+)"); Matcher matcher = pattern.matcher(line); if (traceRead != null) { traceRead.detach(); } traceRead = new TraceMemoryHook(true); long begin, end; if (matcher.find()) { begin = Utils.parseNumber(matcher.group(1)); end = Utils.parseNumber(matcher.group(2)); if (begin > end && end > 0 && end <= traceSize) { end += begin; } if (begin >= end) { File traceFile = new File("target/traceRead.txt"); if (!traceFile.exists() && !traceFile.createNewFile()) { throw new IllegalStateException("createNewFile: " + traceFile); } traceReadRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(traceFile.toPath())), true); traceReadRedirectStream.printf("[%s]Start traceRead%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); traceRead.setRedirect(traceReadRedirectStream); System.out.printf("Set trace all memory read success with trace file: %s.%n", traceFile); } else { boolean needTraceFile = end - begin > traceSize; if (needTraceFile) { File traceFile = new File(String.format("target/traceRead_0x%x-0x%x.txt", begin, end)); if (!traceFile.exists() && !traceFile.createNewFile()) { throw new IllegalStateException("createNewFile: " + traceFile); } traceReadRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(traceFile.toPath())), true); traceReadRedirectStream.printf("[%s]Start traceRead: 0x%x-0x%x%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), begin, end); traceRead.setRedirect(traceReadRedirectStream); System.out.printf("Set trace 0x%x->0x%x memory read success with trace file: %s.%n", begin, end, traceFile.getAbsolutePath()); } else { System.out.printf("Set trace 0x%x->0x%x memory read success.%n", begin, end); } } } else { begin = 1; end = 0; File traceFile = new File("target/traceRead.txt"); if (!traceFile.exists() && !traceFile.createNewFile()) { throw new IllegalStateException("createNewFile: " + traceFile); } traceReadRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(traceFile.toPath())), true); traceReadRedirectStream.printf("[%s]Start traceRead%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); traceRead.setRedirect(traceReadRedirectStream); System.out.printf("Set trace all memory read success with trace file: %s.%n", traceFile.getAbsolutePath()); } emulator.getBackend().hook_add_new((ReadHook) traceRead, begin, end, emulator); return false; } if (line.startsWith("traceWrite")) { // start trace memory write Pattern pattern = Pattern.compile("traceWrite\\s+(\\w+)\\s+(\\w+)"); Matcher matcher = pattern.matcher(line); if (traceWrite != null) { traceWrite.detach(); } traceWrite = new TraceMemoryHook(false); long begin, end; if (matcher.find()) { begin = Utils.parseNumber(matcher.group(1)); end = Utils.parseNumber(matcher.group(2)); if (begin > end && end > 0 && end <= traceSize) { end += begin; } if (begin >= end) { File traceFile = new File("target/traceWrite.txt"); if (!traceFile.exists() && !traceFile.createNewFile()) { throw new IllegalStateException("createNewFile: " + traceFile); } traceWriteRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(traceFile.toPath())), true); traceWriteRedirectStream.printf("[%s]Start traceWrite%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); traceWrite.setRedirect(traceWriteRedirectStream); System.out.printf("Set trace all memory write success with trace file: %s.%n", traceFile); } else { boolean needTraceFile = end - begin > traceSize; if (needTraceFile) { File traceFile = new File(String.format("target/traceWrite_0x%x-0x%x.txt", begin, end)); if (!traceFile.exists() && !traceFile.createNewFile()) { throw new IllegalStateException("createNewFile: " + traceFile); } traceWriteRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(traceFile.toPath())), true); traceWriteRedirectStream.printf("[%s]Start traceWrite: 0x%x-0x%x%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), begin, end); traceWrite.setRedirect(traceWriteRedirectStream); System.out.printf("Set trace 0x%x->0x%x memory write success with trace file: %s.%n", begin, end, traceFile.getAbsolutePath()); } else { System.out.printf("Set trace 0x%x->0x%x memory write success.%n", begin, end); } } } else { begin = 1; end = 0; File traceFile = new File("target/traceWrite.txt"); if (!traceFile.exists() && !traceFile.createNewFile()) { throw new IllegalStateException("createNewFile: " + traceFile); } traceWriteRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(traceFile.toPath())), true); traceWriteRedirectStream.printf("[%s]Start traceWrite%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); traceWrite.setRedirect(traceWriteRedirectStream); System.out.printf("Set trace all memory write success with trace file: %s.%n", traceFile.getAbsolutePath()); } emulator.getBackend().hook_add_new((WriteHook) traceWrite, begin, end, emulator); return false; } if (line.startsWith("trace")) { // start trace instructions Memory memory = emulator.getMemory(); Pattern pattern = Pattern.compile("trace\\s+(\\w+)\\s+(\\w+)"); Matcher matcher = pattern.matcher(line); if (traceHook != null) { traceHook.detach(); } traceHookRedirectStream = null; long begin, end; if (matcher.find()) { begin = Utils.parseNumber(matcher.group(1)); end = Utils.parseNumber(matcher.group(2)); if (begin > end && end > 0 && end < traceSize) { end += begin; } if (begin >= end) { File traceFile = new File("target/traceCode.txt"); if (!traceFile.exists() && (!traceFile.getParentFile().exists() || !traceFile.createNewFile())) { throw new IllegalStateException("createNewFile: " + traceFile.getAbsolutePath()); } traceHookRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(traceFile.toPath())), true); traceHookRedirectStream.printf("[%s]Start traceCode%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); System.out.printf("Set trace all instructions success with trace file: %s.%n", traceFile.getAbsolutePath()); } else { boolean needTraceFile = end - begin > traceSize; if (needTraceFile) { File traceFile = new File(String.format("target/traceCode_0x%x-0x%x.txt", begin, end)); if (!traceFile.exists() && !traceFile.createNewFile()) { throw new IllegalStateException("createNewFile: " + traceFile); } traceHookRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(traceFile.toPath())), true); traceHookRedirectStream.printf("[%s]Start traceCode: 0x%x-0x%x%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), begin, end); System.out.printf("Set trace 0x%x->0x%x instructions success with trace file: %s.%n", begin, end, traceFile.getAbsolutePath()); } else { System.out.printf("Set trace 0x%x->0x%x instructions success.%n", begin, end); } } } else { String redirect = null; Module module = memory.findModuleByAddress(address); { int index = line.indexOf(' '); if (index != -1) { redirect = line.substring(index + 1).trim(); } } File traceFile = null; if (redirect != null && redirect.trim().length() > 0) { Module check = memory.findModule(redirect); if (check != null) { module = check; } else { File outFile = new File(redirect.trim()); try { if (!outFile.exists() && !outFile.createNewFile()) { throw new IllegalStateException("createNewFile: " + outFile); } traceHookRedirectStream = new PrintStream(new BufferedOutputStream(Files.newOutputStream(outFile.toPath())), true); traceHookRedirectStream.printf("[%s]Start trace %s%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), module == null ? "all" : module); traceFile = outFile; } catch (IOException e) { System.err.println("Set trace redirect out file failed: " + outFile); return false; } } } begin = module == null ? 1 : module.base; end = module == null ? 0 : (module.base + module.size); System.out.println("Set trace " + (module == null ? "all" : module) + " instructions success" + (traceFile == null ? "." : (" with trace file: " + traceFile.getAbsolutePath()))); } traceHook = new AssemblyCodeDumper(emulator, begin, end, null); if (traceHookRedirectStream != null) { traceHook.setRedirect(traceHookRedirectStream); } emulator.getBackend().hook_add_new(traceHook, begin, end, emulator); return false; } if (line.startsWith("vm")) { Memory memory = emulator.getMemory(); String maxLengthSoName = memory.getMaxLengthLibraryName(); StringBuilder sb = new StringBuilder(); String filter = null; { int index = line.indexOf(' '); if (index != -1) { filter = line.substring(index + 1).trim(); } } int index = 0; long filterAddress = -1; if (filter != null && filter.startsWith("0x")) { filterAddress = Utils.parseNumber(filter); } for (Module module : memory.getLoadedModules()) { if (filter == null || module.getPath().toLowerCase().contains(filter.toLowerCase()) || (filterAddress >= module.base && filterAddress < module.base + module.size)) { sb.append(String.format("[%3s][%" + maxLengthSoName.length() + "s] ", index++, FilenameUtils.getName(module.name))); sb.append(String.format("[0x%0" + Long.toHexString(memory.getMaxSizeOfLibrary()).length() + "x-0x%x]", module.getBaseHeader(), module.base + module.size)); sb.append(module.getPath()); sb.append("\n"); } } if (index == 0) { System.err.println("Find loaded library failed with filter: " + filter); } else { System.out.println(sb); } return false; } if ("vbs".equals(line)) { // view breakpoints Memory memory = emulator.getMemory(); StringBuilder sb = new StringBuilder("* means temporary bp:\n"); String maxLengthSoName = memory.getMaxLengthLibraryName(); for (Map.Entry<Long, BreakPoint> entry : breakMap.entrySet()) { address = entry.getKey(); BreakPoint bp = entry.getValue(); Instruction ins = null; try { byte[] code = backend.mem_read(address, 4); Instruction[] insns = emulator.disassemble(address, code, bp.isThumb(), 1); if (insns != null && insns.length > 0) { ins = insns[0]; } } catch(Exception ignored) {} if (ins == null) { sb.append(String.format("[%" + String.valueOf(maxLengthSoName).length() + "s]", "0x" + Long.toHexString(address))); if (bp.isTemporary()) { sb.append('*'); } } else { sb.append(ARM.assembleDetail(emulator, ins, address, bp.isThumb(), bp.isTemporary(), memory.getMaxLengthLibraryName().length())); } sb.append("\n"); } System.out.println(sb); return false; } if ("stop".equals(line)) { backend.emu_stop(); return true; } if ("s".equals(line) || "si".equals(line)) { setSingleStep(1); return true; } if ("nb".equals(line)) { if (!blockHooked) { blockHooked = true;
emulator.getBackend().hook_add_new((BlockHook) this, 1, 0, emulator);
8
2023-10-17 06:13:28+00:00
24k
robaho/httpserver
src/test/java/jdk/test/lib/Utils.java
[ { "identifier": "assertTrue", "path": "src/test/java/jdk/test/lib/Asserts.java", "snippet": "public static void assertTrue(boolean value) {\n assertTrue(value, null);\n}" }, { "identifier": "ProcessTools", "path": "src/test/java/jdk/test/lib/process/ProcessTools.java", "snippet": "pub...
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.ServerSocket; import java.net.URL; import java.net.URLClassLoader; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.AclEntry; import java.nio.file.attribute.AclEntryType; import java.nio.file.attribute.AclFileAttributeView; import java.nio.file.attribute.FileAttribute; import java.nio.channels.SocketChannel; import java.nio.file.attribute.PosixFilePermissions; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HexFormat; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Set; import java.util.function.BooleanSupplier; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static jdk.test.lib.Asserts.assertTrue; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.process.OutputAnalyzer;
16,070
*/ public static URLClassLoader getTestClassPathURLClassLoader(ClassLoader parent) { URL[] urls = Arrays.stream(TEST_CLASS_PATH.split(File.pathSeparator)) .map(Paths::get) .map(Path::toUri) .map(x -> { try { return x.toURL(); } catch (MalformedURLException ex) { throw new Error("Test issue. JTREG property" + " 'test.class.path'" + " is not defined correctly", ex); } }).toArray(URL[]::new); return new URLClassLoader(urls, parent); } /** * Runs runnable and checks that it throws expected exception. If exceptionException is null it means * that we expect no exception to be thrown. * @param runnable what we run * @param expectedException expected exception */ public static void runAndCheckException(ThrowingRunnable runnable, Class<? extends Throwable> expectedException) { runAndCheckException(runnable, t -> { if (t == null) { if (expectedException != null) { throw new AssertionError("Didn't get expected exception " + expectedException.getSimpleName()); } } else { String message = "Got unexpected exception " + t.getClass().getSimpleName(); if (expectedException == null) { throw new AssertionError(message, t); } else if (!expectedException.isAssignableFrom(t.getClass())) { message += " instead of " + expectedException.getSimpleName(); throw new AssertionError(message, t); } } }); } /** * Runs runnable and makes some checks to ensure that it throws expected exception. * @param runnable what we run * @param checkException a consumer which checks that we got expected exception and raises a new exception otherwise */ public static void runAndCheckException(ThrowingRunnable runnable, Consumer<Throwable> checkException) { Throwable throwable = null; try { runnable.run(); } catch (Throwable t) { throwable = t; } checkException.accept(throwable); } /** * Converts to VM type signature * * @param type Java type to convert * @return string representation of VM type */ public static String toJVMTypeSignature(Class<?> type) { if (type.isPrimitive()) { if (type == boolean.class) { return "Z"; } else if (type == byte.class) { return "B"; } else if (type == char.class) { return "C"; } else if (type == double.class) { return "D"; } else if (type == float.class) { return "F"; } else if (type == int.class) { return "I"; } else if (type == long.class) { return "J"; } else if (type == short.class) { return "S"; } else if (type == void.class) { return "V"; } else { throw new Error("Unsupported type: " + type); } } String result = type.getName().replaceAll("\\.", "/"); if (!type.isArray()) { return "L" + result + ";"; } return result; } public static Object[] getNullValues(Class<?>... types) { Object[] result = new Object[types.length]; int i = 0; for (Class<?> type : types) { result[i++] = NULL_VALUES.get(type); } return result; } private static Map<Class<?>, Object> NULL_VALUES = new HashMap<>(); static { NULL_VALUES.put(boolean.class, false); NULL_VALUES.put(byte.class, (byte) 0); NULL_VALUES.put(short.class, (short) 0); NULL_VALUES.put(char.class, '\0'); NULL_VALUES.put(int.class, 0); NULL_VALUES.put(long.class, 0L); NULL_VALUES.put(float.class, 0.0f); NULL_VALUES.put(double.class, 0.0d); } /* * Run uname with specified arguments. */ public static OutputAnalyzer uname(String... args) throws Throwable { String[] cmds = new String[args.length + 1]; cmds[0] = "uname"; System.arraycopy(args, 0, cmds, 1, args.length);
/* * Copyright (c) 2013, 2022, 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; /** * Common library for various test helper functions. */ public final class Utils { /** * Returns the value of 'test.class.path' system property. */ public static final String TEST_CLASS_PATH = System.getProperty("test.class.path", "."); /** * Returns the sequence used by operating system to separate lines. */ public static final String NEW_LINE = System.getProperty("line.separator"); /** * Returns the value of 'test.vm.opts' system property. */ public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim(); /** * Returns the value of 'test.java.opts' system property. */ public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim(); /** * Returns the value of 'test.src' system property. */ public static final String TEST_SRC = System.getProperty("test.src", "").trim(); /** * Returns the value of 'test.root' system property. */ public static final String TEST_ROOT = System.getProperty("test.root", "").trim(); /* * Returns the value of 'test.jdk' system property */ public static final String TEST_JDK = System.getProperty("test.jdk"); /* * Returns the value of 'compile.jdk' system property */ public static final String COMPILE_JDK = System.getProperty("compile.jdk", TEST_JDK); /** * Returns the value of 'test.classes' system property */ public static final String TEST_CLASSES = System.getProperty("test.classes", "."); /** * Returns the value of 'test.name' system property */ public static final String TEST_NAME = System.getProperty("test.name", "."); /** * Returns the value of 'test.nativepath' system property */ public static final String TEST_NATIVE_PATH = System.getProperty("test.nativepath", "."); /** * Defines property name for seed value. */ public static final String SEED_PROPERTY_NAME = "jdk.test.lib.random.seed"; /** * Returns the value of 'file.separator' system property */ public static final String FILE_SEPARATOR = System.getProperty("file.separator"); /** * Random generator with predefined seed. */ private static volatile Random RANDOM_GENERATOR; /** * Maximum number of attempts to get free socket */ private static final int MAX_SOCKET_TRIES = 10; /** * Contains the seed value used for {@link java.util.Random} creation. */ public static final long SEED; static { var seed = Long.getLong(SEED_PROPERTY_NAME); if (seed != null) { // use explicitly set seed SEED = seed; } else { var v = Runtime.version(); // promotable builds have build number, and it's greater than 0 if (v.build().orElse(0) > 0) { // promotable build -> use 1st 8 bytes of md5($version) try { var md = MessageDigest.getInstance("MD5"); var bytes = v.toString() .getBytes(StandardCharsets.UTF_8); bytes = md.digest(bytes); SEED = ByteBuffer.wrap(bytes).getLong(); } catch (NoSuchAlgorithmException e) { throw new Error(e); } } else { // "personal" build -> use random seed SEED = new Random().nextLong(); } } } /** * Returns the value of 'test.timeout.factor' system property * converted to {@code double}. */ public static final double TIMEOUT_FACTOR; static { String toFactor = System.getProperty("test.timeout.factor", "1.0"); TIMEOUT_FACTOR = Double.parseDouble(toFactor); } /** * Returns the value of JTREG default test timeout in milliseconds * converted to {@code long}. */ public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120); private Utils() { // Private constructor to prevent class instantiation } /** * Returns the list of VM options with -J prefix. * * @return The list of VM options with -J prefix */ public static List<String> getForwardVmOptions() { String[] opts = safeSplitString(VM_OPTIONS); for (int i = 0; i < opts.length; i++) { opts[i] = "-J" + opts[i]; } return Arrays.asList(opts); } /** * Returns the default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts. * @return An array of options, or an empty array if no options. */ public static String[] getTestJavaOpts() { List<String> opts = new ArrayList<String>(); Collections.addAll(opts, safeSplitString(VM_OPTIONS)); Collections.addAll(opts, safeSplitString(JAVA_OPTIONS)); return opts.toArray(new String[0]); } /** * Combines given arguments with default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts * @return The combination of JTReg test java options and user args. */ public static String[] prependTestJavaOpts(String... userArgs) { List<String> opts = new ArrayList<String>(); Collections.addAll(opts, getTestJavaOpts()); Collections.addAll(opts, userArgs); return opts.toArray(new String[0]); } /** * Combines given arguments with default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts * @return The combination of JTReg test java options and user args. */ public static String[] appendTestJavaOpts(String... userArgs) { List<String> opts = new ArrayList<String>(); Collections.addAll(opts, userArgs); Collections.addAll(opts, getTestJavaOpts()); return opts.toArray(new String[0]); } /** * Combines given arguments with default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts * @return The combination of JTReg test java options and user args. */ public static String[] addTestJavaOpts(String... userArgs) { return prependTestJavaOpts(userArgs); } private static final Pattern useGcPattern = Pattern.compile( "(?:\\-XX\\:[\\+\\-]Use.+GC)"); /** * Removes any options specifying which GC to use, for example "-XX:+UseG1GC". * Removes any options matching: -XX:(+/-)Use*GC * Used when a test need to set its own GC version. Then any * GC specified by the framework must first be removed. * @return A copy of given opts with all GC options removed. */ public static List<String> removeGcOpts(List<String> opts) { List<String> optsWithoutGC = new ArrayList<String>(); for (String opt : opts) { if (useGcPattern.matcher(opt).matches()) { System.out.println("removeGcOpts: removed " + opt); } else { optsWithoutGC.add(opt); } } return optsWithoutGC; } /** * Returns the default JTReg arguments for a jvm running a test without * options that matches regular expressions in {@code filters}. * This is the combination of JTReg arguments test.vm.opts and test.java.opts. * @param filters Regular expressions used to filter out options. * @return An array of options, or an empty array if no options. */ public static String[] getFilteredTestJavaOpts(String... filters) { String options[] = getTestJavaOpts(); if (filters.length == 0) { return options; } List<String> filteredOptions = new ArrayList<String>(options.length); Pattern patterns[] = new Pattern[filters.length]; for (int i = 0; i < filters.length; i++) { patterns[i] = Pattern.compile(filters[i]); } for (String option : options) { boolean matched = false; for (int i = 0; i < patterns.length && !matched; i++) { Matcher matcher = patterns[i].matcher(option); matched = matcher.find(); } if (!matched) { filteredOptions.add(option); } } return filteredOptions.toArray(new String[filteredOptions.size()]); } /** * Splits a string by white space. * Works like String.split(), but returns an empty array * if the string is null or empty. */ private static String[] safeSplitString(String s) { if (s == null || s.trim().isEmpty()) { return new String[] {}; } return s.trim().split("\\s+"); } /** * @return The full command line for the ProcessBuilder. */ public static String getCommandLine(ProcessBuilder pb) { StringBuilder cmd = new StringBuilder(); for (String s : pb.command()) { cmd.append(s).append(" "); } return cmd.toString(); } /** * Returns the socket address of an endpoint that refuses connections. The * endpoint is an InetSocketAddress where the address is the loopback address * and the port is a system port (1-1023 range). * This method is a better choice than getFreePort for tests that need * an endpoint that refuses connections. */ public static InetSocketAddress refusingEndpoint() { InetAddress lb = InetAddress.getLoopbackAddress(); int port = 1; while (port < 1024) { InetSocketAddress sa = new InetSocketAddress(lb, port); try { SocketChannel.open(sa).close(); } catch (IOException ioe) { return sa; } port++; } throw new RuntimeException("Unable to find system port that is refusing connections"); } /** * Returns local addresses with symbolic and numeric scopes */ public static List<InetAddress> getAddressesWithSymbolicAndNumericScopes() { List<InetAddress> result = new LinkedList<>(); try { NetworkConfiguration conf = NetworkConfiguration.probe(); conf.ip4Addresses().forEach(result::add); // Java reports link local addresses with symbolic scope, // but on Windows java.net.NetworkInterface generates its own scope names // which are incompatible with native Windows routines. // So on Windows test only addresses with numeric scope. // On other platforms test both symbolic and numeric scopes. conf.ip6Addresses() // test only IPv6 loopback and link-local addresses (JDK-8224775) .filter(addr -> addr.isLinkLocalAddress() || addr.isLoopbackAddress()) .forEach(addr6 -> { try { result.add(Inet6Address.getByAddress(null, addr6.getAddress(), addr6.getScopeId())); } catch (UnknownHostException e) { // cannot happen! throw new RuntimeException("Unexpected", e); } if (!Platform.isWindows()) { result.add(addr6); } }); } catch (IOException e) { // cannot happen! throw new RuntimeException("Unexpected", e); } return result; } /** * Returns the free port on the loopback address. * * @return The port number * @throws IOException if an I/O error occurs when opening the socket */ public static int getFreePort() throws IOException { try (ServerSocket serverSocket = new ServerSocket(0, 5, InetAddress.getLoopbackAddress());) { return serverSocket.getLocalPort(); } } /** * Returns the free unreserved port on the local host. * * @param reservedPorts reserved ports * @return The port number or -1 if failed to find a free port */ public static int findUnreservedFreePort(int... reservedPorts) { int numTries = 0; while (numTries++ < MAX_SOCKET_TRIES) { int port = -1; try { port = getFreePort(); } catch (IOException e) { e.printStackTrace(); } if (port > 0 && !isReserved(port, reservedPorts)) { return port; } } return -1; } private static boolean isReserved(int port, int[] reservedPorts) { for (int p : reservedPorts) { if (p == port) { return true; } } return false; } /** * Returns the name of the local host. * * @return The host name * @throws UnknownHostException if IP address of a host could not be determined */ public static String getHostname() throws UnknownHostException { InetAddress inetAddress = InetAddress.getLocalHost(); String hostName = inetAddress.getHostName(); assertTrue((hostName != null && !hostName.isEmpty()), "Cannot get hostname"); return hostName; } /** * Adjusts the provided timeout value for the TIMEOUT_FACTOR * @param tOut the timeout value to be adjusted * @return The timeout value adjusted for the value of "test.timeout.factor" * system property */ public static long adjustTimeout(long tOut) { return Math.round(tOut * Utils.TIMEOUT_FACTOR); } /** * Return the contents of the named file as a single String, * or null if not found. * @param filename name of the file to read * @return String contents of file, or null if file not found. * @throws IOException * if an I/O error occurs reading from the file or a malformed or * unmappable byte sequence is read */ public static String fileAsString(String filename) throws IOException { Path filePath = Paths.get(filename); if (!Files.exists(filePath)) return null; return new String(Files.readAllBytes(filePath)); } /** * Returns hex view of byte array * * @param bytes byte array to process * @return space separated hexadecimal string representation of bytes * @deprecated replaced by {@link java.util.HexFormat#ofDelimiter(String) * HexFormat.ofDelimiter(" ").format (byte[], char)}. */ @Deprecated public static String toHexString(byte[] bytes) { return HexFormat.ofDelimiter(" ").withUpperCase().formatHex(bytes); } /** * Returns byte array of hex view * * @param hex hexadecimal string representation * @return byte array */ public static byte[] toByteArray(String hex) { return HexFormat.of().parseHex(hex); } /** * Returns {@link java.util.Random} generator initialized with particular seed. * The seed could be provided via system property {@link Utils#SEED_PROPERTY_NAME}. * In case no seed is provided and the build under test is "promotable" * (its build number ({@code $BUILD} in {@link Runtime.Version}) is greater than 0, * the seed based on string representation of {@link Runtime#version()} is used. * Otherwise, the seed is randomly generated. * The used seed printed to stdout. * The printing is not in the synchronized block so as to prevent carrier threads starvation. * @return {@link java.util.Random} generator with particular seed. */ public static Random getRandomInstance() { if (RANDOM_GENERATOR == null) { synchronized (Utils.class) { if (RANDOM_GENERATOR == null) { RANDOM_GENERATOR = new Random(SEED); } else { return RANDOM_GENERATOR; } } System.out.printf("For random generator using seed: %d%n", SEED); System.out.printf("To re-run test with same seed value please add \"-D%s=%d\" to command line.%n", SEED_PROPERTY_NAME, SEED); } return RANDOM_GENERATOR; } /** * Returns random element of non empty collection * * @param <T> a type of collection element * @param collection collection of elements * @return random element of collection * @throws IllegalArgumentException if collection is empty */ public static <T> T getRandomElement(Collection<T> collection) throws IllegalArgumentException { if (collection.isEmpty()) { throw new IllegalArgumentException("Empty collection"); } Random random = getRandomInstance(); int elementIndex = 1 + random.nextInt(collection.size() - 1); Iterator<T> iterator = collection.iterator(); while (--elementIndex != 0) { iterator.next(); } return iterator.next(); } /** * Returns random element of non empty array * * @param <T> a type of array element * @param array array of elements * @return random element of array * @throws IllegalArgumentException if array is empty */ public static <T> T getRandomElement(T[] array) throws IllegalArgumentException { if (array == null || array.length == 0) { throw new IllegalArgumentException("Empty or null array"); } Random random = getRandomInstance(); return array[random.nextInt(array.length)]; } /** * Wait for condition to be true * * @param condition a condition to wait for */ public static final void waitForCondition(BooleanSupplier condition) { waitForCondition(condition, -1L, 100L); } /** * Wait until timeout for condition to be true * * @param condition a condition to wait for * @param timeout a time in milliseconds to wait for condition to be true * specifying -1 will wait forever * @return condition value, to determine if wait was successful */ public static final boolean waitForCondition(BooleanSupplier condition, long timeout) { return waitForCondition(condition, timeout, 100L); } /** * Wait until timeout for condition to be true for specified time * * @param condition a condition to wait for * @param timeout a time in milliseconds to wait for condition to be true, * specifying -1 will wait forever * @param sleepTime a time to sleep value in milliseconds * @return condition value, to determine if wait was successful */ public static final boolean waitForCondition(BooleanSupplier condition, long timeout, long sleepTime) { long startTime = System.currentTimeMillis(); while (!(condition.getAsBoolean() || (timeout != -1L && ((System.currentTimeMillis() - startTime) > timeout)))) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new Error(e); } } return condition.getAsBoolean(); } /** * Interface same as java.lang.Runnable but with * method {@code run()} able to throw any Throwable. */ public static interface ThrowingRunnable { void run() throws Throwable; } /** * Filters out an exception that may be thrown by the given * test according to the given filter. * * @param test method that is invoked and checked for exception. * @param filter function that checks if the thrown exception matches * criteria given in the filter's implementation. * @return exception that matches the filter if it has been thrown or * {@code null} otherwise. * @throws Throwable if test has thrown an exception that does not * match the filter. */ public static Throwable filterException(ThrowingRunnable test, Function<Throwable, Boolean> filter) throws Throwable { try { test.run(); } catch (Throwable t) { if (filter.apply(t)) { return t; } else { throw t; } } return null; } /** * Ensures a requested class is loaded * @param aClass class to load */ public static void ensureClassIsLoaded(Class<?> aClass) { if (aClass == null) { throw new Error("Requested null class"); } try { Class.forName(aClass.getName(), /* initialize = */ true, ClassLoader.getSystemClassLoader()); } catch (ClassNotFoundException e) { throw new Error("Class not found", e); } } /** * @param parent a class loader to be the parent for the returned one * @return an UrlClassLoader with urls made of the 'test.class.path' jtreg * property and with the given parent */ public static URLClassLoader getTestClassPathURLClassLoader(ClassLoader parent) { URL[] urls = Arrays.stream(TEST_CLASS_PATH.split(File.pathSeparator)) .map(Paths::get) .map(Path::toUri) .map(x -> { try { return x.toURL(); } catch (MalformedURLException ex) { throw new Error("Test issue. JTREG property" + " 'test.class.path'" + " is not defined correctly", ex); } }).toArray(URL[]::new); return new URLClassLoader(urls, parent); } /** * Runs runnable and checks that it throws expected exception. If exceptionException is null it means * that we expect no exception to be thrown. * @param runnable what we run * @param expectedException expected exception */ public static void runAndCheckException(ThrowingRunnable runnable, Class<? extends Throwable> expectedException) { runAndCheckException(runnable, t -> { if (t == null) { if (expectedException != null) { throw new AssertionError("Didn't get expected exception " + expectedException.getSimpleName()); } } else { String message = "Got unexpected exception " + t.getClass().getSimpleName(); if (expectedException == null) { throw new AssertionError(message, t); } else if (!expectedException.isAssignableFrom(t.getClass())) { message += " instead of " + expectedException.getSimpleName(); throw new AssertionError(message, t); } } }); } /** * Runs runnable and makes some checks to ensure that it throws expected exception. * @param runnable what we run * @param checkException a consumer which checks that we got expected exception and raises a new exception otherwise */ public static void runAndCheckException(ThrowingRunnable runnable, Consumer<Throwable> checkException) { Throwable throwable = null; try { runnable.run(); } catch (Throwable t) { throwable = t; } checkException.accept(throwable); } /** * Converts to VM type signature * * @param type Java type to convert * @return string representation of VM type */ public static String toJVMTypeSignature(Class<?> type) { if (type.isPrimitive()) { if (type == boolean.class) { return "Z"; } else if (type == byte.class) { return "B"; } else if (type == char.class) { return "C"; } else if (type == double.class) { return "D"; } else if (type == float.class) { return "F"; } else if (type == int.class) { return "I"; } else if (type == long.class) { return "J"; } else if (type == short.class) { return "S"; } else if (type == void.class) { return "V"; } else { throw new Error("Unsupported type: " + type); } } String result = type.getName().replaceAll("\\.", "/"); if (!type.isArray()) { return "L" + result + ";"; } return result; } public static Object[] getNullValues(Class<?>... types) { Object[] result = new Object[types.length]; int i = 0; for (Class<?> type : types) { result[i++] = NULL_VALUES.get(type); } return result; } private static Map<Class<?>, Object> NULL_VALUES = new HashMap<>(); static { NULL_VALUES.put(boolean.class, false); NULL_VALUES.put(byte.class, (byte) 0); NULL_VALUES.put(short.class, (short) 0); NULL_VALUES.put(char.class, '\0'); NULL_VALUES.put(int.class, 0); NULL_VALUES.put(long.class, 0L); NULL_VALUES.put(float.class, 0.0f); NULL_VALUES.put(double.class, 0.0d); } /* * Run uname with specified arguments. */ public static OutputAnalyzer uname(String... args) throws Throwable { String[] cmds = new String[args.length + 1]; cmds[0] = "uname"; System.arraycopy(args, 0, cmds, 1, args.length);
return ProcessTools.executeCommand(cmds);
1
2023-10-15 15:56:58+00:00
24k
team-moabam/moabam-BE
src/main/java/com/moabam/api/application/room/SearchService.java
[ { "identifier": "GlobalConstant", "path": "src/main/java/com/moabam/global/common/util/GlobalConstant.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class GlobalConstant {\n\n\tpublic static final String BLANK = \"\";\n\tpublic static final String DELIMITER = \"/\";\n\tpubli...
import static com.moabam.global.common.util.GlobalConstant.*; import static com.moabam.global.error.model.ErrorMessage.*; import static org.apache.commons.lang3.StringUtils.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.notification.NotificationService; import com.moabam.api.application.room.mapper.CertificationsMapper; import com.moabam.api.application.room.mapper.ParticipantMapper; import com.moabam.api.application.room.mapper.RoomMapper; import com.moabam.api.application.room.mapper.RoutineMapper; import com.moabam.api.domain.item.Inventory; import com.moabam.api.domain.item.repository.InventorySearchRepository; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.room.Certification; import com.moabam.api.domain.room.DailyMemberCertification; import com.moabam.api.domain.room.DailyRoomCertification; import com.moabam.api.domain.room.Participant; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.RoomType; import com.moabam.api.domain.room.Routine; import com.moabam.api.domain.room.repository.CertificationsSearchRepository; import com.moabam.api.domain.room.repository.ParticipantSearchRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.domain.room.repository.RoomSearchRepository; import com.moabam.api.domain.room.repository.RoutineRepository; import com.moabam.api.dto.room.CertificationImageResponse; import com.moabam.api.dto.room.CertificationImagesResponse; import com.moabam.api.dto.room.GetAllRoomResponse; import com.moabam.api.dto.room.GetAllRoomsResponse; import com.moabam.api.dto.room.ManageRoomResponse; import com.moabam.api.dto.room.MyRoomResponse; import com.moabam.api.dto.room.MyRoomsResponse; import com.moabam.api.dto.room.ParticipantResponse; import com.moabam.api.dto.room.RoomDetailsResponse; import com.moabam.api.dto.room.RoomHistoryResponse; import com.moabam.api.dto.room.RoomsHistoryResponse; import com.moabam.api.dto.room.RoutineResponse; import com.moabam.api.dto.room.TodayCertificateRankResponse; import com.moabam.api.dto.room.UnJoinedRoomCertificateRankResponse; import com.moabam.api.dto.room.UnJoinedRoomDetailsResponse; import com.moabam.global.common.util.ClockHolder; import com.moabam.global.error.exception.ForbiddenException; import com.moabam.global.error.exception.NotFoundException; import jakarta.annotation.Nullable; import lombok.RequiredArgsConstructor;
17,378
List<RoutineResponse> routineResponses = RoutineMapper.toRoutineResponses(routines); List<DailyMemberCertification> sortedDailyMemberCertifications = certificationsSearchRepository.findSortedDailyMemberCertifications(roomId, clockHolder.date()); List<Long> memberIds = sortedDailyMemberCertifications.stream() .map(DailyMemberCertification::getMemberId) .toList(); List<Member> members = memberService.getRoomMembers(memberIds); List<Inventory> inventories = inventorySearchRepository.findDefaultInventories(memberIds, room.getRoomType().name()); List<UnJoinedRoomCertificateRankResponse> unJoinedRoomCertificateRankResponses = new ArrayList<>(); int rank = 1; for (DailyMemberCertification certification : sortedDailyMemberCertifications) { Member member = members.stream() .filter(m -> m.getId().equals(certification.getMemberId())) .findAny() .orElseThrow(() -> new NotFoundException(MEMBER_NOT_FOUND)); Inventory inventory = inventories.stream() .filter(i -> i.getMemberId().equals(member.getId())) .findAny() .orElseThrow(() -> new NotFoundException(INVENTORY_NOT_FOUND)); UnJoinedRoomCertificateRankResponse response = RoomMapper.toUnJoinedRoomCertificateRankResponse(member, rank, inventory); unJoinedRoomCertificateRankResponses.add(response); rank += 1; } return RoomMapper.toUnJoinedRoomDetails(room, routineResponses, unJoinedRoomCertificateRankResponses); } private boolean isHasNext(List<GetAllRoomResponse> getAllRoomResponse, List<Room> rooms) { boolean hasNext = false; if (rooms.size() > ROOM_FIXED_SEARCH_SIZE) { hasNext = true; rooms.remove(ROOM_FIXED_SEARCH_SIZE); } List<Long> roomIds = rooms.stream() .map(Room::getId) .toList(); List<Routine> routines = routineRepository.findAllByRoomIdIn(roomIds); for (Room room : rooms) { List<Routine> filteredRoutines = routines.stream() .filter(routine -> routine.getRoom().getId().equals(room.getId())) .toList(); List<RoutineResponse> filteredResponses = RoutineMapper.toRoutineResponses(filteredRoutines); boolean isPassword = !isEmpty(room.getPassword()); getAllRoomResponse.add(RoomMapper.toSearchAllRoomResponse(room, filteredResponses, isPassword)); } return hasNext; } private List<RoutineResponse> getRoutineResponses(Long roomId) { List<Routine> roomRoutines = routineRepository.findAllByRoomId(roomId); return RoutineMapper.toRoutineResponses(roomRoutines); } private List<TodayCertificateRankResponse> getTodayCertificateRankResponses(Long memberId, Long roomId, List<DailyMemberCertification> dailyMemberCertifications, LocalDate date, RoomType roomType) { List<Certification> certifications = certificationsSearchRepository.findCertifications(roomId, date); List<Participant> participants = participantSearchRepository.findAllWithDeletedByRoomId(roomId); List<Member> members = memberService.getRoomMembers(participants.stream() .map(Participant::getMemberId) .distinct() .toList()); List<Long> knocks = notificationService.getMyKnockStatusInRoom(memberId, roomId, participants); List<Long> memberIds = members.stream() .map(Member::getId) .toList(); List<Inventory> inventories = inventorySearchRepository.findDefaultInventories(memberIds, roomType.name()); List<TodayCertificateRankResponse> responses = new ArrayList<>( completedMembers(dailyMemberCertifications, members, certifications, participants, date, knocks, inventories)); if (clockHolder.date().equals(date)) { responses.addAll(uncompletedMembers(dailyMemberCertifications, members, participants, date, knocks, inventories)); } return responses; } private List<TodayCertificateRankResponse> completedMembers( List<DailyMemberCertification> dailyMemberCertifications, List<Member> members, List<Certification> certifications, List<Participant> participants, LocalDate date, List<Long> knocks, List<Inventory> inventories) { List<TodayCertificateRankResponse> responses = new ArrayList<>(); int rank = 1; for (DailyMemberCertification certification : dailyMemberCertifications) { Member member = members.stream() .filter(m -> m.getId().equals(certification.getMemberId())) .findAny() .orElseThrow(() -> new NotFoundException(ROOM_DETAILS_ERROR)); Inventory inventory = inventories.stream() .filter(i -> i.getMemberId().equals(member.getId())) .findAny() .orElseThrow(() -> new NotFoundException(INVENTORY_NOT_FOUND)); String awakeImage = inventory.getItem().getAwakeImage(); String sleepImage = inventory.getItem().getSleepImage(); int contributionPoint = calculateContributionPoint(member.getId(), participants, date); CertificationImagesResponse certificationImages = getCertificationImages(member.getId(), certifications); boolean isNotificationSent = knocks.contains(member.getId());
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class SearchService { private final RoomRepository roomRepository; private final RoomSearchRepository roomSearchRepository; private final RoutineRepository routineRepository; private final ParticipantSearchRepository participantSearchRepository; private final CertificationsSearchRepository certificationsSearchRepository; private final InventorySearchRepository inventorySearchRepository; private final CertificationService certificationService; private final MemberService memberService; private final NotificationService notificationService; private final ClockHolder clockHolder; public RoomDetailsResponse getRoomDetails(Long memberId, Long roomId, LocalDate date) { Participant participant = participantSearchRepository.findOne(memberId, roomId) .orElseThrow(() -> new NotFoundException(PARTICIPANT_NOT_FOUND)); Room room = participant.getRoom(); String managerNickname = room.getManagerNickname(); List<DailyMemberCertification> dailyMemberCertifications = certificationsSearchRepository.findSortedDailyMemberCertifications(roomId, date); List<RoutineResponse> routineResponses = getRoutineResponses(roomId); List<TodayCertificateRankResponse> todayCertificateRankResponses = getTodayCertificateRankResponses(memberId, roomId, dailyMemberCertifications, date, room.getRoomType()); List<LocalDate> certifiedDates = getCertifiedDatesBeforeWeek(roomId); double completePercentage = calculateCompletePercentage(dailyMemberCertifications.size(), room, date); return RoomMapper.toRoomDetailsResponse(memberId, room, managerNickname, routineResponses, certifiedDates, todayCertificateRankResponses, completePercentage); } public MyRoomsResponse getMyRooms(Long memberId) { LocalDate today = clockHolder.date(); List<MyRoomResponse> myRoomResponses = new ArrayList<>(); List<Participant> participants = participantSearchRepository.findNotDeletedAllByMemberId(memberId); for (Participant participant : participants) { Room room = participant.getRoom(); boolean isMemberCertified = certificationService.existsMemberCertification(memberId, room.getId(), today); boolean isRoomCertified = certificationService.existsRoomCertification(room.getId(), today); myRoomResponses.add(RoomMapper.toMyRoomResponse(room, isMemberCertified, isRoomCertified)); } return RoomMapper.toMyRoomsResponse(myRoomResponses); } public RoomsHistoryResponse getJoinHistory(Long memberId) { List<Participant> participants = participantSearchRepository.findAllByMemberId(memberId); List<RoomHistoryResponse> roomHistoryResponses = participants.stream() .map(participant -> { if (participant.getRoom() == null) { return RoomMapper.toRoomHistoryResponse(null, participant.getDeletedRoomTitle(), participant); } Room room = participant.getRoom(); return RoomMapper.toRoomHistoryResponse(room.getId(), room.getTitle(), participant); }) .toList(); return RoomMapper.toRoomsHistoryResponse(roomHistoryResponses); } public ManageRoomResponse getRoomForModification(Long memberId, Long roomId) { Participant participant = participantSearchRepository.findOne(memberId, roomId) .orElseThrow(() -> new NotFoundException(PARTICIPANT_NOT_FOUND)); if (!participant.isManager()) { throw new ForbiddenException(ROOM_MODIFY_UNAUTHORIZED_REQUEST); } Room room = participant.getRoom(); List<RoutineResponse> routineResponses = getRoutineResponses(roomId); List<Participant> participants = participantSearchRepository.findAllByRoomId(roomId); List<Long> memberIds = participants.stream() .map(Participant::getMemberId) .toList(); List<Member> members = memberService.getRoomMembers(memberIds); List<ParticipantResponse> participantResponses = new ArrayList<>(); for (Member member : members) { int contributionPoint = calculateContributionPoint(member.getId(), participants, clockHolder.date()); participantResponses.add(ParticipantMapper.toParticipantResponse(member, contributionPoint)); } return RoomMapper.toManageRoomResponse(room, memberId, routineResponses, participantResponses); } public GetAllRoomsResponse getAllRooms(@Nullable RoomType roomType, @Nullable Long roomId) { List<GetAllRoomResponse> getAllRoomResponse = new ArrayList<>(); List<Room> rooms = new ArrayList<>(roomSearchRepository.findAllWithNoOffset(roomType, roomId)); boolean hasNext = isHasNext(getAllRoomResponse, rooms); return RoomMapper.toSearchAllRoomsResponse(hasNext, getAllRoomResponse); } public GetAllRoomsResponse searchRooms(String keyword, @Nullable RoomType roomType, @Nullable Long roomId) { List<GetAllRoomResponse> getAllRoomResponse = new ArrayList<>(); List<Room> rooms = new ArrayList<>(roomSearchRepository.searchWithKeyword(keyword, roomType, roomId)); boolean hasNext = isHasNext(getAllRoomResponse, rooms); return RoomMapper.toSearchAllRoomsResponse(hasNext, getAllRoomResponse); } public UnJoinedRoomDetailsResponse getUnJoinedRoomDetails(Long roomId) { Room room = roomRepository.findById(roomId) .orElseThrow(() -> new NotFoundException(ROOM_NOT_FOUND)); List<Routine> routines = routineRepository.findAllByRoomId(roomId); List<RoutineResponse> routineResponses = RoutineMapper.toRoutineResponses(routines); List<DailyMemberCertification> sortedDailyMemberCertifications = certificationsSearchRepository.findSortedDailyMemberCertifications(roomId, clockHolder.date()); List<Long> memberIds = sortedDailyMemberCertifications.stream() .map(DailyMemberCertification::getMemberId) .toList(); List<Member> members = memberService.getRoomMembers(memberIds); List<Inventory> inventories = inventorySearchRepository.findDefaultInventories(memberIds, room.getRoomType().name()); List<UnJoinedRoomCertificateRankResponse> unJoinedRoomCertificateRankResponses = new ArrayList<>(); int rank = 1; for (DailyMemberCertification certification : sortedDailyMemberCertifications) { Member member = members.stream() .filter(m -> m.getId().equals(certification.getMemberId())) .findAny() .orElseThrow(() -> new NotFoundException(MEMBER_NOT_FOUND)); Inventory inventory = inventories.stream() .filter(i -> i.getMemberId().equals(member.getId())) .findAny() .orElseThrow(() -> new NotFoundException(INVENTORY_NOT_FOUND)); UnJoinedRoomCertificateRankResponse response = RoomMapper.toUnJoinedRoomCertificateRankResponse(member, rank, inventory); unJoinedRoomCertificateRankResponses.add(response); rank += 1; } return RoomMapper.toUnJoinedRoomDetails(room, routineResponses, unJoinedRoomCertificateRankResponses); } private boolean isHasNext(List<GetAllRoomResponse> getAllRoomResponse, List<Room> rooms) { boolean hasNext = false; if (rooms.size() > ROOM_FIXED_SEARCH_SIZE) { hasNext = true; rooms.remove(ROOM_FIXED_SEARCH_SIZE); } List<Long> roomIds = rooms.stream() .map(Room::getId) .toList(); List<Routine> routines = routineRepository.findAllByRoomIdIn(roomIds); for (Room room : rooms) { List<Routine> filteredRoutines = routines.stream() .filter(routine -> routine.getRoom().getId().equals(room.getId())) .toList(); List<RoutineResponse> filteredResponses = RoutineMapper.toRoutineResponses(filteredRoutines); boolean isPassword = !isEmpty(room.getPassword()); getAllRoomResponse.add(RoomMapper.toSearchAllRoomResponse(room, filteredResponses, isPassword)); } return hasNext; } private List<RoutineResponse> getRoutineResponses(Long roomId) { List<Routine> roomRoutines = routineRepository.findAllByRoomId(roomId); return RoutineMapper.toRoutineResponses(roomRoutines); } private List<TodayCertificateRankResponse> getTodayCertificateRankResponses(Long memberId, Long roomId, List<DailyMemberCertification> dailyMemberCertifications, LocalDate date, RoomType roomType) { List<Certification> certifications = certificationsSearchRepository.findCertifications(roomId, date); List<Participant> participants = participantSearchRepository.findAllWithDeletedByRoomId(roomId); List<Member> members = memberService.getRoomMembers(participants.stream() .map(Participant::getMemberId) .distinct() .toList()); List<Long> knocks = notificationService.getMyKnockStatusInRoom(memberId, roomId, participants); List<Long> memberIds = members.stream() .map(Member::getId) .toList(); List<Inventory> inventories = inventorySearchRepository.findDefaultInventories(memberIds, roomType.name()); List<TodayCertificateRankResponse> responses = new ArrayList<>( completedMembers(dailyMemberCertifications, members, certifications, participants, date, knocks, inventories)); if (clockHolder.date().equals(date)) { responses.addAll(uncompletedMembers(dailyMemberCertifications, members, participants, date, knocks, inventories)); } return responses; } private List<TodayCertificateRankResponse> completedMembers( List<DailyMemberCertification> dailyMemberCertifications, List<Member> members, List<Certification> certifications, List<Participant> participants, LocalDate date, List<Long> knocks, List<Inventory> inventories) { List<TodayCertificateRankResponse> responses = new ArrayList<>(); int rank = 1; for (DailyMemberCertification certification : dailyMemberCertifications) { Member member = members.stream() .filter(m -> m.getId().equals(certification.getMemberId())) .findAny() .orElseThrow(() -> new NotFoundException(ROOM_DETAILS_ERROR)); Inventory inventory = inventories.stream() .filter(i -> i.getMemberId().equals(member.getId())) .findAny() .orElseThrow(() -> new NotFoundException(INVENTORY_NOT_FOUND)); String awakeImage = inventory.getItem().getAwakeImage(); String sleepImage = inventory.getItem().getSleepImage(); int contributionPoint = calculateContributionPoint(member.getId(), participants, date); CertificationImagesResponse certificationImages = getCertificationImages(member.getId(), certifications); boolean isNotificationSent = knocks.contains(member.getId());
TodayCertificateRankResponse response = CertificationsMapper.toTodayCertificateRankResponse(rank, member,
4
2023-10-20 06:15:43+00:00
24k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/textfield/XmTextFieldSkin.java
[ { "identifier": "FxKit", "path": "BaseUI/src/main/java/com/xm2013/jfx/common/FxKit.java", "snippet": "public class FxKit {\n\n /** The Constant DOUBLE_ARROW_RIGHT. */\n public static final String DOUBLE_ARROW_RIGHT = \"<svg version=\\\"1.1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" p-id=\\\"1050...
import com.xm2013.jfx.common.FxKit; import com.xm2013.jfx.control.base.BorderType; import com.xm2013.jfx.control.base.ColorType; import com.xm2013.jfx.control.base.RoundType; import com.xm2013.jfx.control.base.SizeType; import com.xm2013.jfx.control.label.XmLabel; import com.xm2013.jfx.control.svg.XmSVGView; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.beans.value.ChangeListener; import javafx.event.EventHandler; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.control.PasswordField; import javafx.scene.control.SkinBase; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.util.Duration; import static com.xm2013.jfx.common.FxKit.CLEAN_PATH;
17,780
/* * 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.control.textfield; public class XmTextFieldSkin extends SkinBase<XmTextField> { private static String ENABLE_PATH = "M512 398.336c-75.776 0-137.216 61.44-137.216 137.216s61.44 " + "137.216 137.216 137.216 137.216-61.44 137.216-137.216-61.44-137.216-137.216-137.216z m0 " + "205.824c-37.888 0-68.608-30.72-68.608-68.608s30.72-68.608 68.608-68.608 68.608 30.72 68.608 " + "68.608c0.512 37.376-30.72 68.608-68.608 68.608z m0-369.664c-278.016 0-479.744 179.712-479.744 " + "300.544 0 118.784 215.04 300.544 479.744 300.544 262.144 0 474.624-181.76 474.624-300.544S774.144 " + "234.496 512 234.496z m0 532.992c-237.568 0-411.136-162.816-411.136-232.448 0-79.36 173.568-232.448 " + "411.136-232.448 235.008 0 406.528 162.816 406.528 232.448s-171.52 232.448-406.528 232.448z"; private static String DISABLE_PATH = "M989.184 533.504c0 52.736-42.496 118.272-114.176 175.104-6.144 " + "5.12-13.824 7.68-21.504 7.68-10.24 0-19.968-4.608-26.624-12.8-11.776-14.848-9.216-36.352 " + "5.12-48.128 60.928-48.64 88.576-97.28 88.576-121.856 0-69.12-171.52-232.448-406.528-232.448-26.624 " + "0-53.248 2.048-79.872 5.632-18.432 3.072-35.84-10.24-38.912-28.672-2.56-18.432 10.24-35.84 " + "28.672-38.912 29.696-4.608 59.904-6.656 89.6-6.656 263.168 0 475.648 182.272 475.648 301.056z " + "m-136.192 272.896c13.312 13.312 13.312 34.816 0 48.128-6.656 6.656-15.36 10.24-24.064 10.24-8.704 " + "0-17.408-3.584-24.064-10.24l-66.56-66.56c-71.168 29.696-147.968 45.568-223.744 45.568-264.704 " + "0-479.744-181.76-479.744-300.544 0-82.432 86.016-178.176 209.92-238.592L175.616 225.28a33.9968 " + "33.9968 0 0 1 0-48.128c13.312-13.312 34.816-13.312 48.128 0l104.96 104.96 524.288 524.288zM445.44 " + "533.504c0 37.888 30.72 68.608 68.608 68.608 10.752 0 20.992-2.56 30.72-7.168l-92.16-92.16c-4.608 " + "9.216-7.168 19.456-7.168 30.72z m240.64 202.24l-91.136-91.136c-23.04 16.896-50.688 26.112-80.384 " + "26.112-75.776 0-137.216-61.44-137.216-137.216 0-29.184 9.728-56.832 26.112-79.872L296.96 346.624c" + "-119.808 52.224-193.536 135.168-193.536 186.88 0 69.12 173.568 232.448 411.136 232.448 57.856-0.512" + " 116.224-10.752 171.52-30.208z"; private XmTextField control; /** * 文本框的标签 */ private XmLabel label; /** * 后缀图标的容器,clear, suffix */ private HBox suffixPane; /** * 清除图标按钮 */ private XmSVGView cleanIcon; /** * 显示密码按钮 */ private XmSVGView showPwdIcon; private XmSVGView enablePwdIcon; private Pane showPwdIconPane; //背景 private Pane fieldBackground; //VERTICAL_INLINE状态下,获得/失去焦点后,label变化的动画 private Timeline labelTimeline = new Timeline(); //是否需要需要更新布局 private boolean layoutUpdated = false; //VERTICAL_INLINE状态下, label当前是否放大 private boolean labelZoomIn = false; private boolean labelAnimatePlaying = false; private double paddingLeft = 0, paddingRight = 0, paddingTop = 0, paddingBottom = 0, hgap = 6, vgap = 6; public XmTextFieldSkin(XmTextField control) { super(control); this.control = control; if(control.getInputType().equals(XmTextInputType.PASSWORD)){ if(control.getField() instanceof PasswordField == false){ InnerPasswordField field = new InnerPasswordField(); field.showPasswordProperty().bind(control.showPasswordProperty()); field.echocharProperty().bind(control.echocharProperty()); field.promptTextProperty().bind(control.placeHolderProperty()); String text = control.getText(); control.setField(field); control.setText(text); } } // ObservableList<Node> children = this.getChildren(); //构建标签 label = new XmLabel(); label.setAlignment(control.getAlignment()); label.getStyleClass().add("field-label"); label.textProperty().bind(control.labelProperty()); label.prefWidthProperty().bind(control.labelWidthProperty()); label.graphicProperty().bind(control.labelIconProperty()); control.setPadding(control.getMargin()); control.paddingProperty().bind(this.control.marginProperty()); //构建后缀 suffixPane = new HBox(); suffixPane.setSpacing(3); suffixPane.getStyleClass().add("field-suffix-pane"); //是否删除的文本按钮 cleanIcon=new XmSVGView(CLEAN_PATH); cleanIcon.getStyleClass().add("field-clean"); cleanIcon.setSize(14);
/* * 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.control.textfield; public class XmTextFieldSkin extends SkinBase<XmTextField> { private static String ENABLE_PATH = "M512 398.336c-75.776 0-137.216 61.44-137.216 137.216s61.44 " + "137.216 137.216 137.216 137.216-61.44 137.216-137.216-61.44-137.216-137.216-137.216z m0 " + "205.824c-37.888 0-68.608-30.72-68.608-68.608s30.72-68.608 68.608-68.608 68.608 30.72 68.608 " + "68.608c0.512 37.376-30.72 68.608-68.608 68.608z m0-369.664c-278.016 0-479.744 179.712-479.744 " + "300.544 0 118.784 215.04 300.544 479.744 300.544 262.144 0 474.624-181.76 474.624-300.544S774.144 " + "234.496 512 234.496z m0 532.992c-237.568 0-411.136-162.816-411.136-232.448 0-79.36 173.568-232.448 " + "411.136-232.448 235.008 0 406.528 162.816 406.528 232.448s-171.52 232.448-406.528 232.448z"; private static String DISABLE_PATH = "M989.184 533.504c0 52.736-42.496 118.272-114.176 175.104-6.144 " + "5.12-13.824 7.68-21.504 7.68-10.24 0-19.968-4.608-26.624-12.8-11.776-14.848-9.216-36.352 " + "5.12-48.128 60.928-48.64 88.576-97.28 88.576-121.856 0-69.12-171.52-232.448-406.528-232.448-26.624 " + "0-53.248 2.048-79.872 5.632-18.432 3.072-35.84-10.24-38.912-28.672-2.56-18.432 10.24-35.84 " + "28.672-38.912 29.696-4.608 59.904-6.656 89.6-6.656 263.168 0 475.648 182.272 475.648 301.056z " + "m-136.192 272.896c13.312 13.312 13.312 34.816 0 48.128-6.656 6.656-15.36 10.24-24.064 10.24-8.704 " + "0-17.408-3.584-24.064-10.24l-66.56-66.56c-71.168 29.696-147.968 45.568-223.744 45.568-264.704 " + "0-479.744-181.76-479.744-300.544 0-82.432 86.016-178.176 209.92-238.592L175.616 225.28a33.9968 " + "33.9968 0 0 1 0-48.128c13.312-13.312 34.816-13.312 48.128 0l104.96 104.96 524.288 524.288zM445.44 " + "533.504c0 37.888 30.72 68.608 68.608 68.608 10.752 0 20.992-2.56 30.72-7.168l-92.16-92.16c-4.608 " + "9.216-7.168 19.456-7.168 30.72z m240.64 202.24l-91.136-91.136c-23.04 16.896-50.688 26.112-80.384 " + "26.112-75.776 0-137.216-61.44-137.216-137.216 0-29.184 9.728-56.832 26.112-79.872L296.96 346.624c" + "-119.808 52.224-193.536 135.168-193.536 186.88 0 69.12 173.568 232.448 411.136 232.448 57.856-0.512" + " 116.224-10.752 171.52-30.208z"; private XmTextField control; /** * 文本框的标签 */ private XmLabel label; /** * 后缀图标的容器,clear, suffix */ private HBox suffixPane; /** * 清除图标按钮 */ private XmSVGView cleanIcon; /** * 显示密码按钮 */ private XmSVGView showPwdIcon; private XmSVGView enablePwdIcon; private Pane showPwdIconPane; //背景 private Pane fieldBackground; //VERTICAL_INLINE状态下,获得/失去焦点后,label变化的动画 private Timeline labelTimeline = new Timeline(); //是否需要需要更新布局 private boolean layoutUpdated = false; //VERTICAL_INLINE状态下, label当前是否放大 private boolean labelZoomIn = false; private boolean labelAnimatePlaying = false; private double paddingLeft = 0, paddingRight = 0, paddingTop = 0, paddingBottom = 0, hgap = 6, vgap = 6; public XmTextFieldSkin(XmTextField control) { super(control); this.control = control; if(control.getInputType().equals(XmTextInputType.PASSWORD)){ if(control.getField() instanceof PasswordField == false){ InnerPasswordField field = new InnerPasswordField(); field.showPasswordProperty().bind(control.showPasswordProperty()); field.echocharProperty().bind(control.echocharProperty()); field.promptTextProperty().bind(control.placeHolderProperty()); String text = control.getText(); control.setField(field); control.setText(text); } } // ObservableList<Node> children = this.getChildren(); //构建标签 label = new XmLabel(); label.setAlignment(control.getAlignment()); label.getStyleClass().add("field-label"); label.textProperty().bind(control.labelProperty()); label.prefWidthProperty().bind(control.labelWidthProperty()); label.graphicProperty().bind(control.labelIconProperty()); control.setPadding(control.getMargin()); control.paddingProperty().bind(this.control.marginProperty()); //构建后缀 suffixPane = new HBox(); suffixPane.setSpacing(3); suffixPane.getStyleClass().add("field-suffix-pane"); //是否删除的文本按钮 cleanIcon=new XmSVGView(CLEAN_PATH); cleanIcon.getStyleClass().add("field-clean"); cleanIcon.setSize(14);
cleanIcon.setColor(Color.web(ColorType.DANGER));
2
2023-10-17 08:57:08+00:00
24k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/PCFGLA/GrammarTrainer.java
[ { "identifier": "TreeBankType", "path": "src/berkeley_parser/edu/berkeley/nlp/PCFGLA/Corpus.java", "snippet": "public enum TreeBankType {\n\tBROWN, WSJ, CHINESE, GERMAN, SPANISH, FRENCH, CONLL, SINGLEFILE\n}" }, { "identifier": "NoSmoothing", "path": "src/berkeley_parser/edu/berkeley/nlp/PCF...
import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Random; import edu.berkeley.nlp.PCFGLA.Corpus.TreeBankType; import edu.berkeley.nlp.PCFGLA.smoothing.NoSmoothing; import edu.berkeley.nlp.PCFGLA.smoothing.SmoothAcrossParentBits; import edu.berkeley.nlp.PCFGLA.smoothing.Smoother; import edu.berkeley.nlp.syntax.StateSet; import edu.berkeley.nlp.syntax.Tree; import edu.berkeley.nlp.util.Numberer;
15,733
short nSubstates = opts.nSubStates; short[] numSubStatesArray = initializeSubStateArray(trainTrees, validationTrees, tagNumberer, nSubstates); if (baseline) { short one = 1; Arrays.fill(numSubStatesArray, one); System.out .println("Training just the baseline grammar (1 substate for all states)"); randomness = 0.0f; } if (VERBOSE) { for (int i = 0; i < numSubStatesArray.length; i++) { System.out.println("Tag " + (String) tagNumberer.object(i) + " " + i); } } System.out.println("There are " + numSubStatesArray.length + " observed categories."); // initialize lexicon and grammar Lexicon lexicon = null, maxLexicon = null, previousLexicon = null; Grammar grammar = null, maxGrammar = null, previousGrammar = null; double maxLikelihood = Double.NEGATIVE_INFINITY; // String smootherStr = opts.smooth; // Smoother lexiconSmoother = null; // Smoother grammarSmoother = null; // if (splitGrammarFile!=null){ // lexiconSmoother = maxLexicon.smoother; // grammarSmoother = maxGrammar.smoother; // System.out.println("Using smoother from input grammar."); // } // else if (smootherStr.equals("NoSmoothing")) // lexiconSmoother = grammarSmoother = new NoSmoothing(); // else if (smootherStr.equals("SmoothAcrossParentBits")) { // lexiconSmoother = grammarSmoother = new // SmoothAcrossParentBits(grammarSmoothing, maxGrammar.splitTrees); // } // else // throw new // Error("I didn't understand the type of smoother '"+smootherStr+"'"); // System.out.println("Using smoother "+smootherStr); // EM: iterate until the validation likelihood drops for four // consecutive // iterations int iter = 0; int droppingIter = 0; // If we are splitting, we load the old grammar and start off by // splitting. int startSplit = 0; if (splitGrammarFile != null) { System.out.println("Loading old grammar from " + splitGrammarFile); startSplit = 0; // we've already trained the grammar ParserData pData = ParserData.Load(splitGrammarFile); maxGrammar = pData.gr; maxLexicon = pData.lex; numSubStatesArray = maxGrammar.numSubStates; previousGrammar = grammar = maxGrammar; previousLexicon = lexicon = maxLexicon; Numberer.setNumberers(pData.getNumbs()); tagNumberer = Numberer.getGlobalNumberer("tags"); System.out.println("Loading old grammar complete."); if (noSplit) { System.out.println("Will NOT split the loaded grammar."); startSplit = 1; } } double mergingPercentage = opts.mergingPercentage; boolean separateMergingThreshold = opts.separateMergingThreshold; if (mergingPercentage > 0) { System.out.println("Will merge " + (int) (mergingPercentage * 100) + "% of the splits in each round."); System.out .println("The threshold for merging lexical and phrasal categories will be set separately: " + separateMergingThreshold); } StateSetTreeList trainStateSetTrees = new StateSetTreeList(trainTrees, numSubStatesArray, false, tagNumberer); StateSetTreeList validationStateSetTrees = new StateSetTreeList( validationTrees, numSubStatesArray, false, tagNumberer);// deletePC); // get rid of the old trees trainTrees = null; validationTrees = null; corpus = null; System.gc(); if (opts.simpleLexicon) { System.out .println("Replacing words which have been seen less than 5 times with their signature."); Corpus.replaceRareWords(trainStateSetTrees, new SimpleLexicon( numSubStatesArray, -1), opts.rare); } Featurizer feat = new SimpleFeaturizer(opts.rare, opts.reallyRare); // If we're training without loading a split grammar, then we run once // without splitting. if (splitGrammarFile == null) { grammar = new Grammar(numSubStatesArray, findClosedUnaryPaths, new NoSmoothing(), null, filter); // these two lines crash the compiler. dunno why. Lexicon tmp_lexicon = // (opts.featurizedLexicon) ? // new FeaturizedLexicon(numSubStatesArray,feat,trainStateSetTrees) // : (opts.simpleLexicon) ? new SimpleLexicon(numSubStatesArray, -1, smoothParams, new NoSmoothing(), filter, trainStateSetTrees) : new SophisticatedLexicon(numSubStatesArray, SophisticatedLexicon.DEFAULT_SMOOTHING_CUTOFF, smoothParams, new NoSmoothing(), filter); if (opts.featurizedLexicon) tmp_lexicon = new FeaturizedLexicon(numSubStatesArray, feat, trainStateSetTrees); int n = 0; boolean secondHalf = false;
package edu.berkeley.nlp.PCFGLA; /** * Reads in the Penn Treebank and generates N_GRAMMARS different grammars. * * @author Slav Petrov */ public class GrammarTrainer { public static boolean VERBOSE = false; public static int HORIZONTAL_MARKOVIZATION = 1; public static int VERTICAL_MARKOVIZATION = 2; public static Random RANDOM = new Random(0); public static class Options { @Option(name = "-out", required = true, usage = "Output File for Grammar (Required)") public String outFileName; @Option(name = "-path", usage = "Path to Corpus (Default: null)") public String path = null; @Option(name = "-SMcycles", usage = "The number of split&merge iterations (Default: 6)") public int numSplits = 6; @Option(name = "-mergingPercentage", usage = "Merging percentage (Default: 0.5)") public double mergingPercentage = 0.5; @Option(name = "-baseline", usage = "Just read of the MLE baseline grammar") public boolean baseline = false; @Option(name = "-treebank", usage = "Language: WSJ, CHNINESE, GERMAN, CONLL, SINGLEFILE (Default: ENGLISH)") public TreeBankType treebank = TreeBankType.WSJ; @Option(name = "-splitMaxIt", usage = "Maximum number of EM iterations after splitting (Default: 50)") public int splitMaxIterations = 50; @Option(name = "-splitMinIt", usage = "Minimum number of EM iterations after splitting (Default: 50)") public int splitMinIterations = 50; @Option(name = "-mergeMaxIt", usage = "Maximum number of EM iterations after merging (Default: 20)") public int mergeMaxIterations = 20; @Option(name = "-mergeMinIt", usage = "Minimum number of EM iterations after merging (Default: 20)") public int mergeMinIterations = 20; @Option(name = "-smoothMaxIt", usage = "Maximum number of EM iterations with smoothing (Default: 10)") public int smoothMaxIterations = 10; @Option(name = "-di", usage = "The number of allowed iterations in which the validation likelihood drops. (Default: 6)") public int di = 6; @Option(name = "-trfr", usage = "The fraction of the training corpus to keep (Default: 1.0)\n") public double trainingFractionToKeep = 1.0; @Option(name = "-filter", usage = "Filter rules with prob below this threshold (Default: 1.0e-30)") public double filter = 1.0e-30; @Option(name = "-smooth", usage = "Type of grammar smoothing used.") public String smooth = "SmoothAcrossParentBits"; @Option(name = "-maxL", usage = "Maximum sentence length (Default <=10000)") public int maxSentenceLength = 10000; @Option(name = "-b", usage = "LEFT/RIGHT Binarization (Default: RIGHT)") public Binarization binarization = Binarization.RIGHT; @Option(name = "-noSplit", usage = "Don't split - just load and continue training an existing grammar (true/false) (Default:false)") public boolean noSplit = false; @Option(name = "-in", usage = "Input File for Grammar") public String inFile = null; @Option(name = "-randSeed", usage = "Seed for random number generator (Two works well for English)") public int randSeed = 2; @Option(name = "-sep", usage = "Set merging threshold for grammar and lexicon separately (Default: false)") public boolean separateMergingThreshold = false; @Option(name = "-trainOnDevSet", usage = "Include the development set into the training set (Default: false)") public boolean trainOnDevSet = false; @Option(name = "-hor", usage = "Horizontal Markovization (Default: 0)") public int horizontalMarkovization = 0; @Option(name = "-sub", usage = "Number of substates to split (Default: 2)") public short nSubStates = 1; @Option(name = "-ver", usage = "Vertical Markovization (Default: 1)") public int verticalMarkovization = 1; @Option(name = "-v", usage = "Verbose/Quiet (Default: Quiet)\n") public boolean verbose = false; @Option(name = "-lowercase", usage = "Lowercase all words in the treebank") public boolean lowercase = false; @Option(name = "-r", usage = "Level of Randomness at init (Default: 1)\n") public double randomization = 1.0; @Option(name = "-sm1", usage = "Lexicon smoothing parameter 1") public double smoothingParameter1 = 0.5; @Option(name = "-sm2", usage = "Lexicon smoothing parameter 2") public double smoothingParameter2 = 0.1; @Option(name = "-rare", usage = "Rare word threshold (Default 20)") public int rare = 20; @Option(name = "-reallyRare", usage = "Really Rare word threshold (Default 10)") public int reallyRare = 10; @Option(name = "-spath", usage = "Whether or not to store the best path info (true/false) (Default: true)") public boolean findClosedUnaryPaths = true; @Option(name = "-simpleLexicon", usage = "Use the simple generative lexicon") public boolean simpleLexicon = false; @Option(name = "-featurizedLexicon", usage = "Use the featurized lexicon") public boolean featurizedLexicon = false; @Option(name = "-skipSection", usage = "Skips a particular section of the WSJ training corpus (Needed for training Mark Johnsons reranker") public int skipSection = -1; @Option(name = "-skipBilingual", usage = "Skips the bilingual portion of the Chinese treebank (Needed for training the bilingual reranker") public boolean skipBilingual = false; @Option(name = "-keepFunctionLabels", usage = "Retain predicted function labels. Model must have been trained with function labels. (Default: false)") public boolean keepFunctionLabels = false; } public static void main(String[] args) { OptionParser optParser = new OptionParser(Options.class); Options opts = (Options) optParser.parse(args, true); // provide feedback on command-line arguments System.out.println("Calling with " + optParser.getPassedInOptions()); String path = opts.path; // int lang = opts.lang; System.out.println("Loading trees from " + path + " and using language " + opts.treebank); double trainingFractionToKeep = opts.trainingFractionToKeep; int maxSentenceLength = opts.maxSentenceLength; System.out.println("Will remove sentences with more than " + maxSentenceLength + " words."); HORIZONTAL_MARKOVIZATION = opts.horizontalMarkovization; VERTICAL_MARKOVIZATION = opts.verticalMarkovization; System.out .println("Using horizontal=" + HORIZONTAL_MARKOVIZATION + " and vertical=" + VERTICAL_MARKOVIZATION + " markovization."); Binarization binarization = opts.binarization; System.out.println("Using " + binarization.name() + " binarization.");// and // "+annotateString+"."); double randomness = opts.randomization; System.out.println("Using a randomness value of " + randomness); String outFileName = opts.outFileName; if (outFileName == null) { System.out.println("Output File name is required."); System.exit(-1); } else System.out .println("Using grammar output file " + outFileName + "."); VERBOSE = opts.verbose; RANDOM = new Random(opts.randSeed); System.out.println("Random number generator seeded at " + opts.randSeed + "."); boolean manualAnnotation = false; boolean baseline = opts.baseline; boolean noSplit = opts.noSplit; int numSplitTimes = opts.numSplits; if (baseline) numSplitTimes = 0; String splitGrammarFile = opts.inFile; int allowedDroppingIters = opts.di; int maxIterations = opts.splitMaxIterations; int minIterations = opts.splitMinIterations; if (minIterations > 0) System.out.println("I will do at least " + minIterations + " iterations."); double[] smoothParams = { opts.smoothingParameter1, opts.smoothingParameter2 }; System.out.println("Using smoothing parameters " + smoothParams[0] + " and " + smoothParams[1]); boolean allowMoreSubstatesThanCounts = false; boolean findClosedUnaryPaths = opts.findClosedUnaryPaths; Corpus corpus = new Corpus(path, opts.treebank, trainingFractionToKeep, false, opts.skipSection, opts.skipBilingual, opts.keepFunctionLabels); List<Tree<String>> trainTrees = Corpus.binarizeAndFilterTrees( corpus.getTrainTrees(), VERTICAL_MARKOVIZATION, HORIZONTAL_MARKOVIZATION, maxSentenceLength, binarization, manualAnnotation, VERBOSE); List<Tree<String>> validationTrees = Corpus.binarizeAndFilterTrees( corpus.getValidationTrees(), VERTICAL_MARKOVIZATION, HORIZONTAL_MARKOVIZATION, maxSentenceLength, binarization, manualAnnotation, VERBOSE); Numberer tagNumberer = Numberer.getGlobalNumberer("tags"); // for (Tree<String> t : trainTrees){ // System.out.println(t); // } if (opts.trainOnDevSet) { System.out.println("Adding devSet to training data."); trainTrees.addAll(validationTrees); } if (opts.lowercase) { System.out.println("Lowercasing the treebank."); Corpus.lowercaseWords(trainTrees); Corpus.lowercaseWords(validationTrees); } int nTrees = trainTrees.size(); System.out.println("There are " + nTrees + " trees in the training set."); double filter = opts.filter; if (filter > 0) System.out .println("Will remove rules with prob under " + filter + ".\nEven though only unlikely rules are pruned the training LL is not guaranteed to increase in every round anymore " + "(especially when we are close to converging)." + "\nFurthermore it increases the variance because 'good' rules can be pruned away in early stages."); short nSubstates = opts.nSubStates; short[] numSubStatesArray = initializeSubStateArray(trainTrees, validationTrees, tagNumberer, nSubstates); if (baseline) { short one = 1; Arrays.fill(numSubStatesArray, one); System.out .println("Training just the baseline grammar (1 substate for all states)"); randomness = 0.0f; } if (VERBOSE) { for (int i = 0; i < numSubStatesArray.length; i++) { System.out.println("Tag " + (String) tagNumberer.object(i) + " " + i); } } System.out.println("There are " + numSubStatesArray.length + " observed categories."); // initialize lexicon and grammar Lexicon lexicon = null, maxLexicon = null, previousLexicon = null; Grammar grammar = null, maxGrammar = null, previousGrammar = null; double maxLikelihood = Double.NEGATIVE_INFINITY; // String smootherStr = opts.smooth; // Smoother lexiconSmoother = null; // Smoother grammarSmoother = null; // if (splitGrammarFile!=null){ // lexiconSmoother = maxLexicon.smoother; // grammarSmoother = maxGrammar.smoother; // System.out.println("Using smoother from input grammar."); // } // else if (smootherStr.equals("NoSmoothing")) // lexiconSmoother = grammarSmoother = new NoSmoothing(); // else if (smootherStr.equals("SmoothAcrossParentBits")) { // lexiconSmoother = grammarSmoother = new // SmoothAcrossParentBits(grammarSmoothing, maxGrammar.splitTrees); // } // else // throw new // Error("I didn't understand the type of smoother '"+smootherStr+"'"); // System.out.println("Using smoother "+smootherStr); // EM: iterate until the validation likelihood drops for four // consecutive // iterations int iter = 0; int droppingIter = 0; // If we are splitting, we load the old grammar and start off by // splitting. int startSplit = 0; if (splitGrammarFile != null) { System.out.println("Loading old grammar from " + splitGrammarFile); startSplit = 0; // we've already trained the grammar ParserData pData = ParserData.Load(splitGrammarFile); maxGrammar = pData.gr; maxLexicon = pData.lex; numSubStatesArray = maxGrammar.numSubStates; previousGrammar = grammar = maxGrammar; previousLexicon = lexicon = maxLexicon; Numberer.setNumberers(pData.getNumbs()); tagNumberer = Numberer.getGlobalNumberer("tags"); System.out.println("Loading old grammar complete."); if (noSplit) { System.out.println("Will NOT split the loaded grammar."); startSplit = 1; } } double mergingPercentage = opts.mergingPercentage; boolean separateMergingThreshold = opts.separateMergingThreshold; if (mergingPercentage > 0) { System.out.println("Will merge " + (int) (mergingPercentage * 100) + "% of the splits in each round."); System.out .println("The threshold for merging lexical and phrasal categories will be set separately: " + separateMergingThreshold); } StateSetTreeList trainStateSetTrees = new StateSetTreeList(trainTrees, numSubStatesArray, false, tagNumberer); StateSetTreeList validationStateSetTrees = new StateSetTreeList( validationTrees, numSubStatesArray, false, tagNumberer);// deletePC); // get rid of the old trees trainTrees = null; validationTrees = null; corpus = null; System.gc(); if (opts.simpleLexicon) { System.out .println("Replacing words which have been seen less than 5 times with their signature."); Corpus.replaceRareWords(trainStateSetTrees, new SimpleLexicon( numSubStatesArray, -1), opts.rare); } Featurizer feat = new SimpleFeaturizer(opts.rare, opts.reallyRare); // If we're training without loading a split grammar, then we run once // without splitting. if (splitGrammarFile == null) { grammar = new Grammar(numSubStatesArray, findClosedUnaryPaths, new NoSmoothing(), null, filter); // these two lines crash the compiler. dunno why. Lexicon tmp_lexicon = // (opts.featurizedLexicon) ? // new FeaturizedLexicon(numSubStatesArray,feat,trainStateSetTrees) // : (opts.simpleLexicon) ? new SimpleLexicon(numSubStatesArray, -1, smoothParams, new NoSmoothing(), filter, trainStateSetTrees) : new SophisticatedLexicon(numSubStatesArray, SophisticatedLexicon.DEFAULT_SMOOTHING_CUTOFF, smoothParams, new NoSmoothing(), filter); if (opts.featurizedLexicon) tmp_lexicon = new FeaturizedLexicon(numSubStatesArray, feat, trainStateSetTrees); int n = 0; boolean secondHalf = false;
for (Tree<StateSet> stateSetTree : trainStateSetTrees) {
4
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;
20,942
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: {
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();
63
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,913
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));
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));
FeedSubscriber contract = getSubscriberContract(subContractAddr);
4
2023-10-23 20:33:07+00:00
24k
JonnyOnlineYT/xenza
src/minecraft/net/minecraft/client/gui/inventory/GuiFurnace.java
[ { "identifier": "GlStateManager", "path": "src/minecraft/net/minecraft/client/renderer/GlStateManager.java", "snippet": "public class GlStateManager {\n private static GlStateManager.AlphaState alphaState = new GlStateManager.AlphaState((GlStateManager.GlStateManager$1)null);\n private static GlStat...
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ContainerFurnace; import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraft.util.ResourceLocation;
18,952
package net.minecraft.client.gui.inventory; public class GuiFurnace extends GuiContainer { private static final ResourceLocation furnaceGuiTextures = new ResourceLocation("textures/gui/container/furnace.png"); private final InventoryPlayer playerInventory; private IInventory tileFurnace; public GuiFurnace(InventoryPlayer playerInv, IInventory furnaceInv) { super(new ContainerFurnace(playerInv, furnaceInv)); this.playerInventory = playerInv; this.tileFurnace = furnaceInv; } @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { String s = this.tileFurnace.getDisplayName().getUnformattedText(); this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, this.ySize - 96 + 2, 4210752); } @Override protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
package net.minecraft.client.gui.inventory; public class GuiFurnace extends GuiContainer { private static final ResourceLocation furnaceGuiTextures = new ResourceLocation("textures/gui/container/furnace.png"); private final InventoryPlayer playerInventory; private IInventory tileFurnace; public GuiFurnace(InventoryPlayer playerInv, IInventory furnaceInv) { super(new ContainerFurnace(playerInv, furnaceInv)); this.playerInventory = playerInv; this.tileFurnace = furnaceInv; } @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { String s = this.tileFurnace.getDisplayName().getUnformattedText(); this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, this.ySize - 96 + 2, 4210752); } @Override protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
0
2023-10-15 00:21:15+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,304
/* * 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} */
/* * 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;
4
2023-10-23 16:39:40+00:00
24k
eclipse-egit/egit
org.eclipse.egit.core/src/org/eclipse/egit/core/op/SubmoduleUpdateOperation.java
[ { "identifier": "EclipseGitProgressTransformer", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/EclipseGitProgressTransformer.java", "snippet": "public class EclipseGitProgressTransformer implements ProgressMonitor {\n\n\tprivate static long UPDATE_INTERVAL = TimeUnit.MILLISECONDS.toMillis(100...
import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.egit.core.EclipseGitProgressTransformer; import org.eclipse.egit.core.RepositoryUtil; import org.eclipse.egit.core.internal.CoreText; import org.eclipse.egit.core.internal.MergeStrategies; import org.eclipse.egit.core.internal.util.ProjectUtil; import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.SubmoduleInitCommand; import org.eclipse.jgit.api.SubmoduleUpdateCommand; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.merge.MergeStrategy; import org.eclipse.jgit.submodule.SubmoduleWalk; import org.eclipse.team.core.TeamException;
20,084
/****************************************************************************** * Copyright (c) 2012, 2015 GitHub Inc and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Kevin Sawicki (GitHub Inc.) - initial API and implementation * Laurent Delaigue (Obeo) - use of preferred merge strategy * Stephan Hackstedt <stephan.hackstedt@googlemail.com - bug 477695 *****************************************************************************/ package org.eclipse.egit.core.op; /** * Operation that updates a repository's submodules */ public class SubmoduleUpdateOperation implements IEGitOperation { private final Repository repository; private final Collection<String> paths; /** * Create submodule update operation * * @param repository */ public SubmoduleUpdateOperation(final Repository repository) { this.repository = repository; paths = new ArrayList<>(); } /** * Add path of submodule to update * * @param path * @return this operation */ public SubmoduleUpdateOperation addPath(final String path) { paths.add(path); return this; } @Override public void execute(final IProgressMonitor monitor) throws CoreException { IWorkspaceRunnable action = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor pm) throws CoreException { SubMonitor progress = SubMonitor.convert(pm, 4); progress.setTaskName(MessageFormat.format( CoreText.SubmoduleUpdateOperation_updating,
/****************************************************************************** * Copyright (c) 2012, 2015 GitHub Inc and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Kevin Sawicki (GitHub Inc.) - initial API and implementation * Laurent Delaigue (Obeo) - use of preferred merge strategy * Stephan Hackstedt <stephan.hackstedt@googlemail.com - bug 477695 *****************************************************************************/ package org.eclipse.egit.core.op; /** * Operation that updates a repository's submodules */ public class SubmoduleUpdateOperation implements IEGitOperation { private final Repository repository; private final Collection<String> paths; /** * Create submodule update operation * * @param repository */ public SubmoduleUpdateOperation(final Repository repository) { this.repository = repository; paths = new ArrayList<>(); } /** * Add path of submodule to update * * @param path * @return this operation */ public SubmoduleUpdateOperation addPath(final String path) { paths.add(path); return this; } @Override public void execute(final IProgressMonitor monitor) throws CoreException { IWorkspaceRunnable action = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor pm) throws CoreException { SubMonitor progress = SubMonitor.convert(pm, 4); progress.setTaskName(MessageFormat.format( CoreText.SubmoduleUpdateOperation_updating,
RepositoryUtil.INSTANCE.getRepositoryName(repository)));
1
2023-10-20 15:17:51+00:00
24k
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/query/Q12.java
[ { "identifier": "OrderLine", "path": "code/src/main/java/bean/OrderLine.java", "snippet": "@Getter\npublic class OrderLine {\n public Timestamp ol_delivery_d;\n public Timestamp ol_receipdate;\n public Timestamp ol_commitdate;\n\n public OrderLine(Timestamp ol_delivery_d, Timestamp ol_commit...
import bean.OrderLine; import bean.ReservoirSamplingSingleton; 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 benchmark.oltp.OLTPClient.gloabalSysCurrentTime; import static config.CommonConfig.DB_OCEANBASE; import static config.CommonConfig.DB_POSTGRES;
14,679
package benchmark.olap.query; public class Q12 extends baseQuery { private static Logger log = Logger.getLogger(Q12.class); public double k; public double b; private int dbType; public Q12(int dbType) throws ParseException { super(); this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.filterRate = benchmark.olap.OLAPClient.filterRate[11]; //ol_receipdate=0.1518 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException {
package benchmark.olap.query; public class Q12 extends baseQuery { private static Logger log = Logger.getLogger(Q12.class); public double k; public double b; private int dbType; public Q12(int dbType) throws ParseException { super(); this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.filterRate = benchmark.olap.OLAPClient.filterRate[11]; //ol_receipdate=0.1518 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException {
double countNumber = OLAPTerminal.orderLineTableSize.get() * filterRate;
2
2023-10-22 11:22:32+00:00
24k
bowbahdoe/java-audio-stack
vorbisspi/src/main/java/dev/mccue/vorbisspi/vorbis/sampled/convert/DecodedVorbisAudioInputStream.java
[ { "identifier": "PropertiesContainer", "path": "vorbisspi/src/main/java/dev/mccue/vorbisspi/PropertiesContainer.java", "snippet": "public interface PropertiesContainer\r\n{\r\n\tpublic Map properties();\r\n}\r" }, { "identifier": "TDebug", "path": "tritonus-share/src/main/java/dev/mccue/trit...
import dev.mccue.vorbisspi.PropertiesContainer; import dev.mccue.tritonus.share.TDebug; import dev.mccue.tritonus.share.sampled.convert.TAsynchronousFilteredAudioInputStream; import dev.mccue.jogg.Packet; import dev.mccue.jogg.Page; import dev.mccue.jogg.StreamState; import dev.mccue.jogg.SyncState; import dev.mccue.jorbis.Block; import dev.mccue.jorbis.Comment; import dev.mccue.jorbis.DspState; import dev.mccue.jorbis.Info; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream;
20,318
/* * DecodedVorbisAudioInputStream * * JavaZOOM : vorbisspi@javazoom.net * http://www.javazoom.net * * ---------------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * ---------------------------------------------------------------------------- */ package dev.mccue.vorbisspi.vorbis.sampled.convert; /** * This class implements the Vorbis decoding. */ @SuppressWarnings("unchecked") public class DecodedVorbisAudioInputStream extends TAsynchronousFilteredAudioInputStream implements PropertiesContainer { private InputStream oggBitStream_ = null; private SyncState oggSyncState_ = null; private StreamState oggStreamState_ = null; private Page oggPage_ = null; private Packet oggPacket_ = null; private Info vorbisInfo = null; private Comment vorbisComment = null;
/* * DecodedVorbisAudioInputStream * * JavaZOOM : vorbisspi@javazoom.net * http://www.javazoom.net * * ---------------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * ---------------------------------------------------------------------------- */ package dev.mccue.vorbisspi.vorbis.sampled.convert; /** * This class implements the Vorbis decoding. */ @SuppressWarnings("unchecked") public class DecodedVorbisAudioInputStream extends TAsynchronousFilteredAudioInputStream implements PropertiesContainer { private InputStream oggBitStream_ = null; private SyncState oggSyncState_ = null; private StreamState oggStreamState_ = null; private Page oggPage_ = null; private Packet oggPacket_ = null; private Info vorbisInfo = null; private Comment vorbisComment = null;
private DspState vorbisDspState = null;
9
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,465
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();
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)
4
2023-10-17 22:34:04+00:00
24k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/admin/userprofiles/UserProfileServiceImpl.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.db.entities.UserPermission; import org.msh.etbm.db.entities.UserProfile; import org.msh.etbm.services.security.permissions.Permission; import org.msh.etbm.services.security.permissions.Permissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.validation.Errors; import java.util.ArrayList; import java.util.List; import java.util.UUID;
15,369
package org.msh.etbm.services.admin.userprofiles; /** * Implementation of the User profile service for CRUD operations * <p> * Created by rmemoria on 26/1/16. */ @Service public class UserProfileServiceImpl extends EntityServiceImpl<UserProfile, UserProfileQueryParams> implements UserProfileService { private static final String CMD_NAME = "profiles"; @Autowired Permissions permissions; @Override protected void buildQuery(QueryBuilder<UserProfile> builder, UserProfileQueryParams queryParams) { // add profiles builder.addProfile(UserProfileQueryParams.PROFILE_ITEM, SynchronizableItem.class); builder.addDefaultProfile(UserProfileQueryParams.PROFILE_DEFAULT, SynchronizableItem.class); builder.addProfile(UserProfileQueryParams.PROFILE_DETAILED, UserProfileDetailedData.class); // add order by builder.addDefaultOrderByMap(UserProfileQueryParams.ORDERBY_NAME, "name"); if (queryParams.getWorkspaceId() != null) { builder.setWorkspaceId(queryParams.getWorkspaceId()); } } @Override protected void mapRequest(EntityServiceContext<UserProfile> context) { UserProfile entity = context.getEntity(); if (entity.getPermissions().size() > 0) { entity.getPermissions().clear(); removeOldPermissions(entity); } super.mapRequest(context); } @Override public String getCommandType() { return CommandTypes.ADMIN_USERPROFILES; } @Override protected void beforeSave(EntityServiceContext<UserProfile> context, Errors errors) { UserProfile entity = context.getEntity(); List<Permission> toadd = new ArrayList<>(); // check user permissions int index = 0; while (index < entity.getPermissions().size()) { UserPermission userperm = entity.getPermissions().get(index); // set the user profile userperm.setUserProfile(entity); // search for permission by its ID Permission p = permissions.find(userperm.getPermission()); // permission not found ? if (p == null) { errors.reject("Invalid permission: " + userperm.getPermission()); break; } // is there a parent permission ? if (p.getParent() != null) { // search for the parent permission in the list of user permissions UserPermission parent = entity.permissionByPermissionID(p.getParent().getId()); // parent permission was not found ? if (parent == null) { // create a new user permission parent = new UserPermission(); parent.setPermission(p.getParent().getId()); parent.setCanChange(p.getParent().isChangeable()); // add it to the end of the list, so it will be analysed in the loop entity.getPermissions().add(parent); } } index++; } } /** * Delete the previous permissions of an user profile being edited * * @param userProfile the user profile */ protected void removeOldPermissions(UserProfile userProfile) { // is a new user profile? So do nothing if (userProfile.getId() == null) { return; } getEntityManager().createQuery("delete from UserPermission where userProfile.id = :id") .setParameter("id", userProfile.getId()) .executeUpdate(); } @Override public String getFormCommandName() { return CMD_NAME; } @Override
package org.msh.etbm.services.admin.userprofiles; /** * Implementation of the User profile service for CRUD operations * <p> * Created by rmemoria on 26/1/16. */ @Service public class UserProfileServiceImpl extends EntityServiceImpl<UserProfile, UserProfileQueryParams> implements UserProfileService { private static final String CMD_NAME = "profiles"; @Autowired Permissions permissions; @Override protected void buildQuery(QueryBuilder<UserProfile> builder, UserProfileQueryParams queryParams) { // add profiles builder.addProfile(UserProfileQueryParams.PROFILE_ITEM, SynchronizableItem.class); builder.addDefaultProfile(UserProfileQueryParams.PROFILE_DEFAULT, SynchronizableItem.class); builder.addProfile(UserProfileQueryParams.PROFILE_DETAILED, UserProfileDetailedData.class); // add order by builder.addDefaultOrderByMap(UserProfileQueryParams.ORDERBY_NAME, "name"); if (queryParams.getWorkspaceId() != null) { builder.setWorkspaceId(queryParams.getWorkspaceId()); } } @Override protected void mapRequest(EntityServiceContext<UserProfile> context) { UserProfile entity = context.getEntity(); if (entity.getPermissions().size() > 0) { entity.getPermissions().clear(); removeOldPermissions(entity); } super.mapRequest(context); } @Override public String getCommandType() { return CommandTypes.ADMIN_USERPROFILES; } @Override protected void beforeSave(EntityServiceContext<UserProfile> context, Errors errors) { UserProfile entity = context.getEntity(); List<Permission> toadd = new ArrayList<>(); // check user permissions int index = 0; while (index < entity.getPermissions().size()) { UserPermission userperm = entity.getPermissions().get(index); // set the user profile userperm.setUserProfile(entity); // search for permission by its ID Permission p = permissions.find(userperm.getPermission()); // permission not found ? if (p == null) { errors.reject("Invalid permission: " + userperm.getPermission()); break; } // is there a parent permission ? if (p.getParent() != null) { // search for the parent permission in the list of user permissions UserPermission parent = entity.permissionByPermissionID(p.getParent().getId()); // parent permission was not found ? if (parent == null) { // create a new user permission parent = new UserPermission(); parent.setPermission(p.getParent().getId()); parent.setCanChange(p.getParent().isChangeable()); // add it to the end of the list, so it will be analysed in the loop entity.getPermissions().add(parent); } } index++; } } /** * Delete the previous permissions of an user profile being edited * * @param userProfile the user profile */ protected void removeOldPermissions(UserProfile userProfile) { // is a new user profile? So do nothing if (userProfile.getId() == null) { return; } getEntityManager().createQuery("delete from UserPermission where userProfile.id = :id") .setParameter("id", userProfile.getId()) .executeUpdate(); } @Override public String getFormCommandName() { return CMD_NAME; } @Override
public List<Item> execFormRequest(FormRequest req) {
0
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;
19,740
/* * 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. */
/* * 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;
7
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,356
/* * 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
/* * 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;
13
2023-11-03 03:46:01+00:00
24k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/fragments/home/HomeFragment.java
[ { "identifier": "ClassAdapter", "path": "app/src/main/java/com/daominh/quickmem/adapter/group/ClassAdapter.java", "snippet": "public class ClassAdapter extends RecyclerView.Adapter<ClassAdapter.ClassViewHolder> {\n private final Context context;\n private final ArrayList<Group> classes;\n\n pub...
import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.daominh.quickmem.adapter.group.ClassAdapter; import com.daominh.quickmem.adapter.folder.FolderAdapter; import com.daominh.quickmem.adapter.flashcard.SetsAdapter; import com.daominh.quickmem.data.dao.FlashCardDAO; import com.daominh.quickmem.data.dao.FolderDAO; import com.daominh.quickmem.data.dao.GroupDAO; import com.daominh.quickmem.data.model.FlashCard; import com.daominh.quickmem.data.model.Folder; import com.daominh.quickmem.data.model.Group; import com.daominh.quickmem.databinding.FragmentHomeBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.create.CreateSetActivity; import com.daominh.quickmem.ui.activities.search.ViewSearchActivity; import org.jetbrains.annotations.NotNull; import java.util.ArrayList;
14,739
package com.daominh.quickmem.ui.fragments.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private UserSharePreferences userSharePreferences; private SetsAdapter setsAdapter; private FolderAdapter folderAdapter; private ClassAdapter classAdapter; private ArrayList<FlashCard> flashCards; private ArrayList<Folder> folders; private ArrayList<Group> classes; private FlashCardDAO flashCardDAO; private FolderDAO folderDAO; private GroupDAO groupDAO; private String idUser; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); flashCardDAO = new FlashCardDAO(requireActivity()); folderDAO = new FolderDAO(requireActivity()); groupDAO = new GroupDAO(requireActivity()); } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); setupFlashCards(); setupFolders(); setupClasses(); setupVisibility(); setupSwipeRefreshLayout(); setupSearchBar(); setupCreateSetsButton(); binding.swipeRefreshLayout.setOnRefreshListener(() -> { refreshData(); binding.swipeRefreshLayout.setRefreshing(false); Toast.makeText(requireActivity(), "Refreshed", Toast.LENGTH_SHORT).show(); }); } @SuppressLint("NotifyDataSetChanged") private void setupFlashCards() { flashCards = flashCardDAO.getAllFlashCardByUserId(idUser); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.setsRv.setLayoutManager(linearLayoutManager); setsAdapter = new SetsAdapter(requireActivity(), flashCards, false); binding.setsRv.setAdapter(setsAdapter); setsAdapter.notifyDataSetChanged(); } @SuppressLint("NotifyDataSetChanged") private void setupFolders() { folders = folderDAO.getAllFolderByUserId(idUser); folderAdapter = new FolderAdapter(requireActivity(), folders); LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.foldersRv.setLayoutManager(linearLayoutManager1); binding.foldersRv.setAdapter(folderAdapter); folderAdapter.notifyDataSetChanged(); } @SuppressLint("NotifyDataSetChanged") private void setupClasses() { classes = groupDAO.getClassesOwnedByUser(idUser); classes.addAll(groupDAO.getClassesUserIsMemberOf(idUser)); classAdapter = new ClassAdapter(requireActivity(), classes); LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.classesRv.setLayoutManager(linearLayoutManager2); binding.classesRv.setAdapter(classAdapter); classAdapter.notifyDataSetChanged(); } private void setupVisibility() { if (flashCards.isEmpty()) { binding.setsCl.setVisibility(View.GONE); } else { binding.setsCl.setVisibility(View.VISIBLE); } if (folders.isEmpty()) { binding.folderCl.setVisibility(View.GONE); } else { binding.folderCl.setVisibility(View.VISIBLE); } if (classes.isEmpty()) { binding.classCl.setVisibility(View.GONE); } else { binding.classCl.setVisibility(View.VISIBLE); } } private void setupSwipeRefreshLayout() { binding.swipeRefreshLayout.setOnRefreshListener(() -> { refreshData(); binding.swipeRefreshLayout.setRefreshing(false); }); } private void setupSearchBar() { binding.searchBar.setOnClickListener(v -> { Intent intent = new Intent(requireActivity(), ViewSearchActivity.class); startActivity(intent); }); } private void setupCreateSetsButton() {
package com.daominh.quickmem.ui.fragments.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private UserSharePreferences userSharePreferences; private SetsAdapter setsAdapter; private FolderAdapter folderAdapter; private ClassAdapter classAdapter; private ArrayList<FlashCard> flashCards; private ArrayList<Folder> folders; private ArrayList<Group> classes; private FlashCardDAO flashCardDAO; private FolderDAO folderDAO; private GroupDAO groupDAO; private String idUser; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); flashCardDAO = new FlashCardDAO(requireActivity()); folderDAO = new FolderDAO(requireActivity()); groupDAO = new GroupDAO(requireActivity()); } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); setupFlashCards(); setupFolders(); setupClasses(); setupVisibility(); setupSwipeRefreshLayout(); setupSearchBar(); setupCreateSetsButton(); binding.swipeRefreshLayout.setOnRefreshListener(() -> { refreshData(); binding.swipeRefreshLayout.setRefreshing(false); Toast.makeText(requireActivity(), "Refreshed", Toast.LENGTH_SHORT).show(); }); } @SuppressLint("NotifyDataSetChanged") private void setupFlashCards() { flashCards = flashCardDAO.getAllFlashCardByUserId(idUser); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.setsRv.setLayoutManager(linearLayoutManager); setsAdapter = new SetsAdapter(requireActivity(), flashCards, false); binding.setsRv.setAdapter(setsAdapter); setsAdapter.notifyDataSetChanged(); } @SuppressLint("NotifyDataSetChanged") private void setupFolders() { folders = folderDAO.getAllFolderByUserId(idUser); folderAdapter = new FolderAdapter(requireActivity(), folders); LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.foldersRv.setLayoutManager(linearLayoutManager1); binding.foldersRv.setAdapter(folderAdapter); folderAdapter.notifyDataSetChanged(); } @SuppressLint("NotifyDataSetChanged") private void setupClasses() { classes = groupDAO.getClassesOwnedByUser(idUser); classes.addAll(groupDAO.getClassesUserIsMemberOf(idUser)); classAdapter = new ClassAdapter(requireActivity(), classes); LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.classesRv.setLayoutManager(linearLayoutManager2); binding.classesRv.setAdapter(classAdapter); classAdapter.notifyDataSetChanged(); } private void setupVisibility() { if (flashCards.isEmpty()) { binding.setsCl.setVisibility(View.GONE); } else { binding.setsCl.setVisibility(View.VISIBLE); } if (folders.isEmpty()) { binding.folderCl.setVisibility(View.GONE); } else { binding.folderCl.setVisibility(View.VISIBLE); } if (classes.isEmpty()) { binding.classCl.setVisibility(View.GONE); } else { binding.classCl.setVisibility(View.VISIBLE); } } private void setupSwipeRefreshLayout() { binding.swipeRefreshLayout.setOnRefreshListener(() -> { refreshData(); binding.swipeRefreshLayout.setRefreshing(false); }); } private void setupSearchBar() { binding.searchBar.setOnClickListener(v -> { Intent intent = new Intent(requireActivity(), ViewSearchActivity.class); startActivity(intent); }); } private void setupCreateSetsButton() {
binding.createSetsCl.setOnClickListener(v -> startActivity(new Intent(getActivity(), CreateSetActivity.class)));
10
2023-11-07 16:56:39+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;
19,223
/* * 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 { ensureSmdpAddressIsAvailable(); Log.debug(TAG, "ES9+ -> : " + initiateAuthenticationRequest); InitiateAuthenticationReq initiateAuthenticationReq = new InitiateAuthenticationReq(); initiateAuthenticationReq.setRequest(initiateAuthenticationRequest); HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(initiateAuthenticationReq), smdpAddress, INITIATE_AUTHENTICATION_PATH, true); checkHttpStatusCode("InitiateAuthentication", httpResponse, HttpsURLConnection.HTTP_OK); InitiateAuthenticationResp initiateAuthenticationResp = GS.fromJson(httpResponse.getContent(), InitiateAuthenticationResp.class); checkFunctionExecutionStatus("InitiateAuthentication", initiateAuthenticationResp); InitiateAuthenticationResponse initiateAuthenticationResponse = initiateAuthenticationResp.getResponse(); Log.debug(TAG, "ES9+ <- : " + initiateAuthenticationResponse); return initiateAuthenticationResponse; } public AuthenticateClientResponseEs9 authenticateClient(AuthenticateClientRequest authenticateClientRequest) throws Exception { ensureSmdpAddressIsAvailable(); Log.debug(TAG, "ES9+ -> : " + authenticateClientRequest); AuthenticateClientReq authenticateClientReq = new AuthenticateClientReq(); authenticateClientReq.setRequest(authenticateClientRequest); HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(authenticateClientReq), smdpAddress, AUTHENTICATE_CLIENT_PATH, true); checkHttpStatusCode("AuthenticateClient", httpResponse, HttpsURLConnection.HTTP_OK); AuthenticateClientResp authenticateClientResp = GS.fromJson(httpResponse.getContent(), AuthenticateClientResp.class); checkFunctionExecutionStatus("AuthenticateClient", authenticateClientResp); AuthenticateClientResponseEs9 authenticateClientResponseEs9 = authenticateClientResp.getResponse(); Log.debug(TAG, "ES9+ <- : " + authenticateClientResponseEs9); return authenticateClientResponseEs9; }
/* * 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 { ensureSmdpAddressIsAvailable(); Log.debug(TAG, "ES9+ -> : " + initiateAuthenticationRequest); InitiateAuthenticationReq initiateAuthenticationReq = new InitiateAuthenticationReq(); initiateAuthenticationReq.setRequest(initiateAuthenticationRequest); HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(initiateAuthenticationReq), smdpAddress, INITIATE_AUTHENTICATION_PATH, true); checkHttpStatusCode("InitiateAuthentication", httpResponse, HttpsURLConnection.HTTP_OK); InitiateAuthenticationResp initiateAuthenticationResp = GS.fromJson(httpResponse.getContent(), InitiateAuthenticationResp.class); checkFunctionExecutionStatus("InitiateAuthentication", initiateAuthenticationResp); InitiateAuthenticationResponse initiateAuthenticationResponse = initiateAuthenticationResp.getResponse(); Log.debug(TAG, "ES9+ <- : " + initiateAuthenticationResponse); return initiateAuthenticationResponse; } public AuthenticateClientResponseEs9 authenticateClient(AuthenticateClientRequest authenticateClientRequest) throws Exception { ensureSmdpAddressIsAvailable(); Log.debug(TAG, "ES9+ -> : " + authenticateClientRequest); AuthenticateClientReq authenticateClientReq = new AuthenticateClientReq(); authenticateClientReq.setRequest(authenticateClientRequest); HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(authenticateClientReq), smdpAddress, AUTHENTICATE_CLIENT_PATH, true); checkHttpStatusCode("AuthenticateClient", httpResponse, HttpsURLConnection.HTTP_OK); AuthenticateClientResp authenticateClientResp = GS.fromJson(httpResponse.getContent(), AuthenticateClientResp.class); checkFunctionExecutionStatus("AuthenticateClient", authenticateClientResp); AuthenticateClientResponseEs9 authenticateClientResponseEs9 = authenticateClientResp.getResponse(); Log.debug(TAG, "ES9+ <- : " + authenticateClientResponseEs9); return authenticateClientResponseEs9; }
public GetBoundProfilePackageResponse getBoundProfilePackage(GetBoundProfilePackageRequest getBoundProfilePackageRequest) throws Exception {
5
2023-11-06 02:41:13+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,640
while (resultSet.next()) { userList.add(CUser.fromResultSet(resultSet)); } } catch (SQLException e) { Main.getMessage().error(e); } return userList; } private List<CUnsoldItem> parseUnsoldItems() { List<CUnsoldItem> userList = new ArrayList<>(); String query = "SELECT * FROM unsold_items"; try (PreparedStatement preparedStatement = connection.prepareStatement(query); ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { userList.add(CUnsoldItem.fromResultSet(resultSet)); } } catch (SQLException e) { Main.getMessage().error(e); } return userList; } private List<Action> parseLogs() { List<Action> actions = new ArrayList<>(); String query = String.format("SELECT type, owner, uuid FROM `logs` WHERE time > %s AND server != '%s'", lastLogCheck, server); try (PreparedStatement preparedStatement = connection.prepareStatement(query); ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { actions.add(Action.fromResultSet(resultSet)); } } catch (SQLException e) { Main.getMessage().error(e); } lastLogCheck = System.currentTimeMillis(); return actions; } private void applyLogs(List<Action> actions) { for (Action action : actions) { try { switch (action.getType()) { case ADD_SELL_ITEM -> { if (hasSellItem(action.getItem())) { break; } try (PreparedStatement preparedStatement = connection.prepareStatement(String.format("SELECT * FROM sell_items WHERE uuid = '%s'", action.getItem().getKey())); ResultSet resultSet = preparedStatement.executeQuery()) { if (!resultSet.next()) break; CSellItem sellItem = CSellItem.fromResultSet(resultSet); writeLock(() -> addSellItem0(sellItem)); } } case UPDATE_USER -> { try (PreparedStatement preparedStatement = connection.prepareStatement(String.format("SELECT * FROM users WHERE uuid = '%s'", action.getOwner())); ResultSet resultSet = preparedStatement.executeQuery()) { if (!resultSet.next()) break; CUser user = CUser.fromResultSet(resultSet); if (hasUser(user.uuid)) { writeLock(() -> super.replaceUser(user)); } else { writeLock(() -> super.addUser(user)); } boostCheck(user.uuid); } } case ADD_UNSOLD_ITEM -> { if (hasUnsoldItem(action.getItem())) break; try (PreparedStatement preparedStatement = connection.prepareStatement(String.format("SELECT * FROM unsold_items WHERE uuid = '%s'", action.getItem().getKey())); ResultSet resultSet = preparedStatement.executeQuery()) { if (!resultSet.next()) break; CUnsoldItem unsoldItem = CUnsoldItem.fromResultSet(resultSet); writeLock(() -> addUnsoldItem0(unsoldItem)); } } case REMOVE_SELL_ITEM -> { if (!hasSellItem(action.getItem())) break; super.removeSellItem(action.getItem()); } case REMOVE_UNSOLD_ITEM -> { if (!hasUnsoldItem(action.getItem())) break; super.removeUnsoldItem(action.getItem()); } } } catch (SQLException e) { Main.getMessage().error("failed to apply log '%s'", e, action); } } } @Override public void close() { super.close(); try { connection.close(); } catch (SQLException e) { Main.getMessage().error(e); } packetConnection.close(); sqlExecuteTask.cancel(); if (logClearTask != null) logClearTask.cancel(); updateTask.cancel(); moneyGiver.close(); } @Override public void save() { } @Override protected void update() { if ((System.currentTimeMillis() - lastLogCheck) > 1500) { applyLogs(parseLogs()); applyGiveMoney(); } } private void applyGiveMoney() {
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 super.validateAndRemoveItem(event); if (event.isValid()) { updateUsers(event.getUser().getUuid(), event.getSellItem().getSellerUuid()); } } @Override public void validateAndRemoveItem(BuyItemCountEvent event) { // hook super.validateAndRemoveItem(event); if (event.isValid()) { updateUsers(event.getUser().getUuid(), event.getSellItem().getSellerUuid()); } } @Override public UnsoldItem removeUnsoldItem(UniqueName name) { UnsoldItem unsoldItem = super.removeUnsoldItem(name); execute("DELETE FROM unsold_items WHERE uuid = '%s';", name.getKey()); log(new Action(ActionType.REMOVE_UNSOLD_ITEM, unsoldItem.getSellerUuid(), name, server)); packetConnection.saveSend(new PlayOutRemoveUnsoldItemPacket(name)); return unsoldItem; } @Override public void addUnsoldItem(CUnsoldItem unsoldItem) { super.addUnsoldItem(unsoldItem); execute(unsoldItem.toSql("unsold_items")); log(new Action(ActionType.ADD_UNSOLD_ITEM, unsoldItem.getSellerUuid(), unsoldItem.uniqueName, server)); packetConnection.saveSend(new PlayOutAddUnsoldItemPacket(unsoldItem)); } @Override public SellItem removeSellItem(UniqueName name) { SellItem item = super.removeSellItem(name); execute("DELETE FROM sell_items WHERE uuid = '%s';", name.getKey()); log(new Action(ActionType.REMOVE_SELL_ITEM, item.getSellerUuid(), item.getUniqueName(), server)); packetConnection.saveSend(new PlayOutRemoveSellItemPacket(name)); return item; } protected void execute(String sql) { sqlQueue.offer(sql); } protected void execute(String sql, Object... objects) { execute(String.format(sql, objects)); } public void addSqlToQueue(String sql) { execute(sql); } public void addSqlToQueue(String sql, Object... objects) { execute(sql, objects); } protected void log(Action action) { sqlQueue.offer(action.toSql("logs")); } @Override public void load() { writeLock(() -> { List<CSellItem> items = parseSellItems(); List<CUser> users = parseUsers(); List<CUnsoldItem> unsoldItems = parseUnsoldItems(); lastLogCheck = System.currentTimeMillis(); if (!items.isEmpty() || !users.isEmpty() || !unsoldItems.isEmpty()) { load(items, users, unsoldItems); } }); } private List<CSellItem> parseSellItems() { List<CSellItem> sellItems = new ArrayList<>(); String query = "SELECT * FROM sell_items"; try (PreparedStatement preparedStatement = connection.prepareStatement(query); ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { sellItems.add(CSellItem.fromResultSet(resultSet)); } } catch (SQLException e) { Main.getMessage().error(e); } return sellItems; } private List<CUser> parseUsers() { List<CUser> userList = new ArrayList<>(); String query = "SELECT * FROM users"; try (PreparedStatement preparedStatement = connection.prepareStatement(query); ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { userList.add(CUser.fromResultSet(resultSet)); } } catch (SQLException e) { Main.getMessage().error(e); } return userList; } private List<CUnsoldItem> parseUnsoldItems() { List<CUnsoldItem> userList = new ArrayList<>(); String query = "SELECT * FROM unsold_items"; try (PreparedStatement preparedStatement = connection.prepareStatement(query); ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { userList.add(CUnsoldItem.fromResultSet(resultSet)); } } catch (SQLException e) { Main.getMessage().error(e); } return userList; } private List<Action> parseLogs() { List<Action> actions = new ArrayList<>(); String query = String.format("SELECT type, owner, uuid FROM `logs` WHERE time > %s AND server != '%s'", lastLogCheck, server); try (PreparedStatement preparedStatement = connection.prepareStatement(query); ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { actions.add(Action.fromResultSet(resultSet)); } } catch (SQLException e) { Main.getMessage().error(e); } lastLogCheck = System.currentTimeMillis(); return actions; } private void applyLogs(List<Action> actions) { for (Action action : actions) { try { switch (action.getType()) { case ADD_SELL_ITEM -> { if (hasSellItem(action.getItem())) { break; } try (PreparedStatement preparedStatement = connection.prepareStatement(String.format("SELECT * FROM sell_items WHERE uuid = '%s'", action.getItem().getKey())); ResultSet resultSet = preparedStatement.executeQuery()) { if (!resultSet.next()) break; CSellItem sellItem = CSellItem.fromResultSet(resultSet); writeLock(() -> addSellItem0(sellItem)); } } case UPDATE_USER -> { try (PreparedStatement preparedStatement = connection.prepareStatement(String.format("SELECT * FROM users WHERE uuid = '%s'", action.getOwner())); ResultSet resultSet = preparedStatement.executeQuery()) { if (!resultSet.next()) break; CUser user = CUser.fromResultSet(resultSet); if (hasUser(user.uuid)) { writeLock(() -> super.replaceUser(user)); } else { writeLock(() -> super.addUser(user)); } boostCheck(user.uuid); } } case ADD_UNSOLD_ITEM -> { if (hasUnsoldItem(action.getItem())) break; try (PreparedStatement preparedStatement = connection.prepareStatement(String.format("SELECT * FROM unsold_items WHERE uuid = '%s'", action.getItem().getKey())); ResultSet resultSet = preparedStatement.executeQuery()) { if (!resultSet.next()) break; CUnsoldItem unsoldItem = CUnsoldItem.fromResultSet(resultSet); writeLock(() -> addUnsoldItem0(unsoldItem)); } } case REMOVE_SELL_ITEM -> { if (!hasSellItem(action.getItem())) break; super.removeSellItem(action.getItem()); } case REMOVE_UNSOLD_ITEM -> { if (!hasUnsoldItem(action.getItem())) break; super.removeUnsoldItem(action.getItem()); } } } catch (SQLException e) { Main.getMessage().error("failed to apply log '%s'", e, action); } } } @Override public void close() { super.close(); try { connection.close(); } catch (SQLException e) { Main.getMessage().error(e); } packetConnection.close(); sqlExecuteTask.cancel(); if (logClearTask != null) logClearTask.cancel(); updateTask.cancel(); moneyGiver.close(); } @Override public void save() { } @Override protected void update() { if ((System.currentTimeMillis() - lastLogCheck) > 1500) { applyLogs(parseLogs()); applyGiveMoney(); } } private void applyGiveMoney() {
List<ActionGiveMoney> actions = new ArrayList<>();
4
2023-11-08 18:25:18+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,807
/* * 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; private final Boolean holdLockOnServiceUnavailable; private final ScheduledExecutorService executorService; public MomentoDynamoDBLockClient(final MomentoDynamoDBLockClientOptions lockClientOptions) {
/* * 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; private final Boolean holdLockOnServiceUnavailable; private final ScheduledExecutorService executorService; public MomentoDynamoDBLockClient(final MomentoDynamoDBLockClientOptions lockClientOptions) {
super(AmazonDynamoDBLockClientOptions.builder(new NoopDynamoDbClient(), lockClientOptions.getCacheName()).build());
6
2023-11-07 03:56:11+00:00
24k
FallenDeity/GameEngine2DJava
src/main/java/engine/scenes/LevelEditorScene.java
[ { "identifier": "Sprite", "path": "src/main/java/engine/components/sprites/Sprite.java", "snippet": "public class Sprite {\n\tprivate Texture texture = null;\n\tprivate float width = 0, height = 0;\n\tprivate Vector2f[] texCoords =\n\t\t\tnew Vector2f[]{\n\t\t\t\t\tnew Vector2f(1, 1), new Vector2f(1, 0)...
import engine.components.*; import engine.components.sprites.Sprite; import engine.components.sprites.SpriteSheet; import engine.editor.JImGui; import engine.physics2d.components.Box2DCollider; import engine.physics2d.components.RigidBody2D; import engine.physics2d.enums.BodyType; import engine.renderer.Sound; import engine.ruby.Window; import engine.util.AssetPool; import engine.util.CONSTANTS; import engine.util.PipeDirection; import engine.util.Prefabs; import imgui.ImGui; import imgui.ImVec2; import org.joml.Vector2f; import java.io.File; import java.util.ArrayList; import java.util.List;
16,118
package engine.scenes; public class LevelEditorScene extends Scene { private final SpriteSheet blocks; private final GameObject editor; public LevelEditorScene() { editor = createGameObject("Editor"); editor.setNotSerializable(); editor.addComponent(new MouseControls()); editor.addComponent(new KeyControls()); editor.addComponent(new GridLines()); editor.addComponent(new EditorCamera(camera)); editor.addComponent(new GizmoSystem(this, editor)); blocks = AssetPool.getSpriteSheet(CONSTANTS.BLOCK_SHEET_PATH.getValue(), 16, 16, 0, 81); addGameObjectToScene(editor); AssetPool.getSound(CONSTANTS.SOUNDS_PATH.getValue() + "main-theme-overworld.ogg").stop(); } public boolean gizmoActive() { GizmoSystem gizmoSystem = editor.getComponent(GizmoSystem.class); return gizmoSystem.gizmoActive(); } private List<Sound> loadSounds() { String sound_dir = CONSTANTS.SOUNDS_PATH.getValue(); File[] files = new File(sound_dir).listFiles(); if (files != null) { for (File file : files) { if (file.isFile() && file.getName().endsWith(".ogg")) { String path = file.getAbsolutePath(); AssetPool.getSound(path, false); } } } return new ArrayList<>(AssetPool.getSounds()); } private void addBlock(SpriteSheet sheet, int i, ImVec2 windowSize, ImVec2 itemSpacing, float windowX, boolean decoration) { Sprite sprite = sheet.getSprite(i); float spriteWidth = sprite.getWidth() * 3, spriteHeight = sprite.getHeight() * 3; Vector2f[] texCoords = sprite.getTexCoords(); int id = sprite.getTextureID(); ImGui.pushID(i); if (ImGui.imageButton( id, spriteWidth, spriteHeight, texCoords[2].x, texCoords[0].y, texCoords[0].x, texCoords[2].y)) { GameObject ob = Prefabs.generateSpriteObject(sprite, CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue()); if (!decoration) {
package engine.scenes; public class LevelEditorScene extends Scene { private final SpriteSheet blocks; private final GameObject editor; public LevelEditorScene() { editor = createGameObject("Editor"); editor.setNotSerializable(); editor.addComponent(new MouseControls()); editor.addComponent(new KeyControls()); editor.addComponent(new GridLines()); editor.addComponent(new EditorCamera(camera)); editor.addComponent(new GizmoSystem(this, editor)); blocks = AssetPool.getSpriteSheet(CONSTANTS.BLOCK_SHEET_PATH.getValue(), 16, 16, 0, 81); addGameObjectToScene(editor); AssetPool.getSound(CONSTANTS.SOUNDS_PATH.getValue() + "main-theme-overworld.ogg").stop(); } public boolean gizmoActive() { GizmoSystem gizmoSystem = editor.getComponent(GizmoSystem.class); return gizmoSystem.gizmoActive(); } private List<Sound> loadSounds() { String sound_dir = CONSTANTS.SOUNDS_PATH.getValue(); File[] files = new File(sound_dir).listFiles(); if (files != null) { for (File file : files) { if (file.isFile() && file.getName().endsWith(".ogg")) { String path = file.getAbsolutePath(); AssetPool.getSound(path, false); } } } return new ArrayList<>(AssetPool.getSounds()); } private void addBlock(SpriteSheet sheet, int i, ImVec2 windowSize, ImVec2 itemSpacing, float windowX, boolean decoration) { Sprite sprite = sheet.getSprite(i); float spriteWidth = sprite.getWidth() * 3, spriteHeight = sprite.getHeight() * 3; Vector2f[] texCoords = sprite.getTexCoords(); int id = sprite.getTextureID(); ImGui.pushID(i); if (ImGui.imageButton( id, spriteWidth, spriteHeight, texCoords[2].x, texCoords[0].y, texCoords[0].x, texCoords[2].y)) { GameObject ob = Prefabs.generateSpriteObject(sprite, CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue()); if (!decoration) {
RigidBody2D rb = new RigidBody2D();
4
2023-11-04 13:19:21+00:00
24k
RezaGooner/University-food-ordering
Frames/LoginFrame.java
[ { "identifier": "CustomRendererLoginHistory", "path": "Classes/Theme/CustomRendererLoginHistory.java", "snippet": "public class CustomRendererLoginHistory extends DefaultTableCellRenderer {\r\n private static final long serialVersionUID = 1L;\r\n\r\n @Override\r\n public Component getTableCellR...
import Classes.Theme.CustomRendererLoginHistory; import Classes.Theme.CustomRendererOrderCount; import Classes.Theme.StyledButtonUI; import Frames.Order.UniversitySelfRestaurant; import Frames.Profile.ChangePasswordFrame; import Frames.Profile.ForgotPassword; import Frames.Profile.NewUserFrame; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Scanner; import static Classes.Pathes.FilesPath.*; import static Classes.Theme.SoundEffect.*; import static Frames.Admin.AdminWindow.OpenAdminWindow;
20,830
} statusLabel.setText("شماره دانشجویی باید فقط شامل عدد باشد"); statusLabel.setForeground(Color.red); idField.setBackground(Color.YELLOW); idField.setForeground(Color.black); } else if (!isNumeric(id) || id.length() != 10) { try { errorSound(); } catch (Exception ex) { } statusLabel.setText("شماره دانشجویی باید 10 رقمی باشد"); statusLabel.setForeground(Color.red); idField.setBackground(Color.YELLOW); idField.setForeground(Color.black); } else if (password.length() == 0 ){ try { errorSound(); } catch (Exception ex) { } statusLabel.setText("لطفا کلمه عبور را وارد نمایید"); statusLabel.setForeground(Color.red); passwordField.setBackground(Color.YELLOW); passwordField.setForeground(Color.black); } else if ((password.length() < 8 )||(password.length() > 16) ) { try { errorSound(); } catch (Exception ex) { } statusLabel.setText("کلمه عبور باید بین 8 تا 16 کاراکتر باشد"); statusLabel.setForeground(Color.red); passwordField.setBackground(Color.YELLOW); passwordField.setForeground(Color.black); } else { try { BufferedReader reader = new BufferedReader(new FileReader(UserPassPath)); String line; while ((line = reader.readLine()) != null) { String[] parts = line.split(","); tempID = parts[0] ; if (tempID.equals(id) && parts[1].equals(password)) { name = parts[2]; lastName = parts[3]; gender = parts[4]; organization = parts[6]; isValid = true; break; } } reader.close(); } catch (IOException e) { try { errorSound(); } catch (Exception ex) { } } if (!isValid) { try { errorSound(); } catch (Exception ex) { } writeLog("ناموفق"); statusLabel.setText("شماره دانشجویی یا کلمه عبور اشتباه است"); statusLabel.setForeground(Color.red); Object[] options = { "خیر", "بله","ساخت حساب کاربری جدید"}; int noFoundUser = JOptionPane.showOptionDialog(this,"کاربری با این اطلاعات یافت نشد.\nآیا مایل هستید رمز خود را بازیابی کنید؟" , "خروج", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null , options , options[0]); if (noFoundUser == JOptionPane.NO_OPTION){ dispose(); new ForgotPassword(); } else if (noFoundUser == JOptionPane.CANCEL_OPTION){ dispose(); NewUserFrame frame = new NewUserFrame(); frame.setVisible(true); } idField.setBackground(Color.RED); idField.setForeground(Color.WHITE); passwordField.setBackground(Color.RED); passwordField.setForeground(Color.WHITE); } } return isValid; } private class LoginButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { String id = idField.getText(); String password = new String(passwordField.getPassword()); statusLabel.setForeground(Color.black); idField.setBackground(Color.white); idField.setForeground(Color.black); passwordField.setBackground(Color.white); passwordField.setForeground(Color.black); if (isValidLogin(id, password)) { writeLog("موفق"); if (gender.equals("MALE")) { try { wellcomeSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null , "آقای " + name + " " + lastName + " خوش آمدید!"); dispose(); try {
package Frames; /* این کد یک فریم ورود به برنامه است که به کاربران اجازه می‌دهد شماره دانشجویی و رمز عبور خود را وارد کنند و سپس توسط برنامه بررسی شود که این اطلاعات معتبر هستند یا خیر. برای بررسی صحت اطلاعات، برنامه از یک فایل متنی استفاده می‌کند که شماره دانشجویی و رمز عبور کاربران را در خود نگه می‌دارد. در صورتی که اطلاعات وارد شده توسط کاربر با اطلاعات موجود در فایل مطابقت داشته باشد، کاربر به صفحه اصلی برنامه برای سفارش غذا هدایت می‌شود. در غیر این صورت، پیام خطا به کاربر نمایش داده می‌شود و از کاربر خواسته می‌شود تا اطلاعات خود را بررسی کرده و مجدداً وارد کند یا در صورت لزوم، از طریق گزینه هایی که برای او نمایش داده می‌شود، اقدام به بازیابی رمز عبور یا ساخت حساب جدید کند. */ public class LoginFrame extends JFrame { public static boolean isNumeric(String str) { if (str == null || str.length() == 0) { return false; } try { Long.parseLong(str); } catch (NumberFormatException nfe) { return false; } return true; } private static JTextField idField; private final JPasswordField passwordField; private final JLabel statusLabel; private final JCheckBox showPasswordCheckbox; private String name , lastName , gender , organization; public static Color colorButton = new Color(255,255,255); public static Color colorBackground = new Color(241,255,85); private String tempID; public LoginFrame() { setTitle("ورود"); setIconImage(icon.getImage()); setSize(375, 175); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setBackground(colorBackground); JLabel idLabel = new JLabel(": شماره دانشجویی"); idLabel.setHorizontalAlignment(SwingConstants.CENTER); idField = new JTextField(10); JLabel passwordLabel = new JLabel(": کلمـــه عبــور"); passwordLabel.setHorizontalAlignment(SwingConstants.CENTER); passwordField = new JPasswordField(10); passwordField.setEchoChar('\u25cf'); showPasswordCheckbox = new JCheckBox("نمایش کلمه عبور"); showPasswordCheckbox.setBackground(colorBackground); JButton loginButton = new JButton("ورود"); loginButton.setUI(new StyledButtonUI()); loginButton.setBackground(colorButton); statusLabel = new JLabel(""); JPanel panel = new JPanel(new GridLayout(4, 1)); panel.setBackground(colorBackground); panel.add(idLabel); panel.add(idField); panel.add(passwordLabel); panel.add(passwordField); panel.add(showPasswordCheckbox); panel.add(loginButton); panel.add(statusLabel); JButton helpButton = new JButton("اطلاعیه ها"); panel.add(helpButton); helpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame subWindow = new JFrame(); setIconImage(icon.getImage()); subWindow.setTitle(""); subWindow.setSize(300, 200); subWindow.setVisible(true); try { FileReader fileReader = new FileReader(HelpPath); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); while ((line = bufferedReader.readLine()) != null) { if (line.equals("***")) { panel.add(new JSeparator(JSeparator.HORIZONTAL)); } else { JLabel label = new JLabel(line); label.setFont(new Font("Arial", Font.BOLD, 20)); label.setForeground(Color.RED); panel.add(label); } } JScrollPane scrollPane = new JScrollPane(panel); subWindow.add(scrollPane); bufferedReader.close(); } catch (IOException exception) { } JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(helpButton, BorderLayout.CENTER); panel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { subWindow.setVisible(true); } }); add(panel); FontMetrics fm = helpButton.getFontMetrics(helpButton.getFont()); int textWidth = fm.stringWidth(helpButton.getText()); int textHeight = fm.getHeight(); helpButton.setPreferredSize(new Dimension(textWidth, textHeight)); } }); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(colorButton); setJMenuBar(menuBar); JMenu menu = new JMenu("حساب کاربری"); menu.setBackground(colorButton); menuBar.add(menu); JMenuItem adminItem = new JMenuItem("ورود مدیریت"); adminItem.setBackground(colorButton); menu.add(adminItem); JMenuItem forgotItem = new JMenuItem("فراموشی رمز"); forgotItem.setBackground(colorButton); menu.add(forgotItem); JMenuItem changePassword = new JMenuItem("تغییر رمز"); changePassword.setBackground(colorButton); menu.add(changePassword); JMenuItem historyLoginButton = new JMenuItem("سابقه ورود"); historyLoginButton.setBackground(colorButton); menu.add(historyLoginButton); JMenuItem newUserItem = new JMenuItem("جدید"); newUserItem.setBackground(colorButton); menu.add(newUserItem); JMenuItem exitItem = new JMenuItem("خروج"); exitItem.setBackground(colorButton); menuBar.add(exitItem); adminItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { OpenAdminWindow(); } catch (Exception ex) { } } }); historyLoginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { showLoginHistory(); } catch (Exception ex) { } } }); changePassword.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); new ChangePasswordFrame(); } }); forgotItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); new ForgotPassword(); } }); newUserItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); new NewUserFrame(); } }); exitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] options = {"خیر", "بله"}; int exitResult = JOptionPane.showOptionDialog(panel, "آیا خارج می شوید؟", "خروج", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (exitResult == JOptionPane.NO_OPTION) dispose(); } }); add(panel); loginButton.addActionListener(new LoginButtonListener()); showPasswordCheckbox.addActionListener(new ShowPasswordCheckboxListener()); setResizable(false); setVisible(true); } private boolean isValidLogin(String id, String password) { boolean isValid = false; if (id.length() == 0 ) { try { errorSound(); } catch (Exception ex) { } statusLabel.setText("لطفا شماره دانشجویی را وارد نمایید"); statusLabel.setForeground(Color.red); idField.setBackground(Color.YELLOW); idField.setForeground(Color.black); }else if (! isNumeric(id) ) { try { errorSound(); } catch (Exception ex) { } statusLabel.setText("شماره دانشجویی باید فقط شامل عدد باشد"); statusLabel.setForeground(Color.red); idField.setBackground(Color.YELLOW); idField.setForeground(Color.black); } else if (!isNumeric(id) || id.length() != 10) { try { errorSound(); } catch (Exception ex) { } statusLabel.setText("شماره دانشجویی باید 10 رقمی باشد"); statusLabel.setForeground(Color.red); idField.setBackground(Color.YELLOW); idField.setForeground(Color.black); } else if (password.length() == 0 ){ try { errorSound(); } catch (Exception ex) { } statusLabel.setText("لطفا کلمه عبور را وارد نمایید"); statusLabel.setForeground(Color.red); passwordField.setBackground(Color.YELLOW); passwordField.setForeground(Color.black); } else if ((password.length() < 8 )||(password.length() > 16) ) { try { errorSound(); } catch (Exception ex) { } statusLabel.setText("کلمه عبور باید بین 8 تا 16 کاراکتر باشد"); statusLabel.setForeground(Color.red); passwordField.setBackground(Color.YELLOW); passwordField.setForeground(Color.black); } else { try { BufferedReader reader = new BufferedReader(new FileReader(UserPassPath)); String line; while ((line = reader.readLine()) != null) { String[] parts = line.split(","); tempID = parts[0] ; if (tempID.equals(id) && parts[1].equals(password)) { name = parts[2]; lastName = parts[3]; gender = parts[4]; organization = parts[6]; isValid = true; break; } } reader.close(); } catch (IOException e) { try { errorSound(); } catch (Exception ex) { } } if (!isValid) { try { errorSound(); } catch (Exception ex) { } writeLog("ناموفق"); statusLabel.setText("شماره دانشجویی یا کلمه عبور اشتباه است"); statusLabel.setForeground(Color.red); Object[] options = { "خیر", "بله","ساخت حساب کاربری جدید"}; int noFoundUser = JOptionPane.showOptionDialog(this,"کاربری با این اطلاعات یافت نشد.\nآیا مایل هستید رمز خود را بازیابی کنید؟" , "خروج", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null , options , options[0]); if (noFoundUser == JOptionPane.NO_OPTION){ dispose(); new ForgotPassword(); } else if (noFoundUser == JOptionPane.CANCEL_OPTION){ dispose(); NewUserFrame frame = new NewUserFrame(); frame.setVisible(true); } idField.setBackground(Color.RED); idField.setForeground(Color.WHITE); passwordField.setBackground(Color.RED); passwordField.setForeground(Color.WHITE); } } return isValid; } private class LoginButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { String id = idField.getText(); String password = new String(passwordField.getPassword()); statusLabel.setForeground(Color.black); idField.setBackground(Color.white); idField.setForeground(Color.black); passwordField.setBackground(Color.white); passwordField.setForeground(Color.black); if (isValidLogin(id, password)) { writeLog("موفق"); if (gender.equals("MALE")) { try { wellcomeSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null , "آقای " + name + " " + lastName + " خوش آمدید!"); dispose(); try {
new UniversitySelfRestaurant(id, name + " " + lastName , organization);
3
2023-11-03 08:35:22+00:00
24k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/main/KifParser.java
[ { "identifier": "GameAnalyser", "path": "src/main/java/com/chadfield/shogiexplorer/objects/GameAnalyser.java", "snippet": "public class GameAnalyser {\n\n private Process process;\n private OutputStream stdin;\n private BufferedReader bufferedReader;\n private String lastScore = \"\";\n p...
import com.chadfield.shogiexplorer.objects.GameAnalyser; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.LinkedList; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultListModel; import com.chadfield.shogiexplorer.objects.Board; import com.chadfield.shogiexplorer.objects.Board.Turn; import com.chadfield.shogiexplorer.objects.Coordinate; import com.chadfield.shogiexplorer.objects.Game; import com.chadfield.shogiexplorer.objects.Koma; import com.chadfield.shogiexplorer.objects.Notation; import com.chadfield.shogiexplorer.objects.Position; import com.chadfield.shogiexplorer.utils.NotationUtils; import com.chadfield.shogiexplorer.utils.ParserUtils; import com.ibm.icu.text.Transliterator; import java.io.StringReader; import java.nio.charset.Charset; import java.nio.charset.MalformedInputException; import java.nio.charset.StandardCharsets; import java.util.List;
19,316
if (board == null) { board = getStartBoard(game); positionList.add(new Position(SFENParser.getSFEN(board), null, null, new Notation())); } if (line.isEmpty()) { break; } if (isComment(line)) { positionList.getLast().setComment(positionList.getLast().getComment() + line.substring(1) + "\n"); continue; } if (!isRegularMove(line)) { break; } count++; board.setMoveCount(count); lastDestination = parseRegularMove(board, line, moveListModel, lastDestination, positionList); } } } catch (MalformedInputException ex) { return null; } finally { if (fileReader != null) { fileReader.close(); } } game.setPositionList(positionList); return game; } private static Board getStartBoard(Game game) { String sfen; sfen = switch (game.getHandicap()) { case Game.HANDICAP_LANCE -> "lnsgkgsn1/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_BISHOP -> "lnsgkgsnl/1r7/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_ROOK -> "lnsgkgsnl/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_ROOK_LANCE -> "lnsgkgsn1/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_2_PIECE -> "lnsgkgsnl/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_4_PIECE -> "1nsgkgsn1/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_6_PIECE -> "2sgkgs2/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_8_PIECE -> "3gkg3/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; default -> "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1"; }; return SFENParser.parse(sfen); } private static Coordinate parseRegularMove(Board board, String line, DefaultListModel<String> moveListModel, Coordinate lastDestination, LinkedList<Position> positionList) { String[] splitLine = line.trim().split(MULTI_WHITESPACE); int gameNum; try { gameNum = Integer.parseInt(splitLine[0]); } catch (NumberFormatException ex) { positionList.getLast().setComment(positionList.getLast().getComment() + line + "\n"); return lastDestination; } String move = extractRegularMove(splitLine, isSame(line)); Position position = executeMove(board, move, lastDestination); if (position != null) { lastDestination = position.getDestination(); addMoveToMoveList(moveListModel, gameNum, position.getNotation().getJapanese(), board.getNextTurn()); positionList.add(position); } return lastDestination; } private static String extractRegularMove(String[] moveArray, boolean isSame) { String move = moveArray[1]; if (isSame) { move += "\u3000" + moveArray[2]; } return move; } private static void parseGameDetails(String line, Game game) { if (line.startsWith(SENTE)) { game.setSente(line.substring(SENTE.length()).trim()); } if (line.startsWith(GOTE)) { game.setGote(line.substring(GOTE.length()).trim()); } if (line.startsWith(PLACE)) { game.setPlace(line.substring(PLACE.length()).trim()); } if (line.startsWith(HANDICAP)) { game.setHandicap(line.substring(HANDICAP.length()).trim()); } if (line.startsWith(TIME_LIMIT)) { game.setTimeLimit(line.substring(TIME_LIMIT.length()).trim()); } if (line.startsWith(TOURNAMENT)) { game.setTournament(line.substring(TOURNAMENT.length()).trim()); } if (line.startsWith(DATE)) { game.setDate(line.substring(DATE.length()).trim()); } }
/* 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.main; public class KifParser { private static final String DATE = "開始日時:"; private static final String PLACE = "場所:"; private static final String TIME_LIMIT = "持ち時間:"; private static final String TOURNAMENT = "棋戦:"; private static final String SENTE = "先手:"; private static final String GOTE = "後手:"; private static final String MOVE_HEADER = "手数----指手---------消費時間-"; private static final String MULTI_WHITESPACE = "\\s+|\\u3000"; private static final String HANDICAP = "手合割:"; private KifParser() { throw new IllegalStateException("Utility class"); } public static Game parseKif(DefaultListModel<String> moveListModel, File kifFile, String clipboardStr, boolean shiftFile, List<List<Position>> analysisPositionList) throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("Bundle"); moveListModel.clear(); moveListModel.addElement(bundle.getString("label_start_position")); Board board = null; Game game = new Game(); game.setAnalysisPositionList(analysisPositionList); LinkedList<Position> positionList = new LinkedList<>(); boolean foundHeader = false; BufferedReader fileReader = null; try { if (clipboardStr == null) { if (shiftFile) { fileReader = Files.newBufferedReader(kifFile.toPath(), Charset.forName("SJIS")); } else { fileReader = Files.newBufferedReader(kifFile.toPath(), StandardCharsets.UTF_8); } } else { fileReader = new BufferedReader(new StringReader(clipboardStr)); } int count = 1; String line; Coordinate lastDestination = null; while ((line = fileReader.readLine()) != null) { if (!foundHeader) { foundHeader = isHeader(line); if (foundHeader || isComment(line)) { continue; } parseGameDetails(line, game); } else { if (board == null) { board = getStartBoard(game); positionList.add(new Position(SFENParser.getSFEN(board), null, null, new Notation())); } if (line.isEmpty()) { break; } if (isComment(line)) { positionList.getLast().setComment(positionList.getLast().getComment() + line.substring(1) + "\n"); continue; } if (!isRegularMove(line)) { break; } count++; board.setMoveCount(count); lastDestination = parseRegularMove(board, line, moveListModel, lastDestination, positionList); } } } catch (MalformedInputException ex) { return null; } finally { if (fileReader != null) { fileReader.close(); } } game.setPositionList(positionList); return game; } private static Board getStartBoard(Game game) { String sfen; sfen = switch (game.getHandicap()) { case Game.HANDICAP_LANCE -> "lnsgkgsn1/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_BISHOP -> "lnsgkgsnl/1r7/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_ROOK -> "lnsgkgsnl/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_ROOK_LANCE -> "lnsgkgsn1/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_2_PIECE -> "lnsgkgsnl/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_4_PIECE -> "1nsgkgsn1/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_6_PIECE -> "2sgkgs2/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_8_PIECE -> "3gkg3/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; default -> "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1"; }; return SFENParser.parse(sfen); } private static Coordinate parseRegularMove(Board board, String line, DefaultListModel<String> moveListModel, Coordinate lastDestination, LinkedList<Position> positionList) { String[] splitLine = line.trim().split(MULTI_WHITESPACE); int gameNum; try { gameNum = Integer.parseInt(splitLine[0]); } catch (NumberFormatException ex) { positionList.getLast().setComment(positionList.getLast().getComment() + line + "\n"); return lastDestination; } String move = extractRegularMove(splitLine, isSame(line)); Position position = executeMove(board, move, lastDestination); if (position != null) { lastDestination = position.getDestination(); addMoveToMoveList(moveListModel, gameNum, position.getNotation().getJapanese(), board.getNextTurn()); positionList.add(position); } return lastDestination; } private static String extractRegularMove(String[] moveArray, boolean isSame) { String move = moveArray[1]; if (isSame) { move += "\u3000" + moveArray[2]; } return move; } private static void parseGameDetails(String line, Game game) { if (line.startsWith(SENTE)) { game.setSente(line.substring(SENTE.length()).trim()); } if (line.startsWith(GOTE)) { game.setGote(line.substring(GOTE.length()).trim()); } if (line.startsWith(PLACE)) { game.setPlace(line.substring(PLACE.length()).trim()); } if (line.startsWith(HANDICAP)) { game.setHandicap(line.substring(HANDICAP.length()).trim()); } if (line.startsWith(TIME_LIMIT)) { game.setTimeLimit(line.substring(TIME_LIMIT.length()).trim()); } if (line.startsWith(TOURNAMENT)) { game.setTournament(line.substring(TOURNAMENT.length()).trim()); } if (line.startsWith(DATE)) { game.setDate(line.substring(DATE.length()).trim()); } }
private static void addMoveToMoveList(DefaultListModel<String> moveListModel, int gameNum, String move, Turn turn) {
2
2023-11-08 09:24:57+00:00
24k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/SysUserServiceImpl.java
[ { "identifier": "LoginAboutAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/LoginAboutAdapt.java", "snippet": "public class LoginAboutAdapt {\n\n public static final int USE_NAME_LENGTH = 8;\n\n /**\n * 构造token信息类\n *\n * @param saTokenInfo s...
import cn.dev33.satoken.secure.SaSecureUtil; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.codec.Base64; import cn.hutool.core.util.RandomUtil; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.provider.StaticCredentialProvider; import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient; import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest; import com.google.code.kaptcha.Producer; import com.qingmeng.config.adapt.LoginAboutAdapt; import com.qingmeng.config.adapt.UserInfoAdapt; import com.qingmeng.config.adapt.UserSettingAdapt; import com.qingmeng.config.cache.UserCache; import com.qingmeng.config.cache.UserFriendSettingCache; import com.qingmeng.config.cache.UserSettingCache; import com.qingmeng.constant.RedisConstant; import com.qingmeng.constant.SystemConstant; import com.qingmeng.dao.*; import com.qingmeng.dto.login.CheckFriendDTO; import com.qingmeng.dto.login.LoginParamDTO; import com.qingmeng.dto.login.RegisterDTO; import com.qingmeng.dto.user.AlterAccountDTO; import com.qingmeng.dto.user.AlterPersonalInfoDTO; import com.qingmeng.dto.user.PersonalPrivacySettingDTO; import com.qingmeng.entity.ChatFriendRoom; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserFriendSetting; import com.qingmeng.entity.SysUserPrivacySetting; import com.qingmeng.enums.user.LoginMethodEnum; import com.qingmeng.config.event.SysUserRegisterEvent; import com.qingmeng.exception.TalkTimeException; import com.qingmeng.service.SysUserFriendService; import com.qingmeng.service.SysUserService; import com.qingmeng.config.strategy.login.LoginFactory; import com.qingmeng.config.strategy.login.LoginStrategy; import com.qingmeng.utils.*; import com.qingmeng.vo.login.CaptchaVO; import com.qingmeng.vo.login.TokenInfoVO; import com.qingmeng.vo.user.*; import darabonba.core.client.ClientOverrideConfiguration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.FastByteArrayOutputStream; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit;
15,105
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:19:00 */ @Service public class SysUserServiceImpl implements SysUserService { public static final String MATH = "math"; public static final String CHAR = "char"; @Value("${alibaba.sms.accessKeyId}") private String aliAccessKeyId; @Value("${alibaba.sms.accessKeySecret}") private String aliAccessKeySecret; @Resource @Lazy private LoginFactory loginFactory; @Resource(name = "captchaProducer") private Producer captchaProducer; @Resource(name = "captchaProducerMath") private Producer captchaProducerMath; @Resource private SysUserDao sysUserDao; @Resource private ApplicationEventPublisher applicationEventPublisher; @Resource private UserCache userCache; @Resource private SysUserPrivacySettingDao sysUserPrivacySettingDao; @Resource private SysUserFriendDao sysUserFriendDao; @Resource private UserFriendSettingCache userFriendSettingCache; @Resource private SysUserFriendSettingDao sysUserFriendSettingDao; @Resource private ChatRoomDao chatRoomDao; @Resource private ChatFriendRoomDao chatFriendRoomDao; @Resource private UserSettingCache userSettingCache; @Resource private SysUserFriendService sysUserFriendService; /** * 验证码类型 */ private final String[] captchaArray = {MATH, CHAR}; /** * 登陆 * * @param paramDTO 登陆参数对象 * @return {@link TokenInfoVO } * @author qingmeng * @createTime: 2023/11/11 00:49:54 */ @Override public TokenInfoVO login(LoginParamDTO paramDTO) { LoginMethodEnum typeEnum = LoginMethodEnum.get(paramDTO.getLoginMethod()); LoginStrategy loginStrategy = loginFactory.getStrategyWithType(typeEnum.getValue()); return loginStrategy.getTokenInfo(paramDTO); } /** * 获取验证码 * * @return {@link CaptchaVO } * @author qingmeng * @createTime: 2023/11/11 14:27:50 */ @Override public CaptchaVO getCaptcha() { //生成随机四位数 String uuid = IdUtils.simpleUUID(); // 构造redis key
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:19:00 */ @Service public class SysUserServiceImpl implements SysUserService { public static final String MATH = "math"; public static final String CHAR = "char"; @Value("${alibaba.sms.accessKeyId}") private String aliAccessKeyId; @Value("${alibaba.sms.accessKeySecret}") private String aliAccessKeySecret; @Resource @Lazy private LoginFactory loginFactory; @Resource(name = "captchaProducer") private Producer captchaProducer; @Resource(name = "captchaProducerMath") private Producer captchaProducerMath; @Resource private SysUserDao sysUserDao; @Resource private ApplicationEventPublisher applicationEventPublisher; @Resource private UserCache userCache; @Resource private SysUserPrivacySettingDao sysUserPrivacySettingDao; @Resource private SysUserFriendDao sysUserFriendDao; @Resource private UserFriendSettingCache userFriendSettingCache; @Resource private SysUserFriendSettingDao sysUserFriendSettingDao; @Resource private ChatRoomDao chatRoomDao; @Resource private ChatFriendRoomDao chatFriendRoomDao; @Resource private UserSettingCache userSettingCache; @Resource private SysUserFriendService sysUserFriendService; /** * 验证码类型 */ private final String[] captchaArray = {MATH, CHAR}; /** * 登陆 * * @param paramDTO 登陆参数对象 * @return {@link TokenInfoVO } * @author qingmeng * @createTime: 2023/11/11 00:49:54 */ @Override public TokenInfoVO login(LoginParamDTO paramDTO) { LoginMethodEnum typeEnum = LoginMethodEnum.get(paramDTO.getLoginMethod()); LoginStrategy loginStrategy = loginFactory.getStrategyWithType(typeEnum.getValue()); return loginStrategy.getTokenInfo(paramDTO); } /** * 获取验证码 * * @return {@link CaptchaVO } * @author qingmeng * @createTime: 2023/11/11 14:27:50 */ @Override public CaptchaVO getCaptcha() { //生成随机四位数 String uuid = IdUtils.simpleUUID(); // 构造redis key
String verifyKey = RedisConstant.CAPTCHA_CODE_KEY + uuid;
6
2023-11-07 16:04:55+00:00
24k
dingodb/dingo-expr
test/src/test/java/io/dingodb/expr/test/cases/EvalConstProvider.java
[ { "identifier": "Types", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/Types.java", "snippet": "public final class Types {\n public static final NullType NULL = new NullType();\n public static final IntType INT = new IntType();\n public static final LongType LONG = new LongType();...
import com.google.common.collect.ImmutableMap; import io.dingodb.expr.runtime.type.Types; import io.dingodb.expr.runtime.utils.DateTimeUtils; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static io.dingodb.expr.runtime.expr.Exprs.ABS; import static io.dingodb.expr.runtime.expr.Exprs.ABS_C; import static io.dingodb.expr.runtime.expr.Exprs.ACOS; import static io.dingodb.expr.runtime.expr.Exprs.ADD; import static io.dingodb.expr.runtime.expr.Exprs.AND; import static io.dingodb.expr.runtime.expr.Exprs.AND_FUN; import static io.dingodb.expr.runtime.expr.Exprs.ARRAY; import static io.dingodb.expr.runtime.expr.Exprs.ASIN; import static io.dingodb.expr.runtime.expr.Exprs.ATAN; import static io.dingodb.expr.runtime.expr.Exprs.CASE; import static io.dingodb.expr.runtime.expr.Exprs.CEIL; import static io.dingodb.expr.runtime.expr.Exprs.CHAR_LENGTH; import static io.dingodb.expr.runtime.expr.Exprs.CONCAT; import static io.dingodb.expr.runtime.expr.Exprs.COS; import static io.dingodb.expr.runtime.expr.Exprs.COSH; import static io.dingodb.expr.runtime.expr.Exprs.DATEDIFF; import static io.dingodb.expr.runtime.expr.Exprs.DATE_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.DATE_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.DIV; import static io.dingodb.expr.runtime.expr.Exprs.EQ; import static io.dingodb.expr.runtime.expr.Exprs.EXP; import static io.dingodb.expr.runtime.expr.Exprs.FLOOR; import static io.dingodb.expr.runtime.expr.Exprs.FORMAT; import static io.dingodb.expr.runtime.expr.Exprs.FROM_UNIXTIME; import static io.dingodb.expr.runtime.expr.Exprs.GE; import static io.dingodb.expr.runtime.expr.Exprs.GT; import static io.dingodb.expr.runtime.expr.Exprs.HEX; import static io.dingodb.expr.runtime.expr.Exprs.INDEX; import static io.dingodb.expr.runtime.expr.Exprs.IS_FALSE; import static io.dingodb.expr.runtime.expr.Exprs.IS_NULL; import static io.dingodb.expr.runtime.expr.Exprs.IS_TRUE; import static io.dingodb.expr.runtime.expr.Exprs.LE; import static io.dingodb.expr.runtime.expr.Exprs.LEFT; import static io.dingodb.expr.runtime.expr.Exprs.LIST; import static io.dingodb.expr.runtime.expr.Exprs.LOCATE2; import static io.dingodb.expr.runtime.expr.Exprs.LOCATE3; import static io.dingodb.expr.runtime.expr.Exprs.LOG; import static io.dingodb.expr.runtime.expr.Exprs.LOWER; import static io.dingodb.expr.runtime.expr.Exprs.LT; import static io.dingodb.expr.runtime.expr.Exprs.LTRIM1; import static io.dingodb.expr.runtime.expr.Exprs.LTRIM2; import static io.dingodb.expr.runtime.expr.Exprs.MAP; import static io.dingodb.expr.runtime.expr.Exprs.MATCHES; import static io.dingodb.expr.runtime.expr.Exprs.MATCHES_NC; import static io.dingodb.expr.runtime.expr.Exprs.MAX; import static io.dingodb.expr.runtime.expr.Exprs.MID2; import static io.dingodb.expr.runtime.expr.Exprs.MID3; import static io.dingodb.expr.runtime.expr.Exprs.MIN; import static io.dingodb.expr.runtime.expr.Exprs.MOD; import static io.dingodb.expr.runtime.expr.Exprs.MUL; import static io.dingodb.expr.runtime.expr.Exprs.NE; import static io.dingodb.expr.runtime.expr.Exprs.NEG; import static io.dingodb.expr.runtime.expr.Exprs.NOT; import static io.dingodb.expr.runtime.expr.Exprs.OR; import static io.dingodb.expr.runtime.expr.Exprs.OR_FUN; import static io.dingodb.expr.runtime.expr.Exprs.POS; import static io.dingodb.expr.runtime.expr.Exprs.POW; import static io.dingodb.expr.runtime.expr.Exprs.REPEAT; import static io.dingodb.expr.runtime.expr.Exprs.REPLACE; import static io.dingodb.expr.runtime.expr.Exprs.REVERSE; import static io.dingodb.expr.runtime.expr.Exprs.RIGHT; import static io.dingodb.expr.runtime.expr.Exprs.ROUND1; import static io.dingodb.expr.runtime.expr.Exprs.ROUND2; import static io.dingodb.expr.runtime.expr.Exprs.RTRIM1; import static io.dingodb.expr.runtime.expr.Exprs.RTRIM2; import static io.dingodb.expr.runtime.expr.Exprs.SIN; import static io.dingodb.expr.runtime.expr.Exprs.SINH; import static io.dingodb.expr.runtime.expr.Exprs.SLICE; import static io.dingodb.expr.runtime.expr.Exprs.SUB; import static io.dingodb.expr.runtime.expr.Exprs.SUBSTR2; import static io.dingodb.expr.runtime.expr.Exprs.SUBSTR3; import static io.dingodb.expr.runtime.expr.Exprs.TAN; import static io.dingodb.expr.runtime.expr.Exprs.TANH; import static io.dingodb.expr.runtime.expr.Exprs.TIMESTAMP_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.TIMESTAMP_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.TIME_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.TIME_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TO_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TO_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TRIM1; import static io.dingodb.expr.runtime.expr.Exprs.TRIM2; import static io.dingodb.expr.runtime.expr.Exprs.UNIX_TIMESTAMP1; import static io.dingodb.expr.runtime.expr.Exprs.UPPER; import static io.dingodb.expr.runtime.expr.Exprs._CP1; import static io.dingodb.expr.runtime.expr.Exprs._CP2; import static io.dingodb.expr.runtime.expr.Exprs._CTF; import static io.dingodb.expr.runtime.expr.Exprs.op; import static io.dingodb.expr.runtime.expr.Exprs.val; import static io.dingodb.expr.runtime.expr.Val.NULL; import static io.dingodb.expr.runtime.expr.Val.NULL_BOOL; import static io.dingodb.expr.runtime.expr.Val.NULL_BYTES; import static io.dingodb.expr.runtime.expr.Val.NULL_DATE; import static io.dingodb.expr.runtime.expr.Val.NULL_DECIMAL; import static io.dingodb.expr.runtime.expr.Val.NULL_DOUBLE; import static io.dingodb.expr.runtime.expr.Val.NULL_FLOAT; import static io.dingodb.expr.runtime.expr.Val.NULL_INT; import static io.dingodb.expr.runtime.expr.Val.NULL_LONG; import static io.dingodb.expr.runtime.expr.Val.NULL_STRING; import static io.dingodb.expr.runtime.expr.Val.NULL_TIME; import static io.dingodb.expr.runtime.expr.Val.NULL_TIMESTAMP; import static io.dingodb.expr.test.ExprsHelper.bytes; import static io.dingodb.expr.test.ExprsHelper.date; import static io.dingodb.expr.test.ExprsHelper.dec; import static io.dingodb.expr.test.ExprsHelper.sec; import static io.dingodb.expr.test.ExprsHelper.time; import static io.dingodb.expr.test.ExprsHelper.ts; import static org.junit.jupiter.params.provider.Arguments.arguments;
18,668
arguments(op(OR_FUN, false, NULL_BOOL, false), null), arguments(op(OR_FUN, false, false, false), false), // Specials arguments(op(IS_NULL, 1), false), arguments(op(IS_NULL, NULL_INT), true), arguments(op(IS_NULL, 1L), false), arguments(op(IS_NULL, NULL_LONG), true), arguments(op(IS_NULL, 1.1f), false), arguments(op(IS_NULL, NULL_FLOAT), true), arguments(op(IS_NULL, 1.1), false), arguments(op(IS_NULL, NULL_DOUBLE), true), arguments(op(IS_NULL, false), false), arguments(op(IS_NULL, NULL_BOOL), true), arguments(op(IS_NULL, dec(1)), false), arguments(op(IS_NULL, NULL_DECIMAL), true), arguments(op(IS_NULL, ""), false), arguments(op(IS_NULL, NULL_STRING), true), arguments(op(IS_NULL, bytes("")), false), arguments(op(IS_NULL, NULL_BYTES), true), arguments(op(IS_NULL, date(0)), false), arguments(op(IS_NULL, NULL_DATE), true), arguments(op(IS_NULL, time(0)), false), arguments(op(IS_NULL, NULL_TIME), true), arguments(op(IS_NULL, ts(0)), false), arguments(op(IS_NULL, NULL_TIMESTAMP), true), arguments(op(IS_TRUE, 1), true), arguments(op(IS_TRUE, 0), false), arguments(op(IS_TRUE, NULL_INT), false), arguments(op(IS_TRUE, 1L), true), arguments(op(IS_TRUE, 0L), false), arguments(op(IS_TRUE, NULL_LONG), false), arguments(op(IS_TRUE, 1.1f), true), arguments(op(IS_TRUE, 0.0f), false), arguments(op(IS_TRUE, NULL_FLOAT), false), arguments(op(IS_TRUE, 1.1), true), arguments(op(IS_TRUE, 0.0), false), arguments(op(IS_TRUE, NULL_DOUBLE), false), arguments(op(IS_TRUE, true), true), arguments(op(IS_TRUE, false), false), arguments(op(IS_TRUE, NULL_BOOL), false), arguments(op(IS_TRUE, dec(1)), true), arguments(op(IS_TRUE, dec(0)), false), arguments(op(IS_TRUE, NULL_DECIMAL), false), arguments(op(IS_TRUE, "abc"), false), arguments(op(IS_TRUE, ""), false), arguments(op(IS_TRUE, NULL_STRING), false), arguments(op(IS_TRUE, bytes("abc")), false), arguments(op(IS_TRUE, bytes("")), false), arguments(op(IS_TRUE, NULL_BYTES), false), arguments(op(IS_TRUE, date(0)), true), arguments(op(IS_TRUE, NULL_DATE), false), arguments(op(IS_TRUE, time(0)), true), arguments(op(IS_TRUE, NULL_TIME), false), arguments(op(IS_TRUE, ts(0)), true), arguments(op(IS_TRUE, NULL_TIMESTAMP), false), arguments(op(IS_FALSE, 1), false), arguments(op(IS_FALSE, 0), true), arguments(op(IS_FALSE, NULL_INT), false), arguments(op(IS_FALSE, 1L), false), arguments(op(IS_FALSE, 0L), true), arguments(op(IS_FALSE, NULL_LONG), false), arguments(op(IS_FALSE, 1.1f), false), arguments(op(IS_FALSE, 0.0f), true), arguments(op(IS_FALSE, NULL_FLOAT), false), arguments(op(IS_FALSE, 1.1), false), arguments(op(IS_FALSE, 0.0), true), arguments(op(IS_FALSE, NULL_DOUBLE), false), arguments(op(IS_FALSE, true), false), arguments(op(IS_FALSE, false), true), arguments(op(IS_FALSE, NULL_BOOL), false), arguments(op(IS_FALSE, dec(1)), false), arguments(op(IS_FALSE, dec(0)), true), arguments(op(IS_FALSE, NULL_DECIMAL), false), arguments(op(IS_FALSE, "abc"), true), arguments(op(IS_FALSE, ""), true), arguments(op(IS_FALSE, NULL_STRING), false), arguments(op(IS_FALSE, bytes("abc")), true), arguments(op(IS_FALSE, bytes("")), true), arguments(op(IS_FALSE, NULL_BYTES), false), arguments(op(IS_FALSE, date(0)), false), arguments(op(IS_FALSE, NULL_DATE), false), arguments(op(IS_FALSE, time(0)), false), arguments(op(IS_FALSE, NULL_TIME), false), arguments(op(IS_FALSE, ts(0)), false), arguments(op(IS_FALSE, NULL_TIMESTAMP), false), arguments(op(CASE, 100), 100), arguments(op(CASE, true, 1, 100), 1), arguments(op(CASE, false, 1, true, 2, 100), 2), // Mathematics arguments(op(ABS, -1), 1), arguments(op(ABS, 1), 1), arguments(op(ABS, -1L), 1L), arguments(op(ABS, 1L), 1L), arguments(op(ABS, -0.5f), 0.5f), arguments(op(ABS, 0.5f), 0.5f), arguments(op(ABS, -0.5), 0.5), arguments(op(ABS, 0.5), 0.5), arguments(op(ABS, dec(-0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS, dec(0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS_C, -1), 1), arguments(op(ABS_C, 1), 1), arguments(op(ABS_C, -1L), 1L), arguments(op(ABS_C, 1L), 1L), arguments(op(ABS_C, -0.5f), 0.5f), arguments(op(ABS_C, 0.5f), 0.5f), arguments(op(ABS_C, -0.5), 0.5), arguments(op(ABS_C, 0.5), 0.5), arguments(op(ABS_C, dec(-0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS_C, dec(0.5)), BigDecimal.valueOf(0.5)), arguments(op(MIN, 1, 2), 1), arguments(op(MIN, 1L, 2L), 1L), arguments(op(MIN, 1.1f, 2.2f), 1.1f), arguments(op(MIN, 1.1, 2.2), 1.1), arguments(op(MIN, dec(1.1), dec(2.2)), BigDecimal.valueOf(1.1)), arguments(op(MIN, "abc", "def"), "abc"), arguments(op(MIN, date(1L), date(2L)), new Date(sec(1L))), arguments(op(MIN, time(1L), time(2L)), new Time(sec(1L))), arguments(op(MIN, ts(1L), ts(2L)), new Timestamp(sec(1L))),
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.test.cases; public class EvalConstProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Stream.of( // Values arguments(val(1), 1), arguments(val(2L), 2L), arguments(val(3.3f), 3.3f), arguments(val(4.4), 4.4), arguments(val(true), true), arguments(val(false), false), arguments(dec(5.5), BigDecimal.valueOf(5.5)), arguments(val("abc"), "abc"), arguments(bytes("123"), "123".getBytes(StandardCharsets.UTF_8)), arguments(date(1L), new Date(sec(1L))), arguments(time(2L), new Time(sec(2L))), arguments(ts(3L), new Timestamp(sec(3L))), arguments(val(null), null), // Castings arguments(op(TO_INT, 1), 1), arguments(op(TO_INT, 1L), 1), arguments(op(TO_INT_C, 1L), 1), arguments(op(TO_INT, 1.4f), 1), arguments(op(TO_INT_C, 1.4f), 1), arguments(op(TO_INT, 1.5f), 2), arguments(op(TO_INT_C, 1.5f), 2), arguments(op(TO_INT, 1.4), 1), arguments(op(TO_INT, 1.5), 2), arguments(op(TO_INT, true), 1), arguments(op(TO_INT, false), 0), arguments(op(TO_INT, dec(1.4)), 1), arguments(op(TO_INT_C, dec(1.4)), 1), arguments(op(TO_INT, dec(1.5)), 2), arguments(op(TO_INT_C, dec(1.5)), 2), arguments(op(TO_INT, "10"), 10), arguments(op(TO_LONG, 1), 1L), arguments(op(TO_LONG, 1L), 1L), arguments(op(TO_LONG, 1.4f), 1L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.5f), 2L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.4), 1L), arguments(op(TO_LONG, 1.5), 2L), arguments(op(TO_LONG, true), 1L), arguments(op(TO_LONG, false), 0L), arguments(op(TO_LONG, dec(1.4)), 1L), arguments(op(TO_LONG, dec(1.5)), 2L), arguments(op(TO_LONG, "10"), 10L), arguments(op(TO_FLOAT, 1), 1.0f), arguments(op(TO_FLOAT, 1L), 1.0f), arguments(op(TO_FLOAT, 1.4f), 1.4f), arguments(op(TO_FLOAT, 1.4), 1.4f), arguments(op(TO_FLOAT, true), 1.0f), arguments(op(TO_FLOAT, false), 0.0f), arguments(op(TO_FLOAT, dec(1.4)), 1.4f), arguments(op(TO_FLOAT, "12.3"), 12.3f), arguments(op(TO_DOUBLE, 1), 1.0), arguments(op(TO_DOUBLE, 1L), 1.0), arguments(op(TO_DOUBLE, 1.4f), 1.4), arguments(op(TO_DOUBLE, 1.4), 1.4), arguments(op(TO_DOUBLE, true), 1.0), arguments(op(TO_DOUBLE, false), 0.0), arguments(op(TO_DOUBLE, dec(1.4)), 1.4), arguments(op(TO_DOUBLE, "12.3"), 12.3), arguments(op(TO_BOOL, 1), true), arguments(op(TO_BOOL, 0), false), arguments(op(TO_BOOL, 1L), true), arguments(op(TO_BOOL, 0L), false), arguments(op(TO_BOOL, 1.4f), true), arguments(op(TO_BOOL, 0.0f), false), arguments(op(TO_BOOL, 1.4), true), arguments(op(TO_BOOL, 0.0), false), arguments(op(TO_BOOL, true), true), arguments(op(TO_BOOL, false), false), arguments(op(TO_BOOL, val(BigDecimal.ONE)), true), arguments(op(TO_BOOL, val(BigDecimal.ZERO)), false), arguments(op(TO_DECIMAL, 1), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1L), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1.4f), BigDecimal.valueOf(1.4f)), arguments(op(TO_DECIMAL, 1.4), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, true), BigDecimal.ONE), arguments(op(TO_DECIMAL, false), BigDecimal.ZERO), arguments(op(TO_DECIMAL, dec(1.4)), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, "12.3"), BigDecimal.valueOf(12.3)), arguments(op(TO_STRING, 1), "1"), arguments(op(TO_STRING, 1L), "1"), arguments(op(TO_STRING, 1.4f), "1.4"), arguments(op(TO_STRING, 1.4), "1.4"), arguments(op(TO_STRING, true), "true"), arguments(op(TO_STRING, false), "false"), arguments(op(TO_STRING, dec(12.3)), "12.3"), arguments(op(TO_STRING, "abc"), "abc"), arguments(op(TO_BYTES, bytes("abc")), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_BYTES, "abc"), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_DATE, 1), new Date(sec(1L))), arguments(op(TO_DATE, 1L), new Date(sec(1L))), arguments(op(TO_DATE, "1970-01-01"), new Date(sec(0L))), arguments(op(TO_DATE, date(1L)), new Date(sec(1L))), arguments(op(TO_TIME, 1), new Time(sec(1L))), arguments(op(TO_TIME, 1L), new Time(sec(1L))), arguments(op(TO_TIME, "00:00:00"), new Time(sec(0L))), arguments(op(TO_TIME, time(1L)), new Time(sec(1L))), arguments(op(TO_TIMESTAMP, 1), new Timestamp(sec(1L))), arguments(op(TO_TIMESTAMP, 1L), new Timestamp(sec(1L))), arguments( op(TO_TIMESTAMP, "1970-01-01 00:00:00"), DateTimeUtils.parseTimestamp("1970-01-01 00:00:00") ), arguments(op(TO_TIMESTAMP, ts(1L)), new Timestamp(sec(1L))), // Arithmetics arguments(op(POS, 1), 1), arguments(op(POS, 1L), 1L), arguments(op(POS, 1.1f), 1.1f), arguments(op(POS, 1.1), 1.1), arguments(op(POS, dec(1.1)), BigDecimal.valueOf(1.1)), arguments(op(NEG, 1), -1), arguments(op(NEG, 1L), -1L), arguments(op(NEG, 1.1f), -1.1f), arguments(op(NEG, 1.1), -1.1), arguments(op(NEG, dec(1.1)), BigDecimal.valueOf(-1.1)), arguments(op(ADD, 1, 2), 3), arguments(op(ADD, 1L, 2L), 3L), arguments(op(ADD, 1.1f, 2.2f), 3.3f), arguments(op(ADD, 1.1, 2.2), 3.3), arguments(op(ADD, dec(1.1), dec(2.2)), BigDecimal.valueOf(3.3)), arguments(op(ADD, 1, 2L), 3L), arguments(op(ADD, 1L, 2.2f), 3.2f), arguments(op(ADD, 1.1f, 2.2), 3.3), arguments(op(ADD, 1.1, dec(2.2)), BigDecimal.valueOf(3.3)), arguments(op(ADD, "a", "bc"), "abc"), arguments(op(SUB, 1, 2), -1), arguments(op(SUB, 1L, 2L), -1L), arguments(op(SUB, 1.1f, 2.2f), -1.1f), arguments(op(SUB, 1.1, 2.2), -1.1), arguments(op(SUB, dec(1.1), dec(2.2)), BigDecimal.valueOf(-1.1)), arguments(op(SUB, 1, 2L), -1L), arguments(op(SUB, 1L, 2.2f), -1.2f), arguments(op(SUB, 1.1f, 2.2), -1.1), arguments(op(SUB, 1.1, dec(2.2)), BigDecimal.valueOf(-1.1)), arguments(op(MUL, 1, 2), 2), arguments(op(MUL, 1L, 2L), 2L), arguments(op(MUL, 1.1f, 2.2f), 2.42f), arguments(op(MUL, 1.1, 2.2), 2.42), arguments(op(MUL, dec(1.1), dec(2.2)), BigDecimal.valueOf(2.42)), arguments(op(MUL, 1, 2L), 2L), arguments(op(MUL, 1L, 2.2f), 2.2f), arguments(op(MUL, 1.1f, 2.2), 2.42), arguments(op(MUL, 1.1, dec(2.2)), BigDecimal.valueOf(2.42)), arguments(op(DIV, 1, 2), 0), arguments(op(DIV, 1L, 2L), 0L), arguments(op(DIV, 1.1f, 2.2f), 0.5f), arguments(op(DIV, 1.1, 2.2), 0.5), arguments(op(DIV, dec(1.1), dec(2.2)), BigDecimal.valueOf(0.5)), arguments(op(DIV, 1, 2L), 0L), arguments(op(DIV, 1L, 2.0f), 0.5f), arguments(op(DIV, 1.1f, 2.2), 0.5), arguments(op(DIV, 1.1, dec(2.2)), BigDecimal.valueOf(0.5)), arguments(op(DIV, 1, 0), null), arguments(op(DIV, 1.1f, 0.0f), null), arguments(op(DIV, 1.2, 0.0), null), arguments(op(DIV, dec(1.3), dec(0)), null), // Relations arguments(op(EQ, 1, 1), true), arguments(op(EQ, 1L, 2L), false), arguments(op(EQ, 1.1f, 1.1f), true), arguments(op(EQ, 1.1, 2.2), false), arguments(op(EQ, true, true), true), arguments(op(EQ, dec(1.1), dec(2.2)), false), arguments(op(EQ, "abc", "abc"), true), arguments(op(EQ, date(1L), date(2L)), false), arguments(op(EQ, time(1L), time(1L)), true), arguments(op(EQ, ts(2L), ts(1L)), false), arguments(op(NE, 1, 1), false), arguments(op(NE, 1L, 2L), true), arguments(op(NE, 1.1f, 1.1f), false), arguments(op(NE, 1.1, 2.2), true), arguments(op(NE, true, true), false), arguments(op(NE, dec(1.1), dec(2.2)), true), arguments(op(NE, "abc", "abc"), false), arguments(op(NE, date(1L), date(2L)), true), arguments(op(NE, time(1L), time(1L)), false), arguments(op(NE, ts(2L), ts(1L)), true), arguments(op(GT, 1, 1), false), arguments(op(GT, 1L, 2L), false), arguments(op(GT, 1.1f, 1.1f), false), arguments(op(GT, 1.1, 2.2), false), arguments(op(GT, true, true), false), arguments(op(GT, dec(1.1), dec(2.2)), false), arguments(op(GT, "abc", "abc"), false), arguments(op(GT, date(1L), date(2L)), false), arguments(op(GT, time(1L), time(1L)), false), arguments(op(GT, ts(2L), ts(1L)), true), arguments(op(GE, 1, 1), true), arguments(op(GE, 1L, 2L), false), arguments(op(GE, 1.1f, 1.1f), true), arguments(op(GE, 1.1, 2.2), false), arguments(op(GE, true, true), true), arguments(op(GE, dec(1.1), dec(2.2)), false), arguments(op(GE, "abc", "abc"), true), arguments(op(GE, date(1L), date(2L)), false), arguments(op(GE, time(1L), time(1L)), true), arguments(op(GE, ts(2L), ts(1L)), true), arguments(op(LT, 1, 1), false), arguments(op(LT, 1L, 2L), true), arguments(op(LT, 1.1f, 1.1f), false), arguments(op(LT, 1.1, 2.2), true), arguments(op(LT, true, true), false), arguments(op(LT, dec(1.1), dec(2.2)), true), arguments(op(LT, "abc", "abc"), false), arguments(op(LT, date(1L), date(2L)), true), arguments(op(LT, time(1L), time(1L)), false), arguments(op(LT, ts(2L), ts(1L)), false), arguments(op(LE, 1, 1), true), arguments(op(LE, 1L, 2L), true), arguments(op(LE, 1.1f, 1.1f), true), arguments(op(LE, 1.1, 2.2), true), arguments(op(LE, true, true), true), arguments(op(LE, dec(1.1), dec(2.2)), true), arguments(op(LE, "abc", "abc"), true), arguments(op(LE, date(1L), date(2L)), true), arguments(op(LE, time(1L), time(1L)), true), arguments(op(LE, ts(2L), ts(1L)), false), // Logics arguments(op(AND, false, false), false), arguments(op(AND, false, true), false), arguments(op(AND, false, NULL_BOOL), false), arguments(op(AND, true, false), false), arguments(op(AND, true, true), true), arguments(op(AND, true, NULL_BOOL), null), arguments(op(AND, NULL_BOOL, false), false), arguments(op(AND, NULL_BOOL, true), null), arguments(op(AND, NULL_BOOL, NULL_BOOL), null), arguments(op(OR, false, false), false), arguments(op(OR, false, true), true), arguments(op(OR, false, NULL_BOOL), null), arguments(op(OR, true, false), true), arguments(op(OR, true, true), true), arguments(op(OR, true, NULL_BOOL), true), arguments(op(OR, NULL_BOOL, false), null), arguments(op(OR, NULL_BOOL, true), true), arguments(op(OR, NULL_BOOL, NULL_BOOL), null), arguments(op(NOT, false), true), arguments(op(NOT, true), false), arguments(op(NOT, NULL_BOOL), null), arguments(op(AND_FUN, true, false, true), false), arguments(op(AND_FUN, true, NULL_BOOL, true), null), arguments(op(AND_FUN, true, true, true), true), arguments(op(OR_FUN, true, false, true), true), arguments(op(OR_FUN, false, NULL_BOOL, false), null), arguments(op(OR_FUN, false, false, false), false), // Specials arguments(op(IS_NULL, 1), false), arguments(op(IS_NULL, NULL_INT), true), arguments(op(IS_NULL, 1L), false), arguments(op(IS_NULL, NULL_LONG), true), arguments(op(IS_NULL, 1.1f), false), arguments(op(IS_NULL, NULL_FLOAT), true), arguments(op(IS_NULL, 1.1), false), arguments(op(IS_NULL, NULL_DOUBLE), true), arguments(op(IS_NULL, false), false), arguments(op(IS_NULL, NULL_BOOL), true), arguments(op(IS_NULL, dec(1)), false), arguments(op(IS_NULL, NULL_DECIMAL), true), arguments(op(IS_NULL, ""), false), arguments(op(IS_NULL, NULL_STRING), true), arguments(op(IS_NULL, bytes("")), false), arguments(op(IS_NULL, NULL_BYTES), true), arguments(op(IS_NULL, date(0)), false), arguments(op(IS_NULL, NULL_DATE), true), arguments(op(IS_NULL, time(0)), false), arguments(op(IS_NULL, NULL_TIME), true), arguments(op(IS_NULL, ts(0)), false), arguments(op(IS_NULL, NULL_TIMESTAMP), true), arguments(op(IS_TRUE, 1), true), arguments(op(IS_TRUE, 0), false), arguments(op(IS_TRUE, NULL_INT), false), arguments(op(IS_TRUE, 1L), true), arguments(op(IS_TRUE, 0L), false), arguments(op(IS_TRUE, NULL_LONG), false), arguments(op(IS_TRUE, 1.1f), true), arguments(op(IS_TRUE, 0.0f), false), arguments(op(IS_TRUE, NULL_FLOAT), false), arguments(op(IS_TRUE, 1.1), true), arguments(op(IS_TRUE, 0.0), false), arguments(op(IS_TRUE, NULL_DOUBLE), false), arguments(op(IS_TRUE, true), true), arguments(op(IS_TRUE, false), false), arguments(op(IS_TRUE, NULL_BOOL), false), arguments(op(IS_TRUE, dec(1)), true), arguments(op(IS_TRUE, dec(0)), false), arguments(op(IS_TRUE, NULL_DECIMAL), false), arguments(op(IS_TRUE, "abc"), false), arguments(op(IS_TRUE, ""), false), arguments(op(IS_TRUE, NULL_STRING), false), arguments(op(IS_TRUE, bytes("abc")), false), arguments(op(IS_TRUE, bytes("")), false), arguments(op(IS_TRUE, NULL_BYTES), false), arguments(op(IS_TRUE, date(0)), true), arguments(op(IS_TRUE, NULL_DATE), false), arguments(op(IS_TRUE, time(0)), true), arguments(op(IS_TRUE, NULL_TIME), false), arguments(op(IS_TRUE, ts(0)), true), arguments(op(IS_TRUE, NULL_TIMESTAMP), false), arguments(op(IS_FALSE, 1), false), arguments(op(IS_FALSE, 0), true), arguments(op(IS_FALSE, NULL_INT), false), arguments(op(IS_FALSE, 1L), false), arguments(op(IS_FALSE, 0L), true), arguments(op(IS_FALSE, NULL_LONG), false), arguments(op(IS_FALSE, 1.1f), false), arguments(op(IS_FALSE, 0.0f), true), arguments(op(IS_FALSE, NULL_FLOAT), false), arguments(op(IS_FALSE, 1.1), false), arguments(op(IS_FALSE, 0.0), true), arguments(op(IS_FALSE, NULL_DOUBLE), false), arguments(op(IS_FALSE, true), false), arguments(op(IS_FALSE, false), true), arguments(op(IS_FALSE, NULL_BOOL), false), arguments(op(IS_FALSE, dec(1)), false), arguments(op(IS_FALSE, dec(0)), true), arguments(op(IS_FALSE, NULL_DECIMAL), false), arguments(op(IS_FALSE, "abc"), true), arguments(op(IS_FALSE, ""), true), arguments(op(IS_FALSE, NULL_STRING), false), arguments(op(IS_FALSE, bytes("abc")), true), arguments(op(IS_FALSE, bytes("")), true), arguments(op(IS_FALSE, NULL_BYTES), false), arguments(op(IS_FALSE, date(0)), false), arguments(op(IS_FALSE, NULL_DATE), false), arguments(op(IS_FALSE, time(0)), false), arguments(op(IS_FALSE, NULL_TIME), false), arguments(op(IS_FALSE, ts(0)), false), arguments(op(IS_FALSE, NULL_TIMESTAMP), false), arguments(op(CASE, 100), 100), arguments(op(CASE, true, 1, 100), 1), arguments(op(CASE, false, 1, true, 2, 100), 2), // Mathematics arguments(op(ABS, -1), 1), arguments(op(ABS, 1), 1), arguments(op(ABS, -1L), 1L), arguments(op(ABS, 1L), 1L), arguments(op(ABS, -0.5f), 0.5f), arguments(op(ABS, 0.5f), 0.5f), arguments(op(ABS, -0.5), 0.5), arguments(op(ABS, 0.5), 0.5), arguments(op(ABS, dec(-0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS, dec(0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS_C, -1), 1), arguments(op(ABS_C, 1), 1), arguments(op(ABS_C, -1L), 1L), arguments(op(ABS_C, 1L), 1L), arguments(op(ABS_C, -0.5f), 0.5f), arguments(op(ABS_C, 0.5f), 0.5f), arguments(op(ABS_C, -0.5), 0.5), arguments(op(ABS_C, 0.5), 0.5), arguments(op(ABS_C, dec(-0.5)), BigDecimal.valueOf(0.5)), arguments(op(ABS_C, dec(0.5)), BigDecimal.valueOf(0.5)), arguments(op(MIN, 1, 2), 1), arguments(op(MIN, 1L, 2L), 1L), arguments(op(MIN, 1.1f, 2.2f), 1.1f), arguments(op(MIN, 1.1, 2.2), 1.1), arguments(op(MIN, dec(1.1), dec(2.2)), BigDecimal.valueOf(1.1)), arguments(op(MIN, "abc", "def"), "abc"), arguments(op(MIN, date(1L), date(2L)), new Date(sec(1L))), arguments(op(MIN, time(1L), time(2L)), new Time(sec(1L))), arguments(op(MIN, ts(1L), ts(2L)), new Timestamp(sec(1L))),
arguments(op(MAX, 1, 2), 2),
46
2023-11-04 08:43:49+00:00
24k
conductor-oss/conductor
core/src/main/java/com/netflix/conductor/core/execution/mapper/HumanTaskMapper.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 java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.core.execution.tasks.Human; import com.netflix.conductor.core.utils.ParametersUtils; import com.netflix.conductor.model.TaskModel; import com.netflix.conductor.model.WorkflowModel; import static com.netflix.conductor.common.metadata.tasks.TaskType.TASK_TYPE_HUMAN;
19,645
/* * 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#HUMAN} to a {@link TaskModel} of type {@link Human} with {@link * TaskModel.Status#IN_PROGRESS} */ @Component public class HumanTaskMapper implements TaskMapper { public static final Logger LOGGER = LoggerFactory.getLogger(HumanTaskMapper.class);
/* * 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#HUMAN} to a {@link TaskModel} of type {@link Human} with {@link * TaskModel.Status#IN_PROGRESS} */ @Component public class HumanTaskMapper implements TaskMapper { public static final Logger LOGGER = LoggerFactory.getLogger(HumanTaskMapper.class);
private final ParametersUtils parametersUtils;
3
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,300
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) {
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");
6
2023-12-07 13:46:27+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;
18,517
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;
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;
13
2023-12-06 13:20:16+00:00
24k
lxs2601055687/contextAdminRuoYi
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java
[ { "identifier": "UserConstants", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java", "snippet": "public interface UserConstants {\n\n /**\n * 平台内系统用户的唯一标志\n */\n String SYS_USER = \"SYS_USER\";\n\n /**\n * 正常状态\n */\n String NORMAL = \"0\";\n\n ...
import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.secure.BCrypt; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ObjectUtil; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.PageQuery; import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.core.domain.entity.SysRole; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.excel.ExcelResult; import com.ruoyi.common.helper.LoginHelper; import com.ruoyi.common.utils.StreamUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.system.domain.vo.SysUserExportVo; import com.ruoyi.system.domain.vo.SysUserImportVo; import com.ruoyi.system.listener.SysUserImportListener; import com.ruoyi.system.service.ISysDeptService; import com.ruoyi.system.service.ISysPostService; import com.ruoyi.system.service.ISysRoleService; import com.ruoyi.system.service.ISysUserService; import lombok.RequiredArgsConstructor; import org.springframework.http.MediaType; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
20,852
package com.ruoyi.web.controller.system; /** * 用户信息 * * @author Lion Li */ @Validated @RequiredArgsConstructor @RestController @RequestMapping("/system/user") public class SysUserController extends BaseController { private final ISysUserService userService; private final ISysRoleService roleService; private final ISysPostService postService; private final ISysDeptService deptService; /** * 获取用户列表 */ @SaCheckPermission("system:user:list") @GetMapping("/list") public TableDataInfo<SysUser> list(SysUser user, PageQuery pageQuery) { return userService.selectPageUserList(user, pageQuery); } /** * 导出用户列表 */
package com.ruoyi.web.controller.system; /** * 用户信息 * * @author Lion Li */ @Validated @RequiredArgsConstructor @RestController @RequestMapping("/system/user") public class SysUserController extends BaseController { private final ISysUserService userService; private final ISysRoleService roleService; private final ISysPostService postService; private final ISysDeptService deptService; /** * 获取用户列表 */ @SaCheckPermission("system:user:list") @GetMapping("/list") public TableDataInfo<SysUser> list(SysUser user, PageQuery pageQuery) { return userService.selectPageUserList(user, pageQuery); } /** * 导出用户列表 */
@Log(title = "用户管理", businessType = BusinessType.EXPORT)
8
2023-12-07 12:06:21+00:00
24k
DantSu/studio
web-ui/src/main/java/studio/webui/MainVerticle.java
[ { "identifier": "StudioConfig", "path": "metadata/src/main/java/studio/config/StudioConfig.java", "snippet": "public enum StudioConfig {\n\n // auto open browser (studio.open.browser)\n STUDIO_OPEN_BROWSER(\"true\"),\n // http listen host (studio.host)\n STUDIO_HOST(\"localhost\"),\n // h...
import java.awt.Desktop; import java.net.URI; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.netty.handler.codec.http.HttpHeaderNames; import io.vertx.core.AbstractVerticle; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpMethod; import io.vertx.ext.bridge.BridgeEventType; import io.vertx.ext.bridge.PermittedOptions; import io.vertx.ext.web.Router; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.handler.CorsHandler; import io.vertx.ext.web.handler.ErrorHandler; import io.vertx.ext.web.handler.StaticHandler; import io.vertx.ext.web.handler.sockjs.SockJSBridgeOptions; import io.vertx.ext.web.handler.sockjs.SockJSHandler; import studio.config.StudioConfig; import studio.metadata.DatabaseMetadataService; import studio.webui.api.DeviceController; import studio.webui.api.EvergreenController; import studio.webui.api.LibraryController; import studio.webui.service.EvergreenService; import studio.webui.service.IStoryTellerService; import studio.webui.service.LibraryService; import studio.webui.service.StoryTellerService; import studio.webui.service.mock.MockStoryTellerService;
15,824
/* * 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; public class MainVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(MainVerticle.class); public static final String MIME_JSON = "application/json"; private LibraryService libraryService; private EvergreenService evergreenService; private IStoryTellerService storyTellerService; @Override public void start() { // Service that manages pack metadata DatabaseMetadataService databaseMetadataService = new DatabaseMetadataService(); // Service that manages local library libraryService = new LibraryService(databaseMetadataService); // Service that manages updates evergreenService = new EvergreenService(vertx); // Service that manages link with the story teller device if (isDevMode()) { LOGGER.warn("[DEV MODE] Initializing mock storyteller service"); storyTellerService = new MockStoryTellerService(vertx.eventBus(), databaseMetadataService); } else { storyTellerService = new StoryTellerService(vertx.eventBus(), databaseMetadataService); } // Config String host = StudioConfig.STUDIO_HOST.getValue(); int port = Integer.parseInt(StudioConfig.STUDIO_PORT.getValue()); Router router = Router.router(vertx); // Handle cross-origin calls router.route().handler(CorsHandler.create("http://" + host + ":.*") // .allowedMethods(Set.of(HttpMethod.GET, HttpMethod.POST)) // .allowedHeaders(Set.of(HttpHeaders.ACCEPT.toString(), HttpHeaders.CONTENT_TYPE.toString(), HttpHeaderNames.X_REQUESTED_WITH.toString())) // .exposedHeaders(Set.of(HttpHeaders.CONTENT_LENGTH.toString(), HttpHeaders.CONTENT_TYPE.toString())) // ); // Bridge event-bus to client-side app router.mountSubRouter("/eventbus", eventBusHandler()); // Rest API router.mountSubRouter("/api", apiRouter()); // Static resources (/webroot) router.route().handler(StaticHandler.create().setCachingEnabled(false)); // Error handler ErrorHandler errorHandler = ErrorHandler.create(vertx, true); router.route().failureHandler(ctx -> { Throwable failure = ctx.failure(); LOGGER.error("Exception thrown", failure); errorHandler.handle(ctx); }); // Start HTTP server vertx.createHttpServer().requestHandler(router).listen(port); // Automatically open URL in browser, unless instructed otherwise String openBrowser = StudioConfig.STUDIO_OPEN_BROWSER.getValue(); if (Boolean.parseBoolean(openBrowser)) { LOGGER.info("Opening URL in default browser..."); if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI("http://" + host + ":" + port)); } catch (Exception e) { LOGGER.error("Failed to open URL in default browser", e); } } } } private Router eventBusHandler() { PermittedOptions address = new PermittedOptions().setAddressRegex("storyteller\\..+"); SockJSBridgeOptions options = new SockJSBridgeOptions().addOutboundPermitted(address); return SockJSHandler.create(vertx).bridge(options, event -> { if (event.type() == BridgeEventType.SOCKET_CREATED) { LOGGER.debug("New sockjs client"); } event.complete(true); }); } private Router apiRouter() { Router router = Router.router(vertx); // Handle JSON router.route().handler(BodyHandler.create()).consumes(MIME_JSON).produces(MIME_JSON); // Device services router.mountSubRouter("/device", DeviceController.apiRouter(vertx, storyTellerService)); // Library services router.mountSubRouter("/library", LibraryController.apiRouter(vertx, libraryService)); // Evergreen services
/* * 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; public class MainVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(MainVerticle.class); public static final String MIME_JSON = "application/json"; private LibraryService libraryService; private EvergreenService evergreenService; private IStoryTellerService storyTellerService; @Override public void start() { // Service that manages pack metadata DatabaseMetadataService databaseMetadataService = new DatabaseMetadataService(); // Service that manages local library libraryService = new LibraryService(databaseMetadataService); // Service that manages updates evergreenService = new EvergreenService(vertx); // Service that manages link with the story teller device if (isDevMode()) { LOGGER.warn("[DEV MODE] Initializing mock storyteller service"); storyTellerService = new MockStoryTellerService(vertx.eventBus(), databaseMetadataService); } else { storyTellerService = new StoryTellerService(vertx.eventBus(), databaseMetadataService); } // Config String host = StudioConfig.STUDIO_HOST.getValue(); int port = Integer.parseInt(StudioConfig.STUDIO_PORT.getValue()); Router router = Router.router(vertx); // Handle cross-origin calls router.route().handler(CorsHandler.create("http://" + host + ":.*") // .allowedMethods(Set.of(HttpMethod.GET, HttpMethod.POST)) // .allowedHeaders(Set.of(HttpHeaders.ACCEPT.toString(), HttpHeaders.CONTENT_TYPE.toString(), HttpHeaderNames.X_REQUESTED_WITH.toString())) // .exposedHeaders(Set.of(HttpHeaders.CONTENT_LENGTH.toString(), HttpHeaders.CONTENT_TYPE.toString())) // ); // Bridge event-bus to client-side app router.mountSubRouter("/eventbus", eventBusHandler()); // Rest API router.mountSubRouter("/api", apiRouter()); // Static resources (/webroot) router.route().handler(StaticHandler.create().setCachingEnabled(false)); // Error handler ErrorHandler errorHandler = ErrorHandler.create(vertx, true); router.route().failureHandler(ctx -> { Throwable failure = ctx.failure(); LOGGER.error("Exception thrown", failure); errorHandler.handle(ctx); }); // Start HTTP server vertx.createHttpServer().requestHandler(router).listen(port); // Automatically open URL in browser, unless instructed otherwise String openBrowser = StudioConfig.STUDIO_OPEN_BROWSER.getValue(); if (Boolean.parseBoolean(openBrowser)) { LOGGER.info("Opening URL in default browser..."); if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI("http://" + host + ":" + port)); } catch (Exception e) { LOGGER.error("Failed to open URL in default browser", e); } } } } private Router eventBusHandler() { PermittedOptions address = new PermittedOptions().setAddressRegex("storyteller\\..+"); SockJSBridgeOptions options = new SockJSBridgeOptions().addOutboundPermitted(address); return SockJSHandler.create(vertx).bridge(options, event -> { if (event.type() == BridgeEventType.SOCKET_CREATED) { LOGGER.debug("New sockjs client"); } event.complete(true); }); } private Router apiRouter() { Router router = Router.router(vertx); // Handle JSON router.route().handler(BodyHandler.create()).consumes(MIME_JSON).produces(MIME_JSON); // Device services router.mountSubRouter("/device", DeviceController.apiRouter(vertx, storyTellerService)); // Library services router.mountSubRouter("/library", LibraryController.apiRouter(vertx, libraryService)); // Evergreen services
router.mountSubRouter("/evergreen", EvergreenController.apiRouter(vertx, evergreenService));
3
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;
15,954
/* * <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"})
/* * <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(
1
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,994
} recordCounter++; streamOutput.flush(); } /** * immitate Cobol function write After Page * * @param data to write * @throws IOException */ public void writeAfterPage(Object data) throws IOException { if (data instanceof String) { if (this.advancing) { streamOutput.write(("1" + data.toString() + lineSeparator).getBytes());// need to add 1 on the begining // of the record if advancing } else { streamOutput.write((data.toString() + lineSeparator).getBytes()); } } else if (data instanceof StructureModel) { byte[] structure = ((StructureModel) data).toFile(); byte[] newStructure = new byte[structure.length + 2]; if (this.advancing) { newStructure[0] = "1".getBytes()[0]; } for (int i = 1; i <= structure.length; i++) { newStructure[i] = structure[i - 1]; } newStructure[newStructure.length - 1] = String.valueOf(lineSeparator).getBytes()[0]; streamOutput.write(newStructure); } streamOutput.flush(); } /** * writes StructureModel objects to file * * @param model object to write * @throws IOException */ public void write(StructureModel model) throws IOException { if (this.type.compareTo(TypeOrganization.LINE_SEQUENTIAL) == 0) { if (this.advancing) { streamOutput.write(" ".getBytes()); streamOutput.write(model.toFile()); streamOutput.write(lineSeparator.getBytes()); } else { streamOutput.write(model.toFile()); streamOutput.write(lineSeparator.getBytes()); } } else if (this.advancing) { streamOutput.write(" ".getBytes()); streamOutput.write(model.toFile()); } else { streamOutput.write(model.toFile()); } streamOutput.flush(); } /** * closes file * * @throws IOException */ public void close() throws IOException { if (streamInput != null) { streamInput.close(); buffReader.close(); } if (streamOutput != null) { streamOutput.close(); } } public static byte[] transcodeField(byte[] source, Charset from, Charset to) { byte[] result = new String(source, from).getBytes(to); if (result.length != source.length) { throw new AssertionError(result.length + "!=" + source.length); } return result; } public boolean hasNext() throws IOException { return streamInput.available() > 0; } public String readIO(StructureModel strRec) throws IOException { strRec.setData(new String(Files.readAllBytes(Paths.get(this.name))).toCharArray()); return strRec.toString(); } public List<String> readTextFileByLines(String fileName) throws IOException { List<String> lines = Files.readAllLines(Paths.get(fileName)); return lines; } public void rewrite(String fileName, String content) throws IOException { List<String> lines = Files.readAllLines(file.toPath()); lines.set(recordCounter - 1, content); Files.write(file.toPath(), lines, StandardOpenOption.WRITE); } public void rewrite(String fileName, StructureModel model) throws IOException { List<String> lines = Files.readAllLines(file.toPath()); lines.set(recordCounter - 1, model.toString()); Files.write(file.toPath(), lines, StandardOpenOption.WRITE); } public String getName() { return this.name; } /** * Sort file * * @param sortKeys collection of keys to sort * @param record specify Type of records in file * @return */ @SuppressWarnings("unchecked")
/* © 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 { try { recordCounter = 0; streamOutput = new FileOutputStream(file, append); // file is opened for writing if (status != null) { status.setData("00".toCharArray()); } } catch (FileNotFoundException exc) { LOGGER.log(Level.WARNING, exc.getMessage()); if (status != null) { status.setData("37".toCharArray()); } } } /** * This method opens file for reading * * @param status status structure. use null value if you don't have this * structure * @throws IOException */ public void openInput(StructureModel status) throws IOException { try { recordCounter = 0; if(csv){ csvReader = new CSVReader(new FileReader(file.getName())); } else{ streamInput = new FileInputStream(file); // file is opened for reading buffReader = // Here BufferedReader object creates. Need for reading file by lines isEBCDIC ? Files.newBufferedReader(file.toPath(), Charset.forName("IBM1047")) : // If File in // EBCIDIC need to // create // BufferedReader // object with // encoding new BufferedReader(new InputStreamReader(streamInput)); if (status != null) { status.setData("00".toCharArray()); } } } catch (FileNotFoundException exc) { LOGGER.log(Level.WARNING, exc.getMessage()); if (status != null) { status.setData("35".toCharArray()); } } } /** * reads one record from file * * @param strRec record object * @return record that was read * @throws IOException when file is finished or some error occurs during reading * when file is finished codeError = 0 if codeError != 0 * there is some error in reading this file */ public String read(StructureModel strRec) throws IOException { recordCounter++; if (!csv && streamInput == null) { // check if file is opened this.codeError = 1; throw new IOException(); } String line; int lineNum = 0; if(csv){ String[] values = null; values = csvReader.readNext(); strRec.setData(values); // set data to record object return strRec.toString(); } else{ if (isEBCDIC) {// need to read line for EBCIDIC file other way PictureType.isEBSDIC = true; char[] buff = new char[recordSize]; lineNum = buffReader.read(buff); // reading line line = new String(buff); } else { PictureType.isEBSDIC = false; line = buffReader.readLine(); // reading line } } if (lineNum == -1 || line == null) { // check if EOF this.codeError = 0; throw new IOException(); } strRec.setData(line.toCharArray()); // set data to record object return strRec.toString(); } public String readIndexed(StructureModel strRec, String key) throws IOException { byte[] data = new byte[strRec.getSize()]; if (streamInput == null) { throw new IOException(); } int sizeRead = streamInput.read(data); int sizeReadFinal = sizeRead; List<String> listFile = new ArrayList<>(); byte[] allData; allData = Files.readAllBytes(Paths.get(name)); if (Files.readAllLines(Paths.get(name), StandardCharsets.ISO_8859_1).get(0).length() > 130 && Files .readAllLines(Paths.get(name), StandardCharsets.ISO_8859_1).get(0).substring(0, 130).contains("@")) { String newLine = Files.readAllLines(Paths.get(name), StandardCharsets.ISO_8859_1).get(0).substring(131); allData = newLine.getBytes(); int i = 0; while (i < allData.length) { listFile.add(new String(allData).substring(i, sizeRead - 1)); i = sizeRead + 2; sizeRead = sizeRead + sizeReadFinal + 3; } } else { int i = 0; while (i < allData.length) { listFile.add(new String(allData).substring(i, sizeRead)); i = sizeRead; sizeRead += sizeReadFinal; } } if (key == null) { return listFile.get(listFile.size() - 1); } else { for (String record : listFile) { strRec.setData(record.toCharArray()); try { if (strRec.getClass().getField(key).get(strRec).toString().equals(keys.get(key))) { strRec.setDataFromFile(record.getBytes()); return strRec.toString(); } } catch (IllegalAccessException | NoSuchFieldException e) { LOGGER.info(String.valueOf(e)); } } } return null; } /** * writing data to file * * @param data to write * @throws IOException */ public void write(String data) throws IOException { if (this.type.compareTo(TypeOrganization.LINE_SEQUENTIAL) == 0) { if (this.advancing) { // if advancing need to add space in the begining of the record streamOutput.write((" " + data + lineSeparator).getBytes()); // in the end of record adding // lineSeparator } else { streamOutput.write((data + lineSeparator).getBytes()); } } else if (this.advancing) { streamOutput.write((" " + data).getBytes()); } else { streamOutput.write(data.getBytes()); } recordCounter++; streamOutput.flush(); } /** * immitate Cobol function write After Line * * @param data to write * @param line after that need to write. * @throws IOException */ public void writeAfterLine(Object data, int line) throws IOException { if (this.advancing) { // // left this code commented because we don't know why WRITE AFTER ADVANCING n // LINES doesn't add blank lines in COBOL. // The situation when it will add lines can be. // // if(recordCounter == 0){ // streamOutput.write(StringUtils.repeat(lineSeparator, line).getBytes()); // } else{ // streamOutput.write(StringUtils.repeat(lineSeparator, line-1).getBytes()); // } streamOutput.write(("0" + data.toString() + lineSeparator).getBytes()); // need to add zero on the begining // of the record if advancing } else { streamOutput.write((data.toString() + lineSeparator).getBytes()); streamOutput.write(StringUtils.repeat(lineSeparator, line).getBytes()); // writes line count of lines before // record } recordCounter++; streamOutput.flush(); } /** * immitate Cobol function write After Page * * @param data to write * @throws IOException */ public void writeAfterPage(Object data) throws IOException { if (data instanceof String) { if (this.advancing) { streamOutput.write(("1" + data.toString() + lineSeparator).getBytes());// need to add 1 on the begining // of the record if advancing } else { streamOutput.write((data.toString() + lineSeparator).getBytes()); } } else if (data instanceof StructureModel) { byte[] structure = ((StructureModel) data).toFile(); byte[] newStructure = new byte[structure.length + 2]; if (this.advancing) { newStructure[0] = "1".getBytes()[0]; } for (int i = 1; i <= structure.length; i++) { newStructure[i] = structure[i - 1]; } newStructure[newStructure.length - 1] = String.valueOf(lineSeparator).getBytes()[0]; streamOutput.write(newStructure); } streamOutput.flush(); } /** * writes StructureModel objects to file * * @param model object to write * @throws IOException */ public void write(StructureModel model) throws IOException { if (this.type.compareTo(TypeOrganization.LINE_SEQUENTIAL) == 0) { if (this.advancing) { streamOutput.write(" ".getBytes()); streamOutput.write(model.toFile()); streamOutput.write(lineSeparator.getBytes()); } else { streamOutput.write(model.toFile()); streamOutput.write(lineSeparator.getBytes()); } } else if (this.advancing) { streamOutput.write(" ".getBytes()); streamOutput.write(model.toFile()); } else { streamOutput.write(model.toFile()); } streamOutput.flush(); } /** * closes file * * @throws IOException */ public void close() throws IOException { if (streamInput != null) { streamInput.close(); buffReader.close(); } if (streamOutput != null) { streamOutput.close(); } } public static byte[] transcodeField(byte[] source, Charset from, Charset to) { byte[] result = new String(source, from).getBytes(to); if (result.length != source.length) { throw new AssertionError(result.length + "!=" + source.length); } return result; } public boolean hasNext() throws IOException { return streamInput.available() > 0; } public String readIO(StructureModel strRec) throws IOException { strRec.setData(new String(Files.readAllBytes(Paths.get(this.name))).toCharArray()); return strRec.toString(); } public List<String> readTextFileByLines(String fileName) throws IOException { List<String> lines = Files.readAllLines(Paths.get(fileName)); return lines; } public void rewrite(String fileName, String content) throws IOException { List<String> lines = Files.readAllLines(file.toPath()); lines.set(recordCounter - 1, content); Files.write(file.toPath(), lines, StandardOpenOption.WRITE); } public void rewrite(String fileName, StructureModel model) throws IOException { List<String> lines = Files.readAllLines(file.toPath()); lines.set(recordCounter - 1, model.toString()); Files.write(file.toPath(), lines, StandardOpenOption.WRITE); } public String getName() { return this.name; } /** * Sort file * * @param sortKeys collection of keys to sort * @param record specify Type of records in file * @return */ @SuppressWarnings("unchecked")
public List<T> sortFile(List<SortKeys> sortKeys, T record) {// }, int[] sizes){
1
2023-12-13 14:56:32+00:00
24k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/tag/mp4/field/Mp4TagReverseDnsField.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 org.jaudiotagger.StandardCharsets; import org.jaudiotagger.audio.generic.Utils; import org.jaudiotagger.audio.mp4.atom.Mp4BoxHeader; import org.jaudiotagger.logging.ErrorMessage; import org.jaudiotagger.tag.TagField; import org.jaudiotagger.tag.TagTextField; import org.jaudiotagger.tag.mp4.Mp4FieldKey; import org.jaudiotagger.tag.mp4.Mp4TagField; import org.jaudiotagger.tag.mp4.atom.Mp4DataBox; import org.jaudiotagger.tag.mp4.atom.Mp4MeanBox; import org.jaudiotagger.tag.mp4.atom.Mp4NameBox; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset;
21,224
package org.jaudiotagger.tag.mp4.field; /** * Represents reverse dns field, used for custom information * * <p>Originally only used by Itunes for information that was iTunes specific but now used in a wide range of uses, * for example Musicbrainz uses it for many of its fields. * * These fields have a more complex setup * Box ---- shows this is a reverse dns metadata field * Box mean the issuer in the form of reverse DNS domain (e.g com.apple.iTunes) * Box name descriptor identifying the type of contents * Box data contents * * The raw data passed starts from the mean box */ public class Mp4TagReverseDnsField extends Mp4TagField implements TagTextField { public static final String IDENTIFIER = "----"; protected int dataSize; //Issuer private String issuer; //Descriptor private String descriptor; //Data Content, //TODO assuming always text at the moment protected String content; /** * Construct from existing file data * * @param parentHeader * @param data * @throws UnsupportedEncodingException */
package org.jaudiotagger.tag.mp4.field; /** * Represents reverse dns field, used for custom information * * <p>Originally only used by Itunes for information that was iTunes specific but now used in a wide range of uses, * for example Musicbrainz uses it for many of its fields. * * These fields have a more complex setup * Box ---- shows this is a reverse dns metadata field * Box mean the issuer in the form of reverse DNS domain (e.g com.apple.iTunes) * Box name descriptor identifying the type of contents * Box data contents * * The raw data passed starts from the mean box */ public class Mp4TagReverseDnsField extends Mp4TagField implements TagTextField { public static final String IDENTIFIER = "----"; protected int dataSize; //Issuer private String issuer; //Descriptor private String descriptor; //Data Content, //TODO assuming always text at the moment protected String content; /** * Construct from existing file data * * @param parentHeader * @param data * @throws UnsupportedEncodingException */
public Mp4TagReverseDnsField(Mp4BoxHeader parentHeader, ByteBuffer data) throws UnsupportedEncodingException
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,224
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()) {
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());
13
2023-12-12 08:16:30+00:00
24k