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
Manzzx/multi-channel-message-reach
metax-web/src/main/java/com/metax/web/service/impl/EChartsDataServiceImpl.java
[ { "identifier": "MetaxDataConstants", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/constant/MetaxDataConstants.java", "snippet": "public class MetaxDataConstants {\n\n public static final String SEPARATOR = \",\";\n\n public static final String JSON_LEFT_BRACE = \"{\...
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.metax.common.core.constant.MetaxDataConstants; import com.metax.common.core.context.SecurityContextHolder; import com.metax.system.api.domain.SysUser; import com.metax.web.domain.MessageTemplate; import com.metax.web.service.EChartsDataService; import com.metax.web.service.IDataService; import com.metax.web.service.IMessageTemplateService; import com.metax.web.service.ISysUserService; import com.metax.web.util.RedisKeyUtil; import com.metax.web.vo.echarts.IndexEChartsData; import com.metax.web.vo.echarts.TemplateEChartsData; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static com.metax.common.core.constant.MetaxDataConstants.*;
12,715
package com.metax.web.service.impl; /** * 首页eCharts图service * @Author: hanabi * @DateTime: 2023/11/2 21:20 **/ @Service @Slf4j public class EChartsDataServiceImpl implements EChartsDataService { @Autowired
package com.metax.web.service.impl; /** * 首页eCharts图service * @Author: hanabi * @DateTime: 2023/11/2 21:20 **/ @Service @Slf4j public class EChartsDataServiceImpl implements EChartsDataService { @Autowired
private IMessageTemplateService messageTemplateService;
6
2023-12-04 05:10:13+00:00
16k
ydb-platform/yoj-project
repository-test/src/main/java/tech/ydb/yoj/repository/test/sample/TestEntityOperations.java
[ { "identifier": "BaseDb", "path": "repository/src/main/java/tech/ydb/yoj/repository/BaseDb.java", "snippet": "public interface BaseDb {\n static <T> T current(Class<T> type) {\n return Proxies.proxy(type, () -> Tx.Current.get().getRepositoryTransaction());\n }\n\n <T extends Entity<T>> T...
import tech.ydb.yoj.repository.BaseDb; import tech.ydb.yoj.repository.db.AbstractDelegatingTable; import tech.ydb.yoj.repository.db.Entity; import tech.ydb.yoj.repository.db.Table; import tech.ydb.yoj.repository.db.TableQueryBuilder; import tech.ydb.yoj.repository.db.bulk.BulkParams; import tech.ydb.yoj.repository.test.sample.model.Bubble; import tech.ydb.yoj.repository.test.sample.model.Complex; import tech.ydb.yoj.repository.test.sample.model.EntityWithValidation; import tech.ydb.yoj.repository.test.sample.model.IndexedEntity; import tech.ydb.yoj.repository.test.sample.model.LogEntry; import tech.ydb.yoj.repository.test.sample.model.Primitive; import tech.ydb.yoj.repository.test.sample.model.Project; import tech.ydb.yoj.repository.test.sample.model.Referring; import tech.ydb.yoj.repository.test.sample.model.Supabubble; import tech.ydb.yoj.repository.test.sample.model.Supabubble2; import tech.ydb.yoj.repository.test.sample.model.Team; import tech.ydb.yoj.repository.test.sample.model.TypeFreak; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList;
11,473
package tech.ydb.yoj.repository.test.sample; public interface TestEntityOperations extends BaseDb { ProjectTable projects(); BubbleTable bubbles(); ComplexTable complexes(); TypeFreakTable typeFreaks(); Table<Primitive> primitives(); Table<Referring> referrings(); Table<LogEntry> logEntries(); Table<Team> teams(); Table<EntityWithValidation> entitiesWithValidation(); IndexedTable indexedTable(); SupabubbleTable supabubbles(); Supabubble2Table supabubbles2(); class ProjectTable extends AbstractDelegatingTable<Project> { public ProjectTable(Table<Project> target) { super(target); } public List<Project> findNamed() { return query() .where("name").isNotNull() .find(); } public List<Project> findTopNamed(int n) { return query() .where("name").isNotNull() .limit(n) .find(); } public void updateName(Project.Id id, String newName) { modifyIfPresent(id, t -> t.withName(newName)); } public List<Project> findByPredicateWithManyIds(Collection<Project.Id> ids) { return query().where("id").in(ids).find(); } public List<Project> findByPredicateWithManyIdValues(Collection<String> ids) { return query().where("id").in(ids).find(); } @Override public void bulkUpsert(List<Project> input, BulkParams params) { getTarget().bulkUpsert(input, params); } } class TypeFreakTable extends AbstractDelegatingTable<TypeFreak> { public TypeFreakTable(Table<TypeFreak> target) { super(target); } public List<TypeFreak> findWithEmbeddedAIn(String possibleA, String... otherPossibleAs) { List<String> lst = new ArrayList<>(1 + otherPossibleAs.length); lst.add(possibleA); lst.addAll(asList(otherPossibleAs)); return findWithEmbeddedAIn(unmodifiableList(lst)); } public List<TypeFreak> findWithEmbeddedAIn(Collection<String> possibleA) { return query().where("embedded.a.a").in(possibleA).find(); } public List<TypeFreak> findWithEmbeddedANotIn(Collection<String> possibleA) { return query().where("embedded.a.a").notIn(possibleA).find(); } public List<TypeFreak> findWithEmbeddedBNotEqualTo(String prohibitedB) { return query().where("embedded.b.b").neq(prohibitedB).find(); } public TypeFreak findByPredicateWithComplexId(TypeFreak.Id id) { return find(id); } public List<TypeFreak.View> findViewWithEmbeddedAIn(Collection<String> possibleA) { return query() .where("embedded.a.a").in(possibleA) .find(TypeFreak.View.class); } public void updateEmbedded(TypeFreak.Id id, TypeFreak.Embedded newEmbedded) { modifyIfPresent(id, t -> t.withEmbedded(newEmbedded)); } } interface TableWithQueryBuilder<T extends Entity<T>> extends Table<T> { @Override TableQueryBuilder<T> query(); } interface ComplexTable extends TableWithQueryBuilder<Complex> { } interface BubbleTable extends Table<Bubble> { void updateSomeFields(Set<Bubble.Id> ids, String fieldA, String fieldB); } interface IndexedTable extends TableWithQueryBuilder<IndexedEntity> { void updateSomeFields(Set<IndexedEntity.Id> ids, String value, String value2); } class SupabubbleTable extends AbstractDelegatingTable<Supabubble> { public SupabubbleTable(Table<Supabubble> target) { super(target); } @Override public TableQueryBuilder<Supabubble> query() { return super.query(); } }
package tech.ydb.yoj.repository.test.sample; public interface TestEntityOperations extends BaseDb { ProjectTable projects(); BubbleTable bubbles(); ComplexTable complexes(); TypeFreakTable typeFreaks(); Table<Primitive> primitives(); Table<Referring> referrings(); Table<LogEntry> logEntries(); Table<Team> teams(); Table<EntityWithValidation> entitiesWithValidation(); IndexedTable indexedTable(); SupabubbleTable supabubbles(); Supabubble2Table supabubbles2(); class ProjectTable extends AbstractDelegatingTable<Project> { public ProjectTable(Table<Project> target) { super(target); } public List<Project> findNamed() { return query() .where("name").isNotNull() .find(); } public List<Project> findTopNamed(int n) { return query() .where("name").isNotNull() .limit(n) .find(); } public void updateName(Project.Id id, String newName) { modifyIfPresent(id, t -> t.withName(newName)); } public List<Project> findByPredicateWithManyIds(Collection<Project.Id> ids) { return query().where("id").in(ids).find(); } public List<Project> findByPredicateWithManyIdValues(Collection<String> ids) { return query().where("id").in(ids).find(); } @Override public void bulkUpsert(List<Project> input, BulkParams params) { getTarget().bulkUpsert(input, params); } } class TypeFreakTable extends AbstractDelegatingTable<TypeFreak> { public TypeFreakTable(Table<TypeFreak> target) { super(target); } public List<TypeFreak> findWithEmbeddedAIn(String possibleA, String... otherPossibleAs) { List<String> lst = new ArrayList<>(1 + otherPossibleAs.length); lst.add(possibleA); lst.addAll(asList(otherPossibleAs)); return findWithEmbeddedAIn(unmodifiableList(lst)); } public List<TypeFreak> findWithEmbeddedAIn(Collection<String> possibleA) { return query().where("embedded.a.a").in(possibleA).find(); } public List<TypeFreak> findWithEmbeddedANotIn(Collection<String> possibleA) { return query().where("embedded.a.a").notIn(possibleA).find(); } public List<TypeFreak> findWithEmbeddedBNotEqualTo(String prohibitedB) { return query().where("embedded.b.b").neq(prohibitedB).find(); } public TypeFreak findByPredicateWithComplexId(TypeFreak.Id id) { return find(id); } public List<TypeFreak.View> findViewWithEmbeddedAIn(Collection<String> possibleA) { return query() .where("embedded.a.a").in(possibleA) .find(TypeFreak.View.class); } public void updateEmbedded(TypeFreak.Id id, TypeFreak.Embedded newEmbedded) { modifyIfPresent(id, t -> t.withEmbedded(newEmbedded)); } } interface TableWithQueryBuilder<T extends Entity<T>> extends Table<T> { @Override TableQueryBuilder<T> query(); } interface ComplexTable extends TableWithQueryBuilder<Complex> { } interface BubbleTable extends Table<Bubble> { void updateSomeFields(Set<Bubble.Id> ids, String fieldA, String fieldB); } interface IndexedTable extends TableWithQueryBuilder<IndexedEntity> { void updateSomeFields(Set<IndexedEntity.Id> ids, String value, String value2); } class SupabubbleTable extends AbstractDelegatingTable<Supabubble> { public SupabubbleTable(Table<Supabubble> target) { super(target); } @Override public TableQueryBuilder<Supabubble> query() { return super.query(); } }
interface Supabubble2Table extends Table<Supabubble2> {
15
2023-12-05 15:57:58+00:00
16k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/LocalLoginFragment.java
[ { "identifier": "Tools", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Tools.java", "snippet": "@SuppressWarnings(\"IOStreamConstructor\")\npublic final class Tools {\n public static final float BYTE_TO_MB = 1024 * 1024;\n public static final Handler MAIN_HANDLER = new Handler(Loop...
import android.os.Bundle; import android.view.View; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import java.io.File;
13,535
package net.kdt.pojavlaunch.fragments; public class LocalLoginFragment extends Fragment { public static final String TAG = "LOCAL_LOGIN_FRAGMENT"; private EditText mUsernameEditText; public LocalLoginFragment(){ super(R.layout.fragment_local_login); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { mUsernameEditText = view.findViewById(R.id.login_edit_email); view.findViewById(R.id.login_button).setOnClickListener(v -> { if(!checkEditText()) return;
package net.kdt.pojavlaunch.fragments; public class LocalLoginFragment extends Fragment { public static final String TAG = "LOCAL_LOGIN_FRAGMENT"; private EditText mUsernameEditText; public LocalLoginFragment(){ super(R.layout.fragment_local_login); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { mUsernameEditText = view.findViewById(R.id.login_edit_email); view.findViewById(R.id.login_button).setOnClickListener(v -> { if(!checkEditText()) return;
ExtraCore.setValue(ExtraConstants.MOJANG_LOGIN_TODO, new String[]{
1
2023-12-01 16:16:12+00:00
16k
kawashirov/distant-horizons
common/src/main/java/com/seibel/distanthorizons/common/wrappers/worldGeneration/step/StepStructureStart.java
[ { "identifier": "ChunkWrapper", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/chunk/ChunkWrapper.java", "snippet": "public class ChunkWrapper implements IChunkWrapper\n{\n\tprivate static final Logger LOGGER = DhLoggerBuilder.getLogger();\n\t\n\t/** useful for debugging, but c...
import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.ProtoChunk; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.ReentrantLock; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import com.seibel.distanthorizons.common.wrappers.worldGeneration.BatchGenerationEnvironment; import com.seibel.distanthorizons.common.wrappers.worldGeneration.ThreadedParameters; import com.seibel.distanthorizons.core.logging.DhLoggerBuilder; import net.minecraft.server.level.WorldGenRegion; import net.minecraft.world.level.chunk.ChunkAccess;
12,053
/* * 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.worldGeneration.step; public final class StepStructureStart { private static final Logger LOGGER = DhLoggerBuilder.getLogger(); private static final ChunkStatus STATUS = ChunkStatus.STRUCTURE_STARTS; private static final ReentrantLock STRUCTURE_PLACEMENT_LOCK = new ReentrantLock(); private final BatchGenerationEnvironment environment; public StepStructureStart(BatchGenerationEnvironment batchGenerationEnvironment) { this.environment = batchGenerationEnvironment; } public static class StructStartCorruptedException extends RuntimeException { private static final long serialVersionUID = -8987434342051563358L; public StructStartCorruptedException(ArrayIndexOutOfBoundsException e) { super("StructStartCorruptedException"); super.initCause(e); fillInStackTrace(); } } public void generateGroup( ThreadedParameters tParams, WorldGenRegion worldGenRegion,
/* * 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.worldGeneration.step; public final class StepStructureStart { private static final Logger LOGGER = DhLoggerBuilder.getLogger(); private static final ChunkStatus STATUS = ChunkStatus.STRUCTURE_STARTS; private static final ReentrantLock STRUCTURE_PLACEMENT_LOCK = new ReentrantLock(); private final BatchGenerationEnvironment environment; public StepStructureStart(BatchGenerationEnvironment batchGenerationEnvironment) { this.environment = batchGenerationEnvironment; } public static class StructStartCorruptedException extends RuntimeException { private static final long serialVersionUID = -8987434342051563358L; public StructStartCorruptedException(ArrayIndexOutOfBoundsException e) { super("StructStartCorruptedException"); super.initCause(e); fillInStackTrace(); } } public void generateGroup( ThreadedParameters tParams, WorldGenRegion worldGenRegion,
List<ChunkWrapper> chunkWrappers) throws InterruptedException
0
2023-12-04 11:41:46+00:00
16k
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;
13,482
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<>();
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);
7
2023-12-01 11:38:42+00:00
16k
vvbbnn00/JavaWeb-CanteenSystem
JavaBackend/src/main/java/cn/vvbbnn00/canteen/controller/rest/ItemResource.java
[ { "identifier": "ItemListRequest", "path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/dto/request/ItemListRequest.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class ItemListRequest extends BasicListRequest {\n @Min(value = 1, message = \"无效的食堂Id\")\n private Integer c...
import cn.vvbbnn00.canteen.annotation.CheckRole; import cn.vvbbnn00.canteen.dto.request.ItemListRequest; import cn.vvbbnn00.canteen.dto.response.BasicDataResponse; import cn.vvbbnn00.canteen.dto.response.BasicListResponse; import cn.vvbbnn00.canteen.model.Comment; import cn.vvbbnn00.canteen.model.Item; import cn.vvbbnn00.canteen.service.CommentService; import cn.vvbbnn00.canteen.service.ItemService; import cn.vvbbnn00.canteen.util.RequestValidatorUtils; import jakarta.enterprise.context.RequestScoped; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotNull; import jakarta.ws.rs.*; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.SecurityContext;
11,187
package cn.vvbbnn00.canteen.controller.rest; @Path("/canteen") @RequestScoped public class ItemResource { @Context SecurityContext securityContext; ItemService itemService = new ItemService(); CommentService commentService = new CommentService(); @POST @Path("/{canteenId}/cuisine/{cuisineId}/item") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @CheckRole("canteen_admin") public BasicDataResponse restAddItem( @PathParam("canteenId") @NotNull @Min(value = 1, message = "无效的食堂Id") Integer canteenId, @PathParam("cuisineId") @NotNull @Min(value = 1, message = "无效的菜品Id") Integer cuisineId, Item item ) { // 校验请求参数,请仔细阅读该方法的文档 RequestValidatorUtils.doHibernateParamsValidate(canteenId, cuisineId, item); RequestValidatorUtils.doHibernateValidate(item); BasicDataResponse response = new BasicDataResponse(); try { Integer userId = Integer.parseInt(securityContext.getUserPrincipal().getName()); item.setCuisineId(cuisineId); Item result = itemService.addItem( item, userId, canteenId ); response.setData(result); response.setMessage("创建菜品成功"); } catch (Exception e) { response.setCode(400); response.setMessage(e.getMessage()); } return response; } @GET @Path("/item/{itemId}") @Produces(MediaType.APPLICATION_JSON) public BasicDataResponse restGetItem( @PathParam("itemId") @NotNull @Min(value = 1, message = "无效的菜品Id") Integer itemId ) { // 校验请求参数,请仔细阅读该方法的文档 RequestValidatorUtils.doHibernateParamsValidate(itemId); BasicDataResponse response = new BasicDataResponse(); try { Item result = itemService.getItemById(itemId); if (result == null) { response.setCode(404); response.setMessage("菜品不存在"); } else { response.setData(result); } } catch (Exception e) { response.setCode(400); response.setMessage(e.getMessage()); } return response; } @GET @Path("/{canteenId}/cuisine/{cuisineId}/item/{itemId}") @Produces(MediaType.APPLICATION_JSON) @CheckRole("user") public BasicDataResponse restGetItemAlia1( @PathParam("canteenId") @NotNull @Min(value = 1, message = "无效的食堂Id") Integer canteenId, @PathParam("cuisineId") @NotNull @Min(value = 1, message = "无效的菜品Id") Integer cuisineId, @PathParam("itemId") @NotNull @Min(value = 1, message = "无效的菜品Id") Integer itemId ) { // 校验请求参数,请仔细阅读该方法的文档 RequestValidatorUtils.doHibernateParamsValidate(canteenId, cuisineId, itemId); BasicDataResponse response = new BasicDataResponse(); try { Item result = itemService.getItemById(itemId); response.setData(result); } catch (Exception e) { response.setCode(400); response.setMessage(e.getMessage()); } return response; } @POST @Path("/item/list") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @CheckRole("user") public BasicListResponse restGetItemList(
package cn.vvbbnn00.canteen.controller.rest; @Path("/canteen") @RequestScoped public class ItemResource { @Context SecurityContext securityContext; ItemService itemService = new ItemService(); CommentService commentService = new CommentService(); @POST @Path("/{canteenId}/cuisine/{cuisineId}/item") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @CheckRole("canteen_admin") public BasicDataResponse restAddItem( @PathParam("canteenId") @NotNull @Min(value = 1, message = "无效的食堂Id") Integer canteenId, @PathParam("cuisineId") @NotNull @Min(value = 1, message = "无效的菜品Id") Integer cuisineId, Item item ) { // 校验请求参数,请仔细阅读该方法的文档 RequestValidatorUtils.doHibernateParamsValidate(canteenId, cuisineId, item); RequestValidatorUtils.doHibernateValidate(item); BasicDataResponse response = new BasicDataResponse(); try { Integer userId = Integer.parseInt(securityContext.getUserPrincipal().getName()); item.setCuisineId(cuisineId); Item result = itemService.addItem( item, userId, canteenId ); response.setData(result); response.setMessage("创建菜品成功"); } catch (Exception e) { response.setCode(400); response.setMessage(e.getMessage()); } return response; } @GET @Path("/item/{itemId}") @Produces(MediaType.APPLICATION_JSON) public BasicDataResponse restGetItem( @PathParam("itemId") @NotNull @Min(value = 1, message = "无效的菜品Id") Integer itemId ) { // 校验请求参数,请仔细阅读该方法的文档 RequestValidatorUtils.doHibernateParamsValidate(itemId); BasicDataResponse response = new BasicDataResponse(); try { Item result = itemService.getItemById(itemId); if (result == null) { response.setCode(404); response.setMessage("菜品不存在"); } else { response.setData(result); } } catch (Exception e) { response.setCode(400); response.setMessage(e.getMessage()); } return response; } @GET @Path("/{canteenId}/cuisine/{cuisineId}/item/{itemId}") @Produces(MediaType.APPLICATION_JSON) @CheckRole("user") public BasicDataResponse restGetItemAlia1( @PathParam("canteenId") @NotNull @Min(value = 1, message = "无效的食堂Id") Integer canteenId, @PathParam("cuisineId") @NotNull @Min(value = 1, message = "无效的菜品Id") Integer cuisineId, @PathParam("itemId") @NotNull @Min(value = 1, message = "无效的菜品Id") Integer itemId ) { // 校验请求参数,请仔细阅读该方法的文档 RequestValidatorUtils.doHibernateParamsValidate(canteenId, cuisineId, itemId); BasicDataResponse response = new BasicDataResponse(); try { Item result = itemService.getItemById(itemId); response.setData(result); } catch (Exception e) { response.setCode(400); response.setMessage(e.getMessage()); } return response; } @POST @Path("/item/list") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @CheckRole("user") public BasicListResponse restGetItemList(
ItemListRequest request
0
2023-12-01 04:55:12+00:00
16k
SuperRicky14/TpaPlusPlus
src/main/java/net/superricky/tpaplusplus/util/manager/AsyncTaskManager.java
[ { "identifier": "Main", "path": "src/main/java/net/superricky/tpaplusplus/Main.java", "snippet": "@Mod(Main.MOD_ID)\npublic class Main {\n // Our mod id\n public static final String MOD_ID = \"tpaplusplus\";\n public static final String MOD_VERSION = \"1.3-1.20.x-BETA-3\";\n\n public Main() ...
import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.mojang.logging.LogUtils; import net.minecraft.network.chat.Component; import net.minecraftforge.common.MinecraftForge; import net.superricky.tpaplusplus.Main; import net.superricky.tpaplusplus.util.Request; import net.superricky.tpaplusplus.util.configuration.Config; import net.superricky.tpaplusplus.util.configuration.Messages; import net.superricky.tpaplusplus.event.RequestAcceptSuccessEvent; import net.superricky.tpaplusplus.event.RequestTimeoutEvent; import net.superricky.tpaplusplus.util.configuration.formatters.MessageParser; import net.superricky.tpaplusplus.util.limitations.LimitationManager; import net.superricky.tpaplusplus.util.manager.saved.SaveDataManager; import org.slf4j.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
13,818
package net.superricky.tpaplusplus.util.manager; public class AsyncTaskManager { private static final Logger LOGGER = LogUtils.getLogger(); private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(Config.ASYNC_GENERAL_TASKS_THREAD_POOL.get()); private AsyncTaskManager() { } public static void scheduleTeleportTimeout(Request request) { executorService.schedule(() -> MinecraftForge.EVENT_BUS.post(new RequestTimeoutEvent(request)), Config.TPA_TIMEOUT_IN_SECONDS.get(), TimeUnit.SECONDS); } // Starts a countdown based on the configured time in the configTPAAcceptSuccessEvent public static synchronized void startTPAAcceptCountdown(Request request) { if (request.isAccepted()) { request.getReceiver().sendSystemMessage(Component.literal("§cYou have already accepted the request!")); return; } if (!(RequestManager.alreadySentTeleportRequest(request))) return; if (!LimitationManager.notifyAndCheckAllowedToTeleport(request.getReceiver(), request.getSender(), true)) return; request.setAccepted(true); if (request.isHereRequest()) request.setAcceptPosition(request.getReceiver().getX(), request.getReceiver().getY(), request.getReceiver().getZ()); else request.setAcceptPosition(request.getSender().getX(), request.getSender().getY(), request.getSender().getZ());
package net.superricky.tpaplusplus.util.manager; public class AsyncTaskManager { private static final Logger LOGGER = LogUtils.getLogger(); private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(Config.ASYNC_GENERAL_TASKS_THREAD_POOL.get()); private AsyncTaskManager() { } public static void scheduleTeleportTimeout(Request request) { executorService.schedule(() -> MinecraftForge.EVENT_BUS.post(new RequestTimeoutEvent(request)), Config.TPA_TIMEOUT_IN_SECONDS.get(), TimeUnit.SECONDS); } // Starts a countdown based on the configured time in the configTPAAcceptSuccessEvent public static synchronized void startTPAAcceptCountdown(Request request) { if (request.isAccepted()) { request.getReceiver().sendSystemMessage(Component.literal("§cYou have already accepted the request!")); return; } if (!(RequestManager.alreadySentTeleportRequest(request))) return; if (!LimitationManager.notifyAndCheckAllowedToTeleport(request.getReceiver(), request.getSender(), true)) return; request.setAccepted(true); if (request.isHereRequest()) request.setAcceptPosition(request.getReceiver().getX(), request.getReceiver().getY(), request.getReceiver().getZ()); else request.setAcceptPosition(request.getSender().getX(), request.getSender().getY(), request.getSender().getZ());
request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.ACCEPT_COUNTDOWN_MESSAGE_START.get(), Config.TPA_ACCEPT_TIME_IN_SECONDS.get())));
3
2023-12-02 05:41:24+00:00
16k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/model/conditions/AlphabeticalCondition.java
[ { "identifier": "ActivityHelper", "path": "app/src/main/java/de/rampro/activitydiary/helpers/ActivityHelper.java", "snippet": "public class ActivityHelper extends AsyncQueryHandler{\n private static final String TAG = ActivityHelper.class.getName();\n\n private static final int QUERY_ALL_ACTIVITIE...
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import de.rampro.activitydiary.helpers.ActivityHelper; import de.rampro.activitydiary.model.DiaryActivity; import de.rampro.activitydiary.ui.settings.SettingsActivity;
12,618
/* * 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 the alphabetical sorting of their names */ public class AlphabeticalCondition extends Condition implements ActivityHelper.DataChangedListener { public AlphabeticalCondition(ActivityHelper helper){ helper.registerDataChangeListener(this); } protected void doEvaluation(){ double weight = Double.parseDouble(sharedPreferences.getString(SettingsActivity.KEY_PREF_COND_ALPHA, "5")); ArrayList<Likelihood> result = new ArrayList<>(ActivityHelper.helper.getUnsortedActivities().size()); if(weight > 0.001) {
/* * 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 the alphabetical sorting of their names */ public class AlphabeticalCondition extends Condition implements ActivityHelper.DataChangedListener { public AlphabeticalCondition(ActivityHelper helper){ helper.registerDataChangeListener(this); } protected void doEvaluation(){ double weight = Double.parseDouble(sharedPreferences.getString(SettingsActivity.KEY_PREF_COND_ALPHA, "5")); ArrayList<Likelihood> result = new ArrayList<>(ActivityHelper.helper.getUnsortedActivities().size()); if(weight > 0.001) {
ArrayList<DiaryActivity> sort = new ArrayList<>(ActivityHelper.helper.getUnsortedActivities());
1
2023-12-02 12:36:40+00:00
16k
Ethylene9160/Chess
src/chess/panels/WebPanel.java
[ { "identifier": "Chess", "path": "src/chess/pieces/Chess.java", "snippet": "public abstract class Chess {\n public final static String KING = \"king\", ROOK = \"rook\", QUEEN = \"queen\",\n KNIGHT = \"knight\", BISHOP = \"bishop\", PAWN = \"pawn\";\n public static Style style = Style.DE...
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.Socket; import chess.pieces.Chess; import chess.recorder.Record; import chess.shop.MoneyShop; import chess.shop.ShengwangShop; import chess.shop.Shop; import chess.style.Style; import chess.threads.OpponentEmoThread; import chess.threads.YourEmoThread; import chess.util.Constants; import chess.util.ImagePath; import chess.web.ChessChannel; import chess.web.Receiver; import chess.web.Sender;
11,807
package chess.panels; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456"); private Sender sender; private Receiver receiver; private Socket client; private YourEmoThread yourEmoThread; private OpponentEmoThread opponentEmoThread; public Shop shengwangShop, moneyShop; JTextArea textArea = new JTextArea("系统消息:\n"); JScrollPane scrollPane; private void setRegisterDialog(){ registerDialog.setLocationRelativeTo(null); registerDialog.setLayout(new GridLayout(4,2)); confirmButton = setButton("确定", Constants.CONFIRM_BUTTON); applyButton = setButton("注册", Constants.APPLY_BUTTON); forgetButton = setButton("找密码",Constants.FORGET_BUTTON); setSignButton = setButton("换签名", Constants.SIGN_BUTTON); registerDialog.setSize(159,150); registerDialog.add(new JLabel("账号")); registerDialog.add(account); registerDialog.add(new JLabel("密码")); registerDialog.add(passward); registerDialog.add(confirmButton); registerDialog.add(applyButton); registerDialog.add(forgetButton); registerDialog.add(setSignButton); } @Override public int reverseX(int x){ return 7-x; } public WebPanel(JLabel hint, String IP, int port){ shengwangShop = new ShengwangShop(this); moneyShop = new MoneyShop(this); type = PanelType.Web; textArea.setFont(Constants.LITTLE_BLACK); scrollPane = new JScrollPane(textArea); disconnectBut = setButtons("断开连接", DISCONNECT_BUTTON); this.playerHint = hint; init(); this.setFocusable(true); this.addMouseListener(this);//自行在构造器中添加! try { client = new Socket(IP, port); } catch (IOException e) { System.out.println("webPanel_Constructure_ck: 没有连接到服务器"); JOptionPane.showMessageDialog(null, "没有连接到服务器", "错误", JOptionPane.ERROR_MESSAGE); } sender = new Sender(client); receiver = new Receiver(client, this); yourEmoThread = new YourEmoThread(this); opponentEmoThread = new OpponentEmoThread(this); new Thread(yourEmoThread).start(); new Thread(opponentEmoThread).start(); new Thread(sender).start(); new Thread(receiver).start(); prepareButton = setButtons("准备", Constants.PREPARE_BUTTON); clorButton = setButtons("交换先后手", COLOR_BUTTON); this.emoButton = setButtons("发表情", Constants.YOUR_EMO); setBounds(0,0,Constants.PANEL_WEIGHT, Constants.FRAME_HEIGHT); textArea.setColumns(15); repaint(); setRegisterDialog(); } public WebPanel(JLabel hint) { this(hint, Constants.HOST, Constants.PORT); } @Override public void paint(Graphics g) { super.paint(g);//clear scrollPane.setBounds(540,350,205,240); add(scrollPane); this.setBounds(0, 0, Constants.PANEL_WEIGHT, Constants.FRAME_HEIGHT); // g.drawImage(Toolkit.getDefaultToolkit().getImage(ImagePath.BACKGROUND), // 0, 0, BOARD_WEIGHT, BOARD_HEIGHT, this);
package chess.panels; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456"); private Sender sender; private Receiver receiver; private Socket client; private YourEmoThread yourEmoThread; private OpponentEmoThread opponentEmoThread; public Shop shengwangShop, moneyShop; JTextArea textArea = new JTextArea("系统消息:\n"); JScrollPane scrollPane; private void setRegisterDialog(){ registerDialog.setLocationRelativeTo(null); registerDialog.setLayout(new GridLayout(4,2)); confirmButton = setButton("确定", Constants.CONFIRM_BUTTON); applyButton = setButton("注册", Constants.APPLY_BUTTON); forgetButton = setButton("找密码",Constants.FORGET_BUTTON); setSignButton = setButton("换签名", Constants.SIGN_BUTTON); registerDialog.setSize(159,150); registerDialog.add(new JLabel("账号")); registerDialog.add(account); registerDialog.add(new JLabel("密码")); registerDialog.add(passward); registerDialog.add(confirmButton); registerDialog.add(applyButton); registerDialog.add(forgetButton); registerDialog.add(setSignButton); } @Override public int reverseX(int x){ return 7-x; } public WebPanel(JLabel hint, String IP, int port){ shengwangShop = new ShengwangShop(this); moneyShop = new MoneyShop(this); type = PanelType.Web; textArea.setFont(Constants.LITTLE_BLACK); scrollPane = new JScrollPane(textArea); disconnectBut = setButtons("断开连接", DISCONNECT_BUTTON); this.playerHint = hint; init(); this.setFocusable(true); this.addMouseListener(this);//自行在构造器中添加! try { client = new Socket(IP, port); } catch (IOException e) { System.out.println("webPanel_Constructure_ck: 没有连接到服务器"); JOptionPane.showMessageDialog(null, "没有连接到服务器", "错误", JOptionPane.ERROR_MESSAGE); } sender = new Sender(client); receiver = new Receiver(client, this); yourEmoThread = new YourEmoThread(this); opponentEmoThread = new OpponentEmoThread(this); new Thread(yourEmoThread).start(); new Thread(opponentEmoThread).start(); new Thread(sender).start(); new Thread(receiver).start(); prepareButton = setButtons("准备", Constants.PREPARE_BUTTON); clorButton = setButtons("交换先后手", COLOR_BUTTON); this.emoButton = setButtons("发表情", Constants.YOUR_EMO); setBounds(0,0,Constants.PANEL_WEIGHT, Constants.FRAME_HEIGHT); textArea.setColumns(15); repaint(); setRegisterDialog(); } public WebPanel(JLabel hint) { this(hint, Constants.HOST, Constants.PORT); } @Override public void paint(Graphics g) { super.paint(g);//clear scrollPane.setBounds(540,350,205,240); add(scrollPane); this.setBounds(0, 0, Constants.PANEL_WEIGHT, Constants.FRAME_HEIGHT); // g.drawImage(Toolkit.getDefaultToolkit().getImage(ImagePath.BACKGROUND), // 0, 0, BOARD_WEIGHT, BOARD_HEIGHT, this);
g.drawImage(Toolkit.getDefaultToolkit().getImage(ImagePath.BACKGROUND),
9
2023-12-01 02:33:32+00:00
16k
tuxiaobei-scu/Draw-and-guess
entry/src/main/java/com/tuxiaobei/drawandguess/slice/MainAbilitySlice.java
[ { "identifier": "MainAbility", "path": "entry/src/main/java/com/tuxiaobei/drawandguess/MainAbility.java", "snippet": "public class MainAbility extends Ability {\n @Override\n public void onStart(Intent intent) {\n super.onStart(intent);\n super.setMainRoute(MainAbilitySlice.class.get...
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT; import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC; import com.tuxiaobei.drawandguess.MainAbility; import com.tuxiaobei.drawandguess.ResourceTable; import com.tuxiaobei.drawandguess.bean.AnswerItem; import com.tuxiaobei.drawandguess.bean.MyPoint; import com.tuxiaobei.drawandguess.component.ChangeName; import com.tuxiaobei.drawandguess.component.DeviceSelectDialog; import com.tuxiaobei.drawandguess.component.DrawPoint; import com.tuxiaobei.drawandguess.component.WordSelectDialog; import com.tuxiaobei.drawandguess.game.Guesser; import com.tuxiaobei.drawandguess.game.MainGame; import com.tuxiaobei.drawandguess.provider.AnswerItemProvider; import com.tuxiaobei.drawandguess.util.GsonUtil; import com.tuxiaobei.drawandguess.util.LogUtils; import com.tuxiaobei.drawandguess.util.Tools; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.aafwk.content.Operation; import ohos.agp.components.*; import ohos.bundle.IBundleManager; import ohos.data.distributed.common.*; import ohos.data.distributed.user.SingleKvStore; import ohos.global.resource.NotExistException; import ohos.global.resource.WrongTypeException; import java.io.IOException; import java.util.ArrayList; import java.util.List;
11,242
} if (findComponentById(ResourceTable.Id_title) instanceof Text) { title = (Text) findComponentById(ResourceTable.Id_title); } if (findComponentById(ResourceTable.Id_back) instanceof Button) { back = (Button) findComponentById(ResourceTable.Id_back); } if (findComponentById(ResourceTable.Id_ans) instanceof TextField) { ans = (TextField) findComponentById(ResourceTable.Id_ans); } if (findComponentById(ResourceTable.Id_submit) instanceof Button) { submit = (Button) findComponentById(ResourceTable.Id_submit); } if (findComponentById(ResourceTable.Id_tip) instanceof Text) { tip = (Text) findComponentById(ResourceTable.Id_tip); } if (findComponentById(ResourceTable.Id_list_answers) instanceof ListContainer) { ans_list = (ListContainer) findComponentById(ResourceTable.Id_list_answers); } if (findComponentById(ResourceTable.Id_show_score) instanceof Text) { show_score = (Text) findComponentById(ResourceTable.Id_show_score); } if (isLocal) { if (findComponentById(ResourceTable.Id_red) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_red)); } if (findComponentById(ResourceTable.Id_green) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_green)); } if (findComponentById(ResourceTable.Id_blue) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_blue)); } if (findComponentById(ResourceTable.Id_yellow) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_yellow)); } if (findComponentById(ResourceTable.Id_pink) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_pink)); } if (findComponentById(ResourceTable.Id_cyan) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_cyan)); } if (findComponentById(ResourceTable.Id_black) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_black)); } ans.setVisibility(Component.HIDE); submit.setVisibility(Component.HIDE); } else { back.setVisibility(Component.HIDE); play.setVisibility(Component.HIDE); show_score.setVisibility(Component.VISIBLE); change_name.setVisibility(Component.VISIBLE); guesser = new Guesser(submit, ans, tip, show_score, this); } transform.setClickedListener(component -> { DeviceSelectDialog dialog = new DeviceSelectDialog(MainAbilitySlice.this); dialog.setListener(deviceIds -> { if (deviceIds != null && !deviceIds.isEmpty()) { // 启动远程页面 startRemoteFas(deviceIds); // 同步远程数据库 pointsSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); ansSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); nameSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); } dialog.hide(); }); dialog.show(); }); play.setClickedListener(component -> { WordSelectDialog dialog = new WordSelectDialog(MainAbilitySlice.this, main_game.getWords()); dialog.setListener(word -> { if (!word.isEmpty()) { newGame(word); } dialog.hide(); }); dialog.show(); }); change_name.setClickedListener(component -> { ChangeName dialog = new ChangeName(MainAbilitySlice.this, local_name); dialog.setListener(name -> { if (!name.isEmpty()) { setName(name); } dialog.hide(); }); dialog.show(); }); } /** * Initialize art boards * * @param intent Intent */ private void initDraw(Intent intent) { boolean isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); //int colorIndex = switchcolor.getColorIndex(); drawl.setWidth(MATCH_PARENT); drawl.setWidth(MATCH_PARENT); canvas.addComponent(drawl); drawPoints(); drawl.setOnDrawBack(points -> { if (points != null && points.size() > 1) { String pointsString = GsonUtil.objectToString(points); LogUtils.info(TAG, "pointsString::" + pointsString); if (pointsSingleKvStore != null) { pointsSingleKvStore.putString(POINTS_KEY, pointsString); } } }); back.setClickedListener(component -> {
/* * Copyright (c) 2021 Huawei Device 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 com.tuxiaobei.drawandguess.slice; /** * MainAbilitySlice * * @since 2021-04-06 */ public class MainAbilitySlice extends AbilitySlice { private static final String TAG = MainAbilitySlice.class.getName(); private static final int PERMISSION_CODE = 20201203; private static final int DELAY_TIME = 10; private static final String STORE_ID_KEY = "storeId"; private static final String POINTS_KEY = "points"; private static final String ANS_KEY = "ans"; private static final String COLOR_INDEX_KEY = "colorIndex"; private static final String IS_FORM_LOCAL_KEY = "isFormLocal"; private static String storeId; private DependentLayout canvas; private Image transform; private Image change_name; private KvManager kvManager; private SingleKvStore pointsSingleKvStore; private SingleKvStore ansSingleKvStore; private SingleKvStore nameSingleKvStore; private Text title; private DrawPoint drawl; private Image play; private Button back; private Text show_score; private Guesser guesser; private Text tip; private Button submit; private TextField ans; private MainGame main_game; private ListContainer ans_list; private final List<AnswerItem> ansData = new ArrayList<>(); private AnswerItemProvider answerItemProvider; private String deviceId; private String local_name; private boolean isLocal; @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); storeId = STORE_ID_KEY + Tools.getRandom(); isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); drawl = new DrawPoint(this, isLocal); findComponentById(isLocal); requestPermission(); initView(intent); initDatabase(); if (isLocal) { nameSingleKvStore.putString(Tools.getDeviceId(this), "系统"); } initDraw(intent); ohos.global.resource.ResourceManager resManager = getResourceManager(); String[] words = null; try { words = resManager.getElement(ResourceTable.Strarray_words).getStringArray(); } catch (IOException e) { e.printStackTrace(); } catch (NotExistException e) { e.printStackTrace(); } catch (WrongTypeException e) { e.printStackTrace(); } main_game = new MainGame(this, words); initListContainer(); } private void initListContainer() { answerItemProvider = new AnswerItemProvider(ansData, this, isLocal); ans_list.setItemProvider(answerItemProvider); } private void initView(Intent intent) { if (!isLocal) { local_name = Tools.getDeviceId(this).substring(0, 6); storeId = intent.getStringParam(STORE_ID_KEY); } title.setText(isLocal ? "本地端" : local_name); transform.setVisibility(isLocal ? Component.VISIBLE : Component.INVISIBLE); } private void requestPermission() { if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) { if (canRequestPermission(DISTRIBUTED_DATASYNC)) { requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC}, PERMISSION_CODE); } } } private void findComponentById(Boolean isLocal) { if (findComponentById(ResourceTable.Id_canvas) instanceof DependentLayout) { canvas = (DependentLayout) findComponentById(ResourceTable.Id_canvas); } if (findComponentById(ResourceTable.Id_transform) instanceof Image) { transform = (Image) findComponentById(ResourceTable.Id_transform); } if (findComponentById(ResourceTable.Id_change_name) instanceof Image) { change_name = (Image) findComponentById(ResourceTable.Id_change_name); } if (findComponentById(ResourceTable.Id_play) instanceof Image) { play = (Image) findComponentById(ResourceTable.Id_play); } if (findComponentById(ResourceTable.Id_title) instanceof Text) { title = (Text) findComponentById(ResourceTable.Id_title); } if (findComponentById(ResourceTable.Id_back) instanceof Button) { back = (Button) findComponentById(ResourceTable.Id_back); } if (findComponentById(ResourceTable.Id_ans) instanceof TextField) { ans = (TextField) findComponentById(ResourceTable.Id_ans); } if (findComponentById(ResourceTable.Id_submit) instanceof Button) { submit = (Button) findComponentById(ResourceTable.Id_submit); } if (findComponentById(ResourceTable.Id_tip) instanceof Text) { tip = (Text) findComponentById(ResourceTable.Id_tip); } if (findComponentById(ResourceTable.Id_list_answers) instanceof ListContainer) { ans_list = (ListContainer) findComponentById(ResourceTable.Id_list_answers); } if (findComponentById(ResourceTable.Id_show_score) instanceof Text) { show_score = (Text) findComponentById(ResourceTable.Id_show_score); } if (isLocal) { if (findComponentById(ResourceTable.Id_red) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_red)); } if (findComponentById(ResourceTable.Id_green) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_green)); } if (findComponentById(ResourceTable.Id_blue) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_blue)); } if (findComponentById(ResourceTable.Id_yellow) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_yellow)); } if (findComponentById(ResourceTable.Id_pink) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_pink)); } if (findComponentById(ResourceTable.Id_cyan) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_cyan)); } if (findComponentById(ResourceTable.Id_black) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_black)); } ans.setVisibility(Component.HIDE); submit.setVisibility(Component.HIDE); } else { back.setVisibility(Component.HIDE); play.setVisibility(Component.HIDE); show_score.setVisibility(Component.VISIBLE); change_name.setVisibility(Component.VISIBLE); guesser = new Guesser(submit, ans, tip, show_score, this); } transform.setClickedListener(component -> { DeviceSelectDialog dialog = new DeviceSelectDialog(MainAbilitySlice.this); dialog.setListener(deviceIds -> { if (deviceIds != null && !deviceIds.isEmpty()) { // 启动远程页面 startRemoteFas(deviceIds); // 同步远程数据库 pointsSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); ansSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); nameSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); } dialog.hide(); }); dialog.show(); }); play.setClickedListener(component -> { WordSelectDialog dialog = new WordSelectDialog(MainAbilitySlice.this, main_game.getWords()); dialog.setListener(word -> { if (!word.isEmpty()) { newGame(word); } dialog.hide(); }); dialog.show(); }); change_name.setClickedListener(component -> { ChangeName dialog = new ChangeName(MainAbilitySlice.this, local_name); dialog.setListener(name -> { if (!name.isEmpty()) { setName(name); } dialog.hide(); }); dialog.show(); }); } /** * Initialize art boards * * @param intent Intent */ private void initDraw(Intent intent) { boolean isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); //int colorIndex = switchcolor.getColorIndex(); drawl.setWidth(MATCH_PARENT); drawl.setWidth(MATCH_PARENT); canvas.addComponent(drawl); drawPoints(); drawl.setOnDrawBack(points -> { if (points != null && points.size() > 1) { String pointsString = GsonUtil.objectToString(points); LogUtils.info(TAG, "pointsString::" + pointsString); if (pointsSingleKvStore != null) { pointsSingleKvStore.putString(POINTS_KEY, pointsString); } } }); back.setClickedListener(component -> {
List<MyPoint> points = drawl.getPoints();
3
2023-12-03 13:36:00+00:00
16k
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;
13,166
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;
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();
5
2023-11-27 18:25:00+00:00
16k
andre111/voxedit
src/client/java/me/andre111/voxedit/client/VoxEditClient.java
[ { "identifier": "Presets", "path": "src/main/java/me/andre111/voxedit/Presets.java", "snippet": "public class Presets {\n\tpublic static final ToolItem.Data andre111;\n\tpublic static final ItemStack andre111Stack;\n\tstatic {\n\t\tandre111 = new ToolItem.Data(Util.make(new ArrayList<>(), list -> {\n\t\...
import org.lwjgl.glfw.GLFW; import org.spongepowered.include.com.google.common.base.Objects; import me.andre111.voxedit.Presets; import me.andre111.voxedit.VoxEdit; import me.andre111.voxedit.client.gui.screen.ToolSelectionScreen; import me.andre111.voxedit.client.network.ClientNetworking; import me.andre111.voxedit.client.renderer.EditorRenderer; import me.andre111.voxedit.client.renderer.HudRenderer; import me.andre111.voxedit.client.renderer.SelectionRenderer; import me.andre111.voxedit.client.renderer.ToolRenderer; import me.andre111.voxedit.item.ToolItem; import me.andre111.voxedit.item.VoxEditItem; import me.andre111.voxedit.network.Command; import me.andre111.voxedit.tool.ConfiguredTool; import me.andre111.voxedit.tool.Tool; import me.andre111.voxedit.tool.config.ToolConfig; import me.andre111.voxedit.tool.data.Selection; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; import net.fabricmc.fabric.api.client.rendering.v1.BuiltinItemRendererRegistry; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.fabricmc.fabric.api.event.client.player.ClientPreAttackCallback; import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.text.Text; import net.minecraft.util.hit.BlockHitResult;
11,637
/* * Copyright (c) 2023 André Schweiger * * 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 me.andre111.voxedit.client; @Environment(value=EnvType.CLIENT) public class VoxEditClient implements ClientModInitializer { public static final KeyBinding INCREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_UP, "key.category.voxedit")); public static final KeyBinding DECREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_DOWN, "key.category.voxedit")); public static final KeyBinding INCREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_ADD, "key.category.voxedit")); public static final KeyBinding DECREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_SUBTRACT, "key.category.voxedit")); public static final KeyBinding UNDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.undo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Z, "key.category.voxedit")); public static final KeyBinding REDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.redo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Y, "key.category.voxedit")); public static final KeyBinding OPEN_MENU = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.openMenu", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "key.category.voxedit")); public static int retargetCooldown; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void onInitializeClient() { ClientNetworking.init(); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_TOOL, ToolRenderer.INSTANCE); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_EDITOR, EditorRenderer.INSTANCE); HudRenderer.init(); ItemGroupEvents.MODIFY_ENTRIES_ALL.register((group, entries) -> { if(group.getType() == ItemGroup.Type.CATEGORY && entries.shouldShowOpRestrictedItems()) { boolean hasCB = entries.getDisplayStacks().stream().filter(stack -> stack.getItem() == Items.COMMAND_BLOCK).findAny().isPresent(); if(hasCB) { for(Tool<?, ?> tool : VoxEdit.TOOL_REGISTRY) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(tool.getDefault())); for(ToolConfig config : tool.getAdditionalCreativeMenuConfigs()) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(new ConfiguredTool(tool, config))); } } entries.add(Presets.andre111Stack); entries.add(VoxEdit.ITEM_EDITOR.getDefaultStack()); } } }); ClientTickEvents.START_CLIENT_TICK.register((mc) -> { if(mc.world != null && mc.player != null) tick(); }); WorldRenderEvents.LAST.register((context) -> { render(context.matrixStack(), context.tickDelta()); }); ClientPreAttackCallback.EVENT.register((client, player, clickCount) -> { ItemStack stack = player.getMainHandStack(); if(stack.getItem() instanceof VoxEditItem) { if(player.isCreative() && MinecraftClient.getInstance().attackCooldown <= 0) { MinecraftClient.getInstance().attackCooldown = 5; ClientNetworking.sendCommand(Command.LEFT_CLICK); } return true; } return false; }); } public static void tick() { if(retargetCooldown > 0) retargetCooldown--; ClientState.player = MinecraftClient.getInstance().player;
/* * Copyright (c) 2023 André Schweiger * * 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 me.andre111.voxedit.client; @Environment(value=EnvType.CLIENT) public class VoxEditClient implements ClientModInitializer { public static final KeyBinding INCREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_UP, "key.category.voxedit")); public static final KeyBinding DECREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_DOWN, "key.category.voxedit")); public static final KeyBinding INCREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_ADD, "key.category.voxedit")); public static final KeyBinding DECREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_SUBTRACT, "key.category.voxedit")); public static final KeyBinding UNDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.undo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Z, "key.category.voxedit")); public static final KeyBinding REDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.redo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Y, "key.category.voxedit")); public static final KeyBinding OPEN_MENU = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.openMenu", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "key.category.voxedit")); public static int retargetCooldown; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void onInitializeClient() { ClientNetworking.init(); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_TOOL, ToolRenderer.INSTANCE); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_EDITOR, EditorRenderer.INSTANCE); HudRenderer.init(); ItemGroupEvents.MODIFY_ENTRIES_ALL.register((group, entries) -> { if(group.getType() == ItemGroup.Type.CATEGORY && entries.shouldShowOpRestrictedItems()) { boolean hasCB = entries.getDisplayStacks().stream().filter(stack -> stack.getItem() == Items.COMMAND_BLOCK).findAny().isPresent(); if(hasCB) { for(Tool<?, ?> tool : VoxEdit.TOOL_REGISTRY) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(tool.getDefault())); for(ToolConfig config : tool.getAdditionalCreativeMenuConfigs()) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(new ConfiguredTool(tool, config))); } } entries.add(Presets.andre111Stack); entries.add(VoxEdit.ITEM_EDITOR.getDefaultStack()); } } }); ClientTickEvents.START_CLIENT_TICK.register((mc) -> { if(mc.world != null && mc.player != null) tick(); }); WorldRenderEvents.LAST.register((context) -> { render(context.matrixStack(), context.tickDelta()); }); ClientPreAttackCallback.EVENT.register((client, player, clickCount) -> { ItemStack stack = player.getMainHandStack(); if(stack.getItem() instanceof VoxEditItem) { if(player.isCreative() && MinecraftClient.getInstance().attackCooldown <= 0) { MinecraftClient.getInstance().attackCooldown = 5; ClientNetworking.sendCommand(Command.LEFT_CLICK); } return true; } return false; }); } public static void tick() { if(retargetCooldown > 0) retargetCooldown--; ClientState.player = MinecraftClient.getInstance().player;
ToolItem.Data oldActive = ClientState.active;
8
2023-12-01 15:12:26+00:00
16k
bioastroiner/Minetweaker-Gregtech6-Addon
src/main/java/mods/bio/gttweaker/core/GTTweaker.java
[ { "identifier": "IMaterial", "path": "src/main/java/mods/bio/gttweaker/api/mods/gregtech/oredict/IMaterial.java", "snippet": "@ZenClass(\"mods.gregtech.oredict.IMaterial\")\npublic interface IMaterial {\n\tOreDictMaterial getMaterial();\n\n\t@ZenOperator(OperatorType.MUL)\n\tIMaterialStack multiply(long...
import cpw.mods.fml.common.event.FMLInitializationEvent; import gregapi.recipes.Recipe; import minetweaker.MineTweakerAPI; import minetweaker.MineTweakerImplementationAPI; import minetweaker.api.item.IIngredient; import minetweaker.util.IEventHandler; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterial; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialData; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialStack; import mods.bio.gttweaker.api.mods.gregtech.oredict.IPrefix; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipe; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipeFactory; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipeMap; import mods.bio.gttweaker.core.command.GTCommand; import mods.bio.gttweaker.core.json.OreDictMaterial_Serializable; import mods.bio.gttweaker.mods.gregtech.oredict.*; import mods.bio.gttweaker.mods.gregtech.recipe.CTRecipe; import mods.bio.gttweaker.mods.gregtech.recipe.CTRecipeMaps; import mods.bio.gttweaker.mods.gregtech.oredict.bracket.CTMaterialBracketHandler; import mods.bio.gttweaker.mods.gregtech.oredict.bracket.CTPrefixBracketHandler; import mods.bio.gttweaker.mods.gregtech.recipe.bracket.CTRecipeMapBracketHandler; import mods.bio.gttweaker.mods.minetweaker.CTIItemStackExpansion; import mods.bio.gttweaker.mods.minetweaker.CTILiquidStackExpansion; import mods.bio.gttweaker.mods.minetweaker.CTIOreDictExpansion; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import java.util.Objects;
11,204
package mods.bio.gttweaker.core; @cpw.mods.fml.common.Mod(modid = GTTweaker.MOD_ID, name = GTTweaker.MOD_NAME, version = GTTweaker.VERSION) public final class GTTweaker extends gregapi.api.Abstract_Mod { // https://github.com/GTNewHorizons/Minetweaker-Gregtech-5-Addon/blob/master/src/main/java/gttweaker/GTTweaker.java public static final String MOD_ID = "GRADLETOKEN_MODID"; public static final String MOD_NAME = "GRADLETOKEN_MODNAME"; public static final String VERSION = "GRADLETOKEN_VERSION"; public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; public static gregapi.code.ModData MOD_DATA = new gregapi.code.ModData(MOD_ID, MOD_NAME); //@cpw.mods.fml.common.SidedProxy(modId = MOD_ID, clientSide = "gregapi.api.example.Example_Proxy_Client", serverSide = "gregapi.api.example.Example_Proxy_Server") public static gregapi.api.Abstract_Proxy PROXY; public static String FORMAT_RECIPE_MAP(Recipe.RecipeMap map){ String[] tmp = map.toString().split("\\."); return tmp[tmp.length-1]; } public static Recipe.RecipeMap FORMAT_RECIPE_MAP(String name){ Recipe.RecipeMap out = null; if(Recipe.RecipeMap.RECIPE_MAPS.containsKey(name)){ out = Recipe.RecipeMap.RECIPE_MAPS.get(name); } if(out == null) for (Recipe.RecipeMap map: Recipe.RecipeMap.RECIPE_MAP_LIST) { String[] tmp = map.toString().split("\\."); String sName = tmp[tmp.length-1]; if(Objects.equals(sName.toLowerCase(),name.toLowerCase())){ out = map; } } if(out!=null){ return out; } else { MineTweakerAPI.logError(name + " is not a valid recipemap name!"); } return out; } public GTTweaker() { } @Override public String getModID() { return MOD_ID; } @Override public String getModName() { return MOD_NAME; } @Override public String getModNameForLog() { return "GTTWEAKER"; } @Override public gregapi.api.Abstract_Proxy getProxy() { return PROXY; } // Do not change these 7 Functions. Just keep them this way. @cpw.mods.fml.common.Mod.EventHandler public final void onPreLoad(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { onModPreInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onLoad(cpw.mods.fml.common.event.FMLInitializationEvent aEvent) { onModInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onPostLoad(cpw.mods.fml.common.event.FMLPostInitializationEvent aEvent) { onModPostInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarting(cpw.mods.fml.common.event.FMLServerStartingEvent aEvent) { onModServerStarting(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarted(cpw.mods.fml.common.event.FMLServerStartedEvent aEvent) { onModServerStarted(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopping(cpw.mods.fml.common.event.FMLServerStoppingEvent aEvent) { onModServerStopping(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopped(cpw.mods.fml.common.event.FMLServerStoppedEvent aEvent) { onModServerStopped(aEvent); } @Override public void onModPreInit2(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { } @Override public void onModInit2(FMLInitializationEvent aEvent) {
package mods.bio.gttweaker.core; @cpw.mods.fml.common.Mod(modid = GTTweaker.MOD_ID, name = GTTweaker.MOD_NAME, version = GTTweaker.VERSION) public final class GTTweaker extends gregapi.api.Abstract_Mod { // https://github.com/GTNewHorizons/Minetweaker-Gregtech-5-Addon/blob/master/src/main/java/gttweaker/GTTweaker.java public static final String MOD_ID = "GRADLETOKEN_MODID"; public static final String MOD_NAME = "GRADLETOKEN_MODNAME"; public static final String VERSION = "GRADLETOKEN_VERSION"; public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; public static gregapi.code.ModData MOD_DATA = new gregapi.code.ModData(MOD_ID, MOD_NAME); //@cpw.mods.fml.common.SidedProxy(modId = MOD_ID, clientSide = "gregapi.api.example.Example_Proxy_Client", serverSide = "gregapi.api.example.Example_Proxy_Server") public static gregapi.api.Abstract_Proxy PROXY; public static String FORMAT_RECIPE_MAP(Recipe.RecipeMap map){ String[] tmp = map.toString().split("\\."); return tmp[tmp.length-1]; } public static Recipe.RecipeMap FORMAT_RECIPE_MAP(String name){ Recipe.RecipeMap out = null; if(Recipe.RecipeMap.RECIPE_MAPS.containsKey(name)){ out = Recipe.RecipeMap.RECIPE_MAPS.get(name); } if(out == null) for (Recipe.RecipeMap map: Recipe.RecipeMap.RECIPE_MAP_LIST) { String[] tmp = map.toString().split("\\."); String sName = tmp[tmp.length-1]; if(Objects.equals(sName.toLowerCase(),name.toLowerCase())){ out = map; } } if(out!=null){ return out; } else { MineTweakerAPI.logError(name + " is not a valid recipemap name!"); } return out; } public GTTweaker() { } @Override public String getModID() { return MOD_ID; } @Override public String getModName() { return MOD_NAME; } @Override public String getModNameForLog() { return "GTTWEAKER"; } @Override public gregapi.api.Abstract_Proxy getProxy() { return PROXY; } // Do not change these 7 Functions. Just keep them this way. @cpw.mods.fml.common.Mod.EventHandler public final void onPreLoad(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { onModPreInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onLoad(cpw.mods.fml.common.event.FMLInitializationEvent aEvent) { onModInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onPostLoad(cpw.mods.fml.common.event.FMLPostInitializationEvent aEvent) { onModPostInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarting(cpw.mods.fml.common.event.FMLServerStartingEvent aEvent) { onModServerStarting(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarted(cpw.mods.fml.common.event.FMLServerStartedEvent aEvent) { onModServerStarted(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopping(cpw.mods.fml.common.event.FMLServerStoppingEvent aEvent) { onModServerStopping(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopped(cpw.mods.fml.common.event.FMLServerStoppedEvent aEvent) { onModServerStopped(aEvent); } @Override public void onModPreInit2(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { } @Override public void onModInit2(FMLInitializationEvent aEvent) {
OreDictMaterial_Serializable._INITLIZE();
8
2023-12-03 11:55:49+00:00
16k
tuxiaobei-scu/SCU-CCSOJ-Backend
DataBackup/src/main/java/top/hcode/hoj/judge/Dispatcher.java
[ { "identifier": "CommonResult", "path": "DataBackup/src/main/java/top/hcode/hoj/common/result/CommonResult.java", "snippet": "@Data\npublic class CommonResult<T>{\n\n private final Integer status; // 状态码\n\n private final T data; // 返回的数据\n\n private final String msg; // 自定义信息\n\n\n /...
import cn.hutool.core.lang.UUID; import cn.hutool.json.JSONObject; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; import top.hcode.hoj.common.result.CommonResult; import top.hcode.hoj.common.result.ResultStatus; import top.hcode.hoj.dao.judge.JudgeEntityService; import top.hcode.hoj.dao.judge.JudgeServerEntityService; import top.hcode.hoj.dao.judge.impl.RemoteJudgeAccountEntityServiceImpl; import top.hcode.hoj.pojo.dto.CompileDTO; import top.hcode.hoj.pojo.dto.TestJudgeReq; import top.hcode.hoj.pojo.dto.TestJudgeRes; import top.hcode.hoj.pojo.dto.ToJudgeDTO; import top.hcode.hoj.pojo.entity.judge.Judge; import top.hcode.hoj.pojo.entity.judge.JudgeServer; import top.hcode.hoj.pojo.entity.judge.RemoteJudgeAccount; import top.hcode.hoj.utils.Constants; import top.hcode.hoj.utils.RedisUtils; import java.util.Map; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger;
11,851
package top.hcode.hoj.judge; /** * @Author: Himit_ZH * @Date: 2021/4/15 17:29 * @Description: */ @Component @Slf4j(topic = "hoj") public class Dispatcher { @Autowired private RestTemplate restTemplate; @Autowired private JudgeServerEntityService judgeServerEntityService; @Autowired private JudgeEntityService judgeEntityService; @Autowired private ChooseUtils chooseUtils; @Autowired private RedisUtils redisUtils; private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(20); private final static Map<String, Future> futureTaskMap = new ConcurrentHashMap<>(20); @Autowired private RemoteJudgeAccountEntityServiceImpl remoteJudgeAccountService; @Value("${judger-host}") private String judgerHost; @Value("${judger-post}") private String judgerPost; public CommonResult dispatcherJudge(String type, String path, Object data) { switch (type) { case "judge": ToJudgeDTO judgeData = (ToJudgeDTO) data; toJudge(path, judgeData, judgeData.getJudge().getSubmitId(), judgeData.getRemoteJudgeProblem() != null); break; case "compile": CompileDTO compileDTO = (CompileDTO) data; return toCompile(path, compileDTO); default: throw new IllegalArgumentException("判题机不支持此调用类型"); } return null; } public void dispatcherTestJudge(TestJudgeReq testJudgeReq, String path) { AtomicInteger count = new AtomicInteger(0); String key = testJudgeReq.getUniqueKey(); Runnable getResultTask = () -> { if (count.get() > 300) { // 300次失败则判为提交失败 Future future = futureTaskMap.get(key); if (future != null) { boolean isCanceled = future.cancel(true); if (isCanceled) { futureTaskMap.remove(key); } } return; } count.getAndIncrement(); JudgeServer judgeServer = chooseUtils.chooseServer(false); if (judgeServer != null) { // 获取到判题机资源 try { JSONObject resultJson = restTemplate.postForObject("http://" + judgerHost + ":" + judgerPost + path, testJudgeReq, JSONObject.class); if (resultJson != null) { if (resultJson.getInt("status") == ResultStatus.SUCCESS.getStatus()) { TestJudgeRes testJudgeRes = resultJson.getBean("data", TestJudgeRes.class); testJudgeRes.setInput(testJudgeReq.getTestCaseInput()); testJudgeRes.setExpectedOutput(testJudgeReq.getExpectedOutput()); testJudgeRes.setProblemJudgeMode(testJudgeReq.getProblemJudgeMode()); redisUtils.set(testJudgeReq.getUniqueKey(), testJudgeRes, 60); } else { TestJudgeRes testJudgeRes = TestJudgeRes.builder()
package top.hcode.hoj.judge; /** * @Author: Himit_ZH * @Date: 2021/4/15 17:29 * @Description: */ @Component @Slf4j(topic = "hoj") public class Dispatcher { @Autowired private RestTemplate restTemplate; @Autowired private JudgeServerEntityService judgeServerEntityService; @Autowired private JudgeEntityService judgeEntityService; @Autowired private ChooseUtils chooseUtils; @Autowired private RedisUtils redisUtils; private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(20); private final static Map<String, Future> futureTaskMap = new ConcurrentHashMap<>(20); @Autowired private RemoteJudgeAccountEntityServiceImpl remoteJudgeAccountService; @Value("${judger-host}") private String judgerHost; @Value("${judger-post}") private String judgerPost; public CommonResult dispatcherJudge(String type, String path, Object data) { switch (type) { case "judge": ToJudgeDTO judgeData = (ToJudgeDTO) data; toJudge(path, judgeData, judgeData.getJudge().getSubmitId(), judgeData.getRemoteJudgeProblem() != null); break; case "compile": CompileDTO compileDTO = (CompileDTO) data; return toCompile(path, compileDTO); default: throw new IllegalArgumentException("判题机不支持此调用类型"); } return null; } public void dispatcherTestJudge(TestJudgeReq testJudgeReq, String path) { AtomicInteger count = new AtomicInteger(0); String key = testJudgeReq.getUniqueKey(); Runnable getResultTask = () -> { if (count.get() > 300) { // 300次失败则判为提交失败 Future future = futureTaskMap.get(key); if (future != null) { boolean isCanceled = future.cancel(true); if (isCanceled) { futureTaskMap.remove(key); } } return; } count.getAndIncrement(); JudgeServer judgeServer = chooseUtils.chooseServer(false); if (judgeServer != null) { // 获取到判题机资源 try { JSONObject resultJson = restTemplate.postForObject("http://" + judgerHost + ":" + judgerPost + path, testJudgeReq, JSONObject.class); if (resultJson != null) { if (resultJson.getInt("status") == ResultStatus.SUCCESS.getStatus()) { TestJudgeRes testJudgeRes = resultJson.getBean("data", TestJudgeRes.class); testJudgeRes.setInput(testJudgeReq.getTestCaseInput()); testJudgeRes.setExpectedOutput(testJudgeReq.getExpectedOutput()); testJudgeRes.setProblemJudgeMode(testJudgeReq.getProblemJudgeMode()); redisUtils.set(testJudgeReq.getUniqueKey(), testJudgeRes, 60); } else { TestJudgeRes testJudgeRes = TestJudgeRes.builder()
.status(Constants.Judge.STATUS_SYSTEM_ERROR.getStatus())
12
2023-12-03 14:15:51+00:00
16k
yichenhsiaonz/EscAIpe-room-final
src/main/java/nz/ac/auckland/se206/controllers/EndingController.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.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; 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.openai.ApiProxyException;
10,807
package nz.ac.auckland.se206.controllers; /** Controller class for the ending scene. */ public class EndingController { @FXML private AnchorPane contentPane; @FXML private ImageView shadowFrame; @FXML private TextArea textArea; @FXML private Button nextButton; @FXML private Button menuButton; @FXML private Label congratsMsg; @FXML private Label defeatedMsg; @FXML private Label youWinMsg; @FXML private Label wonMsg; @FXML private Label butMsg; @FXML private Label someoneMsg; private int chatCount = 0; /** * Initializes the ending scene, loading the initial text. * * @throws ApiProxyException if there is an error communicating with the API proxy */ public void initialize() throws ApiProxyException { // Initialization code goes here GameState.scaleToScreen(contentPane); textArea.appendText("You: Finally I've unlocked the exit! But, what is that?"); } /** * Loads the next text in the ending scene. * * @throws ApiProxyException if there is an error communicating with the API proxy */ @FXML private void onNextClicked() throws ApiProxyException { if (chatCount == 0) { // show neutral AI textArea.clear(); Image newImage = new Image("/images/Ending/neutral-frame.png"); shadowFrame.setImage(newImage); textArea.appendText("AI-23: " + GameState.endingCongrats);
package nz.ac.auckland.se206.controllers; /** Controller class for the ending scene. */ public class EndingController { @FXML private AnchorPane contentPane; @FXML private ImageView shadowFrame; @FXML private TextArea textArea; @FXML private Button nextButton; @FXML private Button menuButton; @FXML private Label congratsMsg; @FXML private Label defeatedMsg; @FXML private Label youWinMsg; @FXML private Label wonMsg; @FXML private Label butMsg; @FXML private Label someoneMsg; private int chatCount = 0; /** * Initializes the ending scene, loading the initial text. * * @throws ApiProxyException if there is an error communicating with the API proxy */ public void initialize() throws ApiProxyException { // Initialization code goes here GameState.scaleToScreen(contentPane); textArea.appendText("You: Finally I've unlocked the exit! But, what is that?"); } /** * Loads the next text in the ending scene. * * @throws ApiProxyException if there is an error communicating with the API proxy */ @FXML private void onNextClicked() throws ApiProxyException { if (chatCount == 0) { // show neutral AI textArea.clear(); Image newImage = new Image("/images/Ending/neutral-frame.png"); shadowFrame.setImage(newImage); textArea.appendText("AI-23: " + GameState.endingCongrats);
TextToSpeechManager.speak(GameState.endingCongrats);
3
2023-12-02 04:57:43+00:00
16k
nageoffer/shortlink
project/src/main/java/com/nageoffer/shortlink/project/service/impl/ShortLinkStatsServiceImpl.java
[ { "identifier": "LinkAccessLogsDO", "path": "project/src/main/java/com/nageoffer/shortlink/project/dao/entity/LinkAccessLogsDO.java", "snippet": "@Data\n@TableName(\"t_link_access_logs\")\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class LinkAccessLogsDO extends BaseDO {\n\n /**\n ...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.nageoffer.shortlink.project.dao.entity.LinkAccessLogsDO; import com.nageoffer.shortlink.project.dao.entity.LinkAccessStatsDO; 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.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.dto.req.ShortLinkGroupStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsReqDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessDailyRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessRecordRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsBrowserRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsDeviceRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsLocaleCNRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsNetworkRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsOsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsTopIpRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsUvRespDTO; import com.nageoffer.shortlink.project.service.ShortLinkStatsService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger;
12,052
.uv(0) .uip(0) .build(); daily.add(accessDailyRespDTO); })); // 地区访问详情(仅国内) List<ShortLinkStatsLocaleCNRespDTO> localeCnStats = new ArrayList<>(); List<LinkLocaleStatsDO> listedLocaleByShortLink = linkLocaleStatsMapper.listLocaleByShortLink(requestParam); int localeCnSum = listedLocaleByShortLink.stream() .mapToInt(LinkLocaleStatsDO::getCnt) .sum(); listedLocaleByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / localeCnSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsLocaleCNRespDTO localeCNRespDTO = ShortLinkStatsLocaleCNRespDTO.builder() .cnt(each.getCnt()) .locale(each.getProvince()) .ratio(actualRatio) .build(); localeCnStats.add(localeCNRespDTO); }); // 小时访问详情 List<Integer> hourStats = new ArrayList<>(); List<LinkAccessStatsDO> listHourStatsByShortLink = linkAccessStatsMapper.listHourStatsByShortLink(requestParam); for (int i = 0; i < 24; i++) { AtomicInteger hour = new AtomicInteger(i); int hourCnt = listHourStatsByShortLink.stream() .filter(each -> Objects.equals(each.getHour(), hour.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); hourStats.add(hourCnt); } // 高频访问IP详情 List<ShortLinkStatsTopIpRespDTO> topIpStats = new ArrayList<>(); List<HashMap<String, Object>> listTopIpByShortLink = linkAccessLogsMapper.listTopIpByShortLink(requestParam); listTopIpByShortLink.forEach(each -> { ShortLinkStatsTopIpRespDTO statsTopIpRespDTO = ShortLinkStatsTopIpRespDTO.builder() .ip(each.get("ip").toString()) .cnt(Integer.parseInt(each.get("count").toString())) .build(); topIpStats.add(statsTopIpRespDTO); }); // 一周访问详情 List<Integer> weekdayStats = new ArrayList<>(); List<LinkAccessStatsDO> listWeekdayStatsByShortLink = linkAccessStatsMapper.listWeekdayStatsByShortLink(requestParam); for (int i = 1; i < 8; i++) { AtomicInteger weekday = new AtomicInteger(i); int weekdayCnt = listWeekdayStatsByShortLink.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByShortLink = linkBrowserStatsMapper.listBrowserStatsByShortLink(requestParam); int browserSum = listBrowserStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByShortLink = linkOsStatsMapper.listOsStatsByShortLink(requestParam); int osSum = listOsStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访客访问类型详情 List<ShortLinkStatsUvRespDTO> uvTypeStats = new ArrayList<>(); HashMap<String, Object> findUvTypeByShortLink = linkAccessLogsMapper.findUvTypeCntByShortLink(requestParam); int oldUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("oldUserCnt")) .map(Object::toString) .orElse("0") ); int newUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("newUserCnt")) .map(Object::toString) .orElse("0") ); int uvSum = oldUserCnt + newUserCnt; double oldRatio = (double) oldUserCnt / uvSum; double actualOldRatio = Math.round(oldRatio * 100.0) / 100.0; double newRatio = (double) newUserCnt / uvSum; double actualNewRatio = Math.round(newRatio * 100.0) / 100.0; ShortLinkStatsUvRespDTO newUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("newUser") .cnt(newUserCnt) .ratio(actualNewRatio) .build(); uvTypeStats.add(newUvRespDTO); ShortLinkStatsUvRespDTO oldUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("oldUser") .cnt(oldUserCnt) .ratio(actualOldRatio) .build(); uvTypeStats.add(oldUvRespDTO); // 访问设备类型详情
/* * 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)获取项目资料 */ @Service @RequiredArgsConstructor public class ShortLinkStatsServiceImpl implements ShortLinkStatsService { private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper; private final LinkAccessLogsMapper linkAccessLogsMapper; private final LinkBrowserStatsMapper linkBrowserStatsMapper; private final LinkOsStatsMapper linkOsStatsMapper; private final LinkDeviceStatsMapper linkDeviceStatsMapper; private final LinkNetworkStatsMapper linkNetworkStatsMapper; @Override public ShortLinkStatsRespDTO oneShortLinkStats(ShortLinkStatsReqDTO requestParam) { List<LinkAccessStatsDO> listStatsByShortLink = linkAccessStatsMapper.listStatsByShortLink(requestParam); if (CollUtil.isEmpty(listStatsByShortLink)) { return null; } // 基础访问数据 LinkAccessStatsDO pvUvUidStatsByShortLink = linkAccessLogsMapper.findPvUvUidStatsByShortLink(requestParam); // 基础访问详情 List<ShortLinkStatsAccessDailyRespDTO> daily = new ArrayList<>(); List<String> rangeDates = DateUtil.rangeToList(DateUtil.parse(requestParam.getStartDate()), DateUtil.parse(requestParam.getEndDate()), DateField.DAY_OF_MONTH).stream() .map(DateUtil::formatDate) .toList(); rangeDates.forEach(each -> listStatsByShortLink.stream() .filter(item -> Objects.equals(each, DateUtil.formatDate(item.getDate()))) .findFirst() .ifPresentOrElse(item -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(item.getPv()) .uv(item.getUv()) .uip(item.getUip()) .build(); daily.add(accessDailyRespDTO); }, () -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(0) .uv(0) .uip(0) .build(); daily.add(accessDailyRespDTO); })); // 地区访问详情(仅国内) List<ShortLinkStatsLocaleCNRespDTO> localeCnStats = new ArrayList<>(); List<LinkLocaleStatsDO> listedLocaleByShortLink = linkLocaleStatsMapper.listLocaleByShortLink(requestParam); int localeCnSum = listedLocaleByShortLink.stream() .mapToInt(LinkLocaleStatsDO::getCnt) .sum(); listedLocaleByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / localeCnSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsLocaleCNRespDTO localeCNRespDTO = ShortLinkStatsLocaleCNRespDTO.builder() .cnt(each.getCnt()) .locale(each.getProvince()) .ratio(actualRatio) .build(); localeCnStats.add(localeCNRespDTO); }); // 小时访问详情 List<Integer> hourStats = new ArrayList<>(); List<LinkAccessStatsDO> listHourStatsByShortLink = linkAccessStatsMapper.listHourStatsByShortLink(requestParam); for (int i = 0; i < 24; i++) { AtomicInteger hour = new AtomicInteger(i); int hourCnt = listHourStatsByShortLink.stream() .filter(each -> Objects.equals(each.getHour(), hour.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); hourStats.add(hourCnt); } // 高频访问IP详情 List<ShortLinkStatsTopIpRespDTO> topIpStats = new ArrayList<>(); List<HashMap<String, Object>> listTopIpByShortLink = linkAccessLogsMapper.listTopIpByShortLink(requestParam); listTopIpByShortLink.forEach(each -> { ShortLinkStatsTopIpRespDTO statsTopIpRespDTO = ShortLinkStatsTopIpRespDTO.builder() .ip(each.get("ip").toString()) .cnt(Integer.parseInt(each.get("count").toString())) .build(); topIpStats.add(statsTopIpRespDTO); }); // 一周访问详情 List<Integer> weekdayStats = new ArrayList<>(); List<LinkAccessStatsDO> listWeekdayStatsByShortLink = linkAccessStatsMapper.listWeekdayStatsByShortLink(requestParam); for (int i = 1; i < 8; i++) { AtomicInteger weekday = new AtomicInteger(i); int weekdayCnt = listWeekdayStatsByShortLink.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByShortLink = linkBrowserStatsMapper.listBrowserStatsByShortLink(requestParam); int browserSum = listBrowserStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByShortLink = linkOsStatsMapper.listOsStatsByShortLink(requestParam); int osSum = listOsStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访客访问类型详情 List<ShortLinkStatsUvRespDTO> uvTypeStats = new ArrayList<>(); HashMap<String, Object> findUvTypeByShortLink = linkAccessLogsMapper.findUvTypeCntByShortLink(requestParam); int oldUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("oldUserCnt")) .map(Object::toString) .orElse("0") ); int newUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("newUserCnt")) .map(Object::toString) .orElse("0") ); int uvSum = oldUserCnt + newUserCnt; double oldRatio = (double) oldUserCnt / uvSum; double actualOldRatio = Math.round(oldRatio * 100.0) / 100.0; double newRatio = (double) newUserCnt / uvSum; double actualNewRatio = Math.round(newRatio * 100.0) / 100.0; ShortLinkStatsUvRespDTO newUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("newUser") .cnt(newUserCnt) .ratio(actualNewRatio) .build(); uvTypeStats.add(newUvRespDTO); ShortLinkStatsUvRespDTO oldUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("oldUser") .cnt(oldUserCnt) .ratio(actualOldRatio) .build(); uvTypeStats.add(oldUvRespDTO); // 访问设备类型详情
List<ShortLinkStatsDeviceRespDTO> deviceStats = new ArrayList<>();
19
2023-11-19 16:04:32+00:00
16k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/parser/ResultParser.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.model.compute.aggregation.bucket.Bucket; import com.ly.ckibana.model.compute.aggregation.bucket.BucketStatics; import com.ly.ckibana.model.compute.aggregation.bucket.BucketsResult; import com.ly.ckibana.model.compute.aggregation.bucket.FilterInnerBucket; import com.ly.ckibana.model.compute.aggregation.bucket.MathBucket; import com.ly.ckibana.model.compute.aggregation.bucket.PercentilesBucket; import com.ly.ckibana.model.compute.aggregation.bucket.PercentilesRankBucket; import com.ly.ckibana.model.compute.aggregation.bucket.RangeBucket; import com.ly.ckibana.model.enums.AggCategory; import com.ly.ckibana.model.enums.AggType; import com.ly.ckibana.model.enums.SortType; import com.ly.ckibana.model.enums.TermsAggOrderType; import com.ly.ckibana.model.response.Response; import com.ly.ckibana.strategy.aggs.Aggregation; import com.ly.ckibana.strategy.aggs.TermsAggStrategy; import com.ly.ckibana.util.JSONUtils; import org.apache.commons.collections4.CollectionUtils; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
11,496
otherDocCount = totalDocCount - showDocCount; } return otherDocCount; } /** * 从statics中获取当前agg对应的buckets,包括sub Buckets,peer Buckets. * * @param aggregation aggregation * @param bucketStatics 所有行数据,包含当前agg/subAgg,peerAgg数据 * @return buckets */ private List<Bucket> buildAggBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics) { String staticsId = aggregation.getStaticsId(); List<Bucket> result = new ArrayList<>(); //按照agg的bucketKey的值分类(如DateHistogramAggsStrategy的DateHistogramBucket的Key为时间)。需要LinkedHashMap保持先后顺序 Map<String, List<Map<String, BucketStatics>>> staticsByAggKeys = bucketStatics.stream().collect(Collectors.groupingBy(each -> each.get(staticsId).getBucketKey(), LinkedHashMap::new, Collectors.toList())); staticsByAggKeys.forEach((key, value) -> { //获取当前agg对应的基本bucket Bucket bucket = value.get(0).get(staticsId).getBucket(); //计算当前bucket对应的总docCount buildDocCount(aggregation, value, bucket); //内存计算。基于sub agg size计算sub buckets(如items top 10)的结果 buildSubAggsBuckets(aggregation, value, bucket); //针对第一层有兄弟节点 buildPeerAggsBuckets(aggregation, value, bucket); result.add(bucket); }); return result; } private void buildPeerAggsBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { if (CollectionUtils.isNotEmpty(aggregation.getPeerAggs())) { bucket.getComputeData().setPeerBucketMap(new HashMap<>()); aggregation.getPeerAggs().forEach(each -> { bucket.getComputeData().getPeerBucketMap().put(each.getAggName(), buildBucketsResult(each, bucketStatics)); }); } } private void buildSubAggsBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { if (CollectionUtils.isNotEmpty(aggregation.getSubAggs()) && !aggregation.isIgnoreSubAggCondition()) { bucket.getComputeData().setSubBucketMap(new HashMap<>()); aggregation.getSubAggs().forEach(each -> bucket.getComputeData().getSubBucketMap().put(each.getAggName(), buildBucketsResult(each, bucketStatics))); } } /** * 计算当前聚合的totalDocCount. * * @param aggregation aggregation * @param bucketStatics bucketStatics * @param bucket bucket */ private void buildDocCount(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { long totalDocCount = 0; for (Map<String, BucketStatics> each : bucketStatics) { totalDocCount = totalDocCount + each.get(aggregation.getStaticsId()).getBucket().getDocCount(); } bucket.setDocCount(totalDocCount); } /** * 对bucket结果数据增加排序处理-基于内存排序实现. * TermsAgg按照avg,max,min,sum等sub agg进行排序,或子查询为 DateHistogramAgg需要内存处理排序 * * @param aggregation aggregation * @param buckets buckets * @return buckets */ private List<Bucket> sortBuckets(Aggregation aggregation, List<Bucket> buckets) { List<Bucket> result; result = sortTermsAggBySubAgg(aggregation, buckets); result = sortChildDateHistogramAgg(aggregation, result); return result; } /** * TermsAgg按照avg,max,min,sum等sub agg进行排序. * * @param aggregation aggregation * @param buckets buckets * @return buckets */ private List<Bucket> sortTermsAggBySubAgg(Aggregation aggregation, List<Bucket> buckets) { List<Bucket> result = buckets; if (null == aggregation.getSubAggs() || !AggType.TERMS.equals(aggregation.getAggType())) { return result; } TermsAggStrategy termsAgg = (TermsAggStrategy) aggregation; if (TermsAggOrderType.METRIC_CUSTOM.equals(termsAgg.getOrderType())) { Aggregation subAgg = termsAgg.getSubAggs().get(termsAgg.getOrderBySubAggIndex()); if (!TermsAggOrderType.METRIC_CUSTOM.equals(termsAgg.getOrderType()) || !AggCategory.MATH.equals(subAgg.getAggCategory())) { return result; } String orderValue = termsAgg.getOrder().split(" ")[1]; result = buckets.stream().sorted((o1, o2) -> { BucketsResult s1 = o1.getComputeData().getSubBucketMap().get(subAgg.getAggName()); BucketsResult s2 = o2.getComputeData().getSubBucketMap().get(subAgg.getAggName()); //math类bucket只有一个bucket MathBucket m1 = (MathBucket) s1.getBuckets().get(0); MathBucket m2 = (MathBucket) s2.getBuckets().get(0); int compareValue = (int) (m1.getValue() - m2.getValue()); return orderValue.equalsIgnoreCase(SortType.ASC.name()) ? compareValue : (-compareValue); }).collect(Collectors.toList()); } return result; } /** * 子查询为 DateHistogramAgg需要内存处理排序. * * @param aggregation aggregation * @param buckets buckets * @return buckets */ private List<Bucket> sortChildDateHistogramAgg(Aggregation aggregation, List<Bucket> buckets) { List<Bucket> result = buckets;
/* * 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; /** * 从ck中解析聚合结果,转换为kibana需要的格式返回. * * @author quzhihao */ @Service public class ResultParser extends HitsResultParser { public static final String BUCKET_FIELD_COMPUTE_DATA = "computeData"; /** * 执行聚合请求,将ck数据转换为kibana需要的格式数据. * * @param aggregation aggregation * @param aggCkResult aggCkResult * @return Response */ public Response execute(Aggregation aggregation, List<JSONObject> aggCkResult) { Response result = new Response(); List<Bucket> buckets = computeBuckets(aggregation, aggCkResult); result.setAggregations(computeAggsResult(aggregation, buckets)); result.getHits().setTotal(buckets.stream().mapToLong(Bucket::getDocCount).sum()); return result; } private Map<String, Map<String, Object>> computeAggsResult(Aggregation aggregation, List<Bucket> buckets) { Map<String, Map<String, Object>> peerAggResult = new HashMap<>(); parseDeepAggData(aggregation, buckets, peerAggResult); Map<String, Map<String, Object>> aggsResult = formatResult(aggregation, buckets, 0); aggsResult.putAll(peerAggResult); return aggsResult; } /** * 将ck结果,经过处理,得到对应的buckets. * 1.内存计算主agg doc_count * 2.内存计算subAgg size * 3.内存计算排序by subAgg */ public List<Bucket> computeBuckets(Aggregation aggregation, List<JSONObject> ckResult) { //statics:每一行ck结果解析到的对应各个agg的bucket结果List<Map<聚合staticsId,BucketStatics{Bucket.key(),Bucket}> List<Map<String, BucketStatics>> statics = buildCkRowAndAggBucketMappingList(aggregation, ckResult); // 解析得到当前agg对应的buckets,包括subBuckets和peerBuckets return buildBucketsResult(aggregation, statics).getBuckets(); } private List<Map<String, BucketStatics>> buildCkRowAndAggBucketMappingList(Aggregation aggregation, List<JSONObject> ckResult) { List<Map<String, BucketStatics>> result = new ArrayList<>(); for (int i = 0; i < ckResult.size(); i++) { JSONObject obj = ckResult.get(i); result.add(buildCkRowAndAggsMapping(aggregation, obj)); } return result; } /** * statics:约定统计数据存放规则(key:每个depth的每个agg,value=bucket,count). */ private Map<String, BucketStatics> buildCkRowAndAggsMapping(Aggregation aggregation, JSONObject ckResult) { Map<String, BucketStatics> result = new HashMap<>(); if (CollectionUtils.isNotEmpty(aggregation.getSubAggs()) && !aggregation.isIgnoreSubAggCondition()) { aggregation.getSubAggs().forEach(each -> result.putAll(buildCkRowAndAggsMapping(each, ckResult))); } if (CollectionUtils.isNotEmpty(aggregation.getPeerAggs())) { aggregation.getPeerAggs().forEach(each -> result.putAll(buildCkRowAndAggsMapping(each, ckResult))); } result.put(aggregation.getStaticsId(), buildBucketStatics(aggregation, ckResult)); return result; } private BucketStatics buildBucketStatics(Aggregation aggregation, JSONObject ckResult) { Bucket bucket = aggregation.buildResultBucket(ckResult); return new BucketStatics(null == bucket.getKey() ? "unknownKey" : bucket.getKey().toString(), bucket); } private void parseDeepAggData(Aggregation aggregation, List<Bucket> buckets, Map<String, Map<String, Object>> peerAggDatas) { buckets.forEach(bucket -> { //注意目前仅第一层有peer agg if (CollectionUtils.isNotEmpty(aggregation.getPeerAggs())) { aggregation.getPeerAggs().forEach(each -> { BucketsResult bucketsResult = bucket.getComputeData().getPeerBucketMap().get(each.getAggName()); List<Bucket> tempBuckets = bucketsResult.getBuckets(); parseDeepAggData(each, tempBuckets, peerAggDatas); peerAggDatas.putAll(formatResult(each, tempBuckets, bucketsResult.getOtherDocCount())); }); } //任意层可能有child agg if (CollectionUtils.isNotEmpty(aggregation.getSubAggs())) { Map<String, Map<String, Object>> aggsData = new HashMap<>(); if (!aggregation.isIgnoreSubAggCondition()) { aggregation.getSubAggs().forEach(each -> { BucketsResult bucketsResult = bucket.getComputeData().getSubBucketMap().get(each.getAggName()); List<Bucket> tempBuckets = bucketsResult.getBuckets(); parseDeepAggData(each, tempBuckets, peerAggDatas); aggsData.putAll(formatResult(each, tempBuckets, bucketsResult.getOtherDocCount())); }); bucket.setComputeSubAggData(aggsData); } } }); } /** * 解析得到当前agg对应的buckets. * 1.内存计算后,内存处理排序和size截取 */ private BucketsResult buildBucketsResult(Aggregation aggsStrategy, List<Map<String, BucketStatics>> bucketStatics) { List<Bucket> currentBuckets = buildAggBuckets(aggsStrategy, bucketStatics); //内存处理排序和size截取 List<Bucket> sortedAndSizedBuckets = subSizeBuckets(aggsStrategy, sortBuckets(aggsStrategy, currentBuckets)); BucketsResult bucketsResult = new BucketsResult(sortedAndSizedBuckets); //构建返回结果:sum_other_doc_count,buckets bucketsResult.setOtherDocCount(buildOtherDocCountForTermAgg(aggsStrategy, currentBuckets, bucketsResult.getBuckets())); return bucketsResult; } /** * 内存截取size. * 由于需要整体内存计算后,才能得到排序后数据。因此需要内存处理size * * @param aggregation agg * @param currentBuckets currentBuckets * @return buckets */ private List<Bucket> subSizeBuckets(Aggregation aggregation, List<Bucket> currentBuckets) { List<Bucket> result = currentBuckets; if (aggregation.getSize() != null && aggregation.getSize() > 0) { result = currentBuckets.subList(0, Math.min(currentBuckets.size(), aggregation.getSize())); } return result; } /** * 为TermAgg补充otherDocCount. * * @param aggregation agg * @param currentBuckets currentBuckets * @param buckets buckets * @return otherDocCount */ private long buildOtherDocCountForTermAgg(Aggregation aggregation, List<Bucket> currentBuckets, List<Bucket> buckets) { long otherDocCount = 0; if (AggType.TERMS.equals(aggregation.getAggType())) { long totalDocCount = currentBuckets.stream().mapToLong(Bucket::getDocCount).sum(); long showDocCount = buckets.stream().mapToLong(Bucket::getDocCount).sum(); otherDocCount = totalDocCount - showDocCount; } return otherDocCount; } /** * 从statics中获取当前agg对应的buckets,包括sub Buckets,peer Buckets. * * @param aggregation aggregation * @param bucketStatics 所有行数据,包含当前agg/subAgg,peerAgg数据 * @return buckets */ private List<Bucket> buildAggBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics) { String staticsId = aggregation.getStaticsId(); List<Bucket> result = new ArrayList<>(); //按照agg的bucketKey的值分类(如DateHistogramAggsStrategy的DateHistogramBucket的Key为时间)。需要LinkedHashMap保持先后顺序 Map<String, List<Map<String, BucketStatics>>> staticsByAggKeys = bucketStatics.stream().collect(Collectors.groupingBy(each -> each.get(staticsId).getBucketKey(), LinkedHashMap::new, Collectors.toList())); staticsByAggKeys.forEach((key, value) -> { //获取当前agg对应的基本bucket Bucket bucket = value.get(0).get(staticsId).getBucket(); //计算当前bucket对应的总docCount buildDocCount(aggregation, value, bucket); //内存计算。基于sub agg size计算sub buckets(如items top 10)的结果 buildSubAggsBuckets(aggregation, value, bucket); //针对第一层有兄弟节点 buildPeerAggsBuckets(aggregation, value, bucket); result.add(bucket); }); return result; } private void buildPeerAggsBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { if (CollectionUtils.isNotEmpty(aggregation.getPeerAggs())) { bucket.getComputeData().setPeerBucketMap(new HashMap<>()); aggregation.getPeerAggs().forEach(each -> { bucket.getComputeData().getPeerBucketMap().put(each.getAggName(), buildBucketsResult(each, bucketStatics)); }); } } private void buildSubAggsBuckets(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { if (CollectionUtils.isNotEmpty(aggregation.getSubAggs()) && !aggregation.isIgnoreSubAggCondition()) { bucket.getComputeData().setSubBucketMap(new HashMap<>()); aggregation.getSubAggs().forEach(each -> bucket.getComputeData().getSubBucketMap().put(each.getAggName(), buildBucketsResult(each, bucketStatics))); } } /** * 计算当前聚合的totalDocCount. * * @param aggregation aggregation * @param bucketStatics bucketStatics * @param bucket bucket */ private void buildDocCount(Aggregation aggregation, List<Map<String, BucketStatics>> bucketStatics, Bucket bucket) { long totalDocCount = 0; for (Map<String, BucketStatics> each : bucketStatics) { totalDocCount = totalDocCount + each.get(aggregation.getStaticsId()).getBucket().getDocCount(); } bucket.setDocCount(totalDocCount); } /** * 对bucket结果数据增加排序处理-基于内存排序实现. * TermsAgg按照avg,max,min,sum等sub agg进行排序,或子查询为 DateHistogramAgg需要内存处理排序 * * @param aggregation aggregation * @param buckets buckets * @return buckets */ private List<Bucket> sortBuckets(Aggregation aggregation, List<Bucket> buckets) { List<Bucket> result; result = sortTermsAggBySubAgg(aggregation, buckets); result = sortChildDateHistogramAgg(aggregation, result); return result; } /** * TermsAgg按照avg,max,min,sum等sub agg进行排序. * * @param aggregation aggregation * @param buckets buckets * @return buckets */ private List<Bucket> sortTermsAggBySubAgg(Aggregation aggregation, List<Bucket> buckets) { List<Bucket> result = buckets; if (null == aggregation.getSubAggs() || !AggType.TERMS.equals(aggregation.getAggType())) { return result; } TermsAggStrategy termsAgg = (TermsAggStrategy) aggregation; if (TermsAggOrderType.METRIC_CUSTOM.equals(termsAgg.getOrderType())) { Aggregation subAgg = termsAgg.getSubAggs().get(termsAgg.getOrderBySubAggIndex()); if (!TermsAggOrderType.METRIC_CUSTOM.equals(termsAgg.getOrderType()) || !AggCategory.MATH.equals(subAgg.getAggCategory())) { return result; } String orderValue = termsAgg.getOrder().split(" ")[1]; result = buckets.stream().sorted((o1, o2) -> { BucketsResult s1 = o1.getComputeData().getSubBucketMap().get(subAgg.getAggName()); BucketsResult s2 = o2.getComputeData().getSubBucketMap().get(subAgg.getAggName()); //math类bucket只有一个bucket MathBucket m1 = (MathBucket) s1.getBuckets().get(0); MathBucket m2 = (MathBucket) s2.getBuckets().get(0); int compareValue = (int) (m1.getValue() - m2.getValue()); return orderValue.equalsIgnoreCase(SortType.ASC.name()) ? compareValue : (-compareValue); }).collect(Collectors.toList()); } return result; } /** * 子查询为 DateHistogramAgg需要内存处理排序. * * @param aggregation aggregation * @param buckets buckets * @return buckets */ private List<Bucket> sortChildDateHistogramAgg(Aggregation aggregation, List<Bucket> buckets) { List<Bucket> result = buckets;
if (AggType.DATE_HISTOGRAM.equals(aggregation.getAggType()) && aggregation.getAggDepth() > Constants.AGG_INIT_DEPTH) {
0
2023-11-21 09:12:07+00:00
16k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/gdxparticleeditor/runnables/OpenRunnable.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.files.FileHandle; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.ray3k.gdxparticleeditor.FileDialogs; import com.ray3k.gdxparticleeditor.Settings; import com.ray3k.gdxparticleeditor.Utils; import com.ray3k.gdxparticleeditor.undo.UndoManager; import com.ray3k.gdxparticleeditor.widgets.poptables.PopConfirmLoad; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static com.ray3k.gdxparticleeditor.Core.*; import static com.ray3k.gdxparticleeditor.Settings.*; import static com.ray3k.gdxparticleeditor.Utils.showToast; import static com.ray3k.gdxparticleeditor.widgets.panels.EffectEmittersPanel.effectEmittersPanel; import static com.ray3k.gdxparticleeditor.widgets.panels.EmitterPropertiesPanel.emitterPropertiesPanel;
13,699
package com.ray3k.gdxparticleeditor.runnables; public class OpenRunnable implements Runnable { private static boolean open; @Override public void run () { if (open) return; if (unsavedChangesMade) { var saveFirstRunnable = new SaveRunnable(); var saveAsFirstRunnable = new SaveAsRunnable(); saveFirstRunnable.setSaveAsRunnable(saveAsFirstRunnable); saveAsFirstRunnable.setSaveRunnable(saveFirstRunnable); saveFirstRunnable.setOnCompletionRunnable(this); var pop = new PopConfirmLoad(saveFirstRunnable, () -> { unsavedChangesMade = false; OpenRunnable.this.run(); }); pop.show(foregroundStage); return; } ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(() -> { open = true; stage.getRoot().setTouchable(Touchable.disabled); if (effectEmittersPanel == null || emitterPropertiesPanel == null) return; var useFileExtension = preferences.getBoolean(NAME_PRESUME_FILE_EXTENSION, DEFAULT_PRESUME_FILE_EXTENSION); var filterPatterns = useFileExtension ? new String[] {"p"} : null; var fileHandle = FileDialogs.openDialog("Open", getDefaultSavePath(), filterPatterns, "Particle files (*.p)"); if (fileHandle != null) { defaultFileName = fileHandle.name(); Settings.setDefaultSavePath(fileHandle.parent()); Gdx.app.postRunnable(() -> { loadOnMainThread(fileHandle); }); openFileFileHandle = fileHandle; } stage.getRoot().setTouchable(Touchable.enabled); open = false; }); service.shutdown(); } private void loadOnMainThread (FileHandle fileHandle) { var completed = Utils.loadParticle(fileHandle); if (!completed) return; selectedEmitter = particleEffect.getEmitters().first(); effectEmittersPanel.populateEmitters(); effectEmittersPanel.updateDisableableWidgets(); emitterPropertiesPanel.populateScrollTable(null); effectEmittersPanel.hidePopEmitterControls(); showToast("Opened " + fileHandle.name());
package com.ray3k.gdxparticleeditor.runnables; public class OpenRunnable implements Runnable { private static boolean open; @Override public void run () { if (open) return; if (unsavedChangesMade) { var saveFirstRunnable = new SaveRunnable(); var saveAsFirstRunnable = new SaveAsRunnable(); saveFirstRunnable.setSaveAsRunnable(saveAsFirstRunnable); saveAsFirstRunnable.setSaveRunnable(saveFirstRunnable); saveFirstRunnable.setOnCompletionRunnable(this); var pop = new PopConfirmLoad(saveFirstRunnable, () -> { unsavedChangesMade = false; OpenRunnable.this.run(); }); pop.show(foregroundStage); return; } ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(() -> { open = true; stage.getRoot().setTouchable(Touchable.disabled); if (effectEmittersPanel == null || emitterPropertiesPanel == null) return; var useFileExtension = preferences.getBoolean(NAME_PRESUME_FILE_EXTENSION, DEFAULT_PRESUME_FILE_EXTENSION); var filterPatterns = useFileExtension ? new String[] {"p"} : null; var fileHandle = FileDialogs.openDialog("Open", getDefaultSavePath(), filterPatterns, "Particle files (*.p)"); if (fileHandle != null) { defaultFileName = fileHandle.name(); Settings.setDefaultSavePath(fileHandle.parent()); Gdx.app.postRunnable(() -> { loadOnMainThread(fileHandle); }); openFileFileHandle = fileHandle; } stage.getRoot().setTouchable(Touchable.enabled); open = false; }); service.shutdown(); } private void loadOnMainThread (FileHandle fileHandle) { var completed = Utils.loadParticle(fileHandle); if (!completed) return; selectedEmitter = particleEffect.getEmitters().first(); effectEmittersPanel.populateEmitters(); effectEmittersPanel.updateDisableableWidgets(); emitterPropertiesPanel.populateScrollTable(null); effectEmittersPanel.hidePopEmitterControls(); showToast("Opened " + fileHandle.name());
UndoManager.clear();
3
2023-11-24 15:58:20+00:00
16k
siam1026/siam-server
siam-system/system-provider/src/main/java/com/siam/system/modular/package_goods/controller/member/internal/MemberGoodsCollectController.java
[ { "identifier": "BasicResultCode", "path": "siam-common/src/main/java/com/siam/package_common/constant/BasicResultCode.java", "snippet": "public class BasicResultCode {\n public static final int ERR = 0;\n\n public static final int SUCCESS = 1;\n\n public static final int TOKEN_ERR = 2;\n}" }...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.constant.BasicResultCode; import com.siam.package_common.entity.BasicData; import com.siam.package_common.entity.BasicResult; import com.siam.package_common.exception.StoneCustomerException; import com.siam.system.modular.package_goods.entity.Goods; import com.siam.system.modular.package_goods.service.GoodsService; import com.siam.system.modular.package_goods.service.GoodsSpecificationOptionService; import com.siam.system.modular.package_user.auth.cache.MemberSessionManager; import com.siam.system.modular.package_user.entity.Member; import com.siam.system.modular.package_goods.entity.internal.MemberGoodsCollect; import com.siam.system.modular.package_goods.model.dto.internal.MemberGoodsCollectDto; import com.siam.system.modular.package_goods.model.example.internal.MemberGoodsCollectExample; import com.siam.system.modular.package_goods.service.internal.MemberGoodsCollectService; import com.siam.system.util.TokenUtil; import io.swagger.annotations.Api; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map;
12,448
package com.siam.system.modular.package_goods.controller.member.internal; @Slf4j @RestController @RequestMapping(value = "/rest/member/goodsCollect") @Transactional(rollbackFor = Exception.class) @Api(tags = "用户商品收藏相关接口", description = "MemberGoodsCollectController") public class MemberGoodsCollectController { @Autowired private MemberGoodsCollectService memberGoodsCollectService; @Autowired private MemberSessionManager memberSessionManager; @Autowired private GoodsSpecificationOptionService goodsSpecificationOptionService; @Autowired private GoodsService goodsService; /** * 商品收藏列表 * * @return * @author 暹罗 */ @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) MemberGoodsCollectDto memberGoodsCollectDto, HttpServletRequest request){ BasicData basicResult = new BasicData(); Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); //TODO-在查询的时候进行埋点修改,跟以往的级联埋点 / 查询时统计不一样 if (memberGoodsCollectDto.getIsBuy()!=null && memberGoodsCollectDto.getIsBuy()){ //查询已买过的收藏商品,先进行埋点修改操作 memberGoodsCollectService.updateIsBuy(); } //只查询当前登录用户有效的商品收藏记录 memberGoodsCollectDto.setMemberId(loginMember.getId()); memberGoodsCollectDto.setIsGoodsExists(true); Page<Map<String, Object>> page = memberGoodsCollectService.getListByPageJoinGoods(memberGoodsCollectDto.getPageNo(), memberGoodsCollectDto.getPageSize(), memberGoodsCollectDto); return BasicResult.success(page); } /** * 新增商品收藏 * * @return * @author 暹罗 */ @PostMapping(value = "/insert") public BasicResult insert(@RequestBody @Validated(value = {}) MemberGoodsCollect memberGoodsCollect, HttpServletRequest request){ BasicResult basicResult = new BasicResult(); Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); //判断是否为第一次加入商品收藏,如果不是则数量加1 MemberGoodsCollectExample example = new MemberGoodsCollectExample(); example.createCriteria().andMemberIdEqualTo(loginMember.getId()) .andGoodsIdEqualTo(memberGoodsCollect.getGoodsId()); List<MemberGoodsCollect> MemberGoodsCollectList = memberGoodsCollectService.selectByExample(example); if(MemberGoodsCollectList!=null && MemberGoodsCollectList.size() > 0){ throw new StoneCustomerException("您已经收藏过此商品"); } //查询该商品对应的门店信息 Goods dbGoods = goodsService.selectByPrimaryKey(memberGoodsCollect.getGoodsId()); if(dbGoods == null){ throw new StoneCustomerException("该商品不存在"); } memberGoodsCollect.setShopId(dbGoods.getShopId()); //加入商品收藏 memberGoodsCollect.setMemberId(loginMember.getId()); memberGoodsCollectService.insertSelective(memberGoodsCollect); basicResult.setSuccess(true);
package com.siam.system.modular.package_goods.controller.member.internal; @Slf4j @RestController @RequestMapping(value = "/rest/member/goodsCollect") @Transactional(rollbackFor = Exception.class) @Api(tags = "用户商品收藏相关接口", description = "MemberGoodsCollectController") public class MemberGoodsCollectController { @Autowired private MemberGoodsCollectService memberGoodsCollectService; @Autowired private MemberSessionManager memberSessionManager; @Autowired private GoodsSpecificationOptionService goodsSpecificationOptionService; @Autowired private GoodsService goodsService; /** * 商品收藏列表 * * @return * @author 暹罗 */ @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) MemberGoodsCollectDto memberGoodsCollectDto, HttpServletRequest request){ BasicData basicResult = new BasicData(); Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); //TODO-在查询的时候进行埋点修改,跟以往的级联埋点 / 查询时统计不一样 if (memberGoodsCollectDto.getIsBuy()!=null && memberGoodsCollectDto.getIsBuy()){ //查询已买过的收藏商品,先进行埋点修改操作 memberGoodsCollectService.updateIsBuy(); } //只查询当前登录用户有效的商品收藏记录 memberGoodsCollectDto.setMemberId(loginMember.getId()); memberGoodsCollectDto.setIsGoodsExists(true); Page<Map<String, Object>> page = memberGoodsCollectService.getListByPageJoinGoods(memberGoodsCollectDto.getPageNo(), memberGoodsCollectDto.getPageSize(), memberGoodsCollectDto); return BasicResult.success(page); } /** * 新增商品收藏 * * @return * @author 暹罗 */ @PostMapping(value = "/insert") public BasicResult insert(@RequestBody @Validated(value = {}) MemberGoodsCollect memberGoodsCollect, HttpServletRequest request){ BasicResult basicResult = new BasicResult(); Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); //判断是否为第一次加入商品收藏,如果不是则数量加1 MemberGoodsCollectExample example = new MemberGoodsCollectExample(); example.createCriteria().andMemberIdEqualTo(loginMember.getId()) .andGoodsIdEqualTo(memberGoodsCollect.getGoodsId()); List<MemberGoodsCollect> MemberGoodsCollectList = memberGoodsCollectService.selectByExample(example); if(MemberGoodsCollectList!=null && MemberGoodsCollectList.size() > 0){ throw new StoneCustomerException("您已经收藏过此商品"); } //查询该商品对应的门店信息 Goods dbGoods = goodsService.selectByPrimaryKey(memberGoodsCollect.getGoodsId()); if(dbGoods == null){ throw new StoneCustomerException("该商品不存在"); } memberGoodsCollect.setShopId(dbGoods.getShopId()); //加入商品收藏 memberGoodsCollect.setMemberId(loginMember.getId()); memberGoodsCollectService.insertSelective(memberGoodsCollect); basicResult.setSuccess(true);
basicResult.setCode(BasicResultCode.SUCCESS);
0
2023-11-26 12:41:06+00:00
16k
3dcitydb/citydb-tool
citydb-cli/src/main/java/org/citydb/cli/importer/ImportController.java
[ { "identifier": "ExecutionException", "path": "citydb-cli/src/main/java/org/citydb/cli/ExecutionException.java", "snippet": "public class ExecutionException extends Exception {\n\n public ExecutionException() {\n super();\n }\n\n public ExecutionException(String message) {\n super...
import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; import org.citydb.cli.ExecutionException; import org.citydb.cli.command.Command; import org.citydb.cli.option.*; import org.citydb.cli.util.CommandHelper; import org.citydb.config.Config; import org.citydb.config.ConfigObject; import org.citydb.core.file.InputFile; import org.citydb.database.DatabaseManager; import org.citydb.io.IOAdapter; import org.citydb.io.IOAdapterManager; import org.citydb.io.InputFiles; import org.citydb.io.reader.FeatureReader; import org.citydb.io.reader.ReadOptions; import org.citydb.io.reader.option.InputFormatOptions; import org.citydb.logging.LoggerManager; import org.citydb.model.feature.Feature; import org.citydb.operation.importer.ImportOptions; import org.citydb.operation.importer.Importer; import org.citydb.operation.importer.util.StatisticsConsumer; import org.citydb.operation.util.FeatureStatistics; import picocli.CommandLine; import java.io.IOException; import java.util.List; import java.util.concurrent.atomic.AtomicLong;
13,083
/* * 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.cli.importer; public abstract class ImportController implements Command { @CommandLine.Mixin protected InputFileOptions inputFileOptions; @CommandLine.Option(names = "--fail-fast", description = "Fail fast on errors.") protected Boolean failFast; @CommandLine.Mixin protected ThreadsOption threadsOption; @CommandLine.Option(names = "--preview", description = "Run in preview mode. Features will not be imported.") protected boolean preview; @CommandLine.Mixin protected IndexOption indexOption; @CommandLine.Option(names = "--compute-extent", description = "Compute and overwrite extents of features.") protected Boolean computeEnvelopes; @CommandLine.ArgGroup(exclusive = false, order = Integer.MAX_VALUE, heading = "Database connection options:%n") protected ConnectionOptions connectionOptions; @ConfigOption private Config config; protected final Logger logger = LoggerManager.getInstance().getLogger(ImportController.class); protected final CommandHelper helper = CommandHelper.newInstance(); private final Object lock = new Object(); private volatile boolean shouldRun = true;
/* * 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.cli.importer; public abstract class ImportController implements Command { @CommandLine.Mixin protected InputFileOptions inputFileOptions; @CommandLine.Option(names = "--fail-fast", description = "Fail fast on errors.") protected Boolean failFast; @CommandLine.Mixin protected ThreadsOption threadsOption; @CommandLine.Option(names = "--preview", description = "Run in preview mode. Features will not be imported.") protected boolean preview; @CommandLine.Mixin protected IndexOption indexOption; @CommandLine.Option(names = "--compute-extent", description = "Compute and overwrite extents of features.") protected Boolean computeEnvelopes; @CommandLine.ArgGroup(exclusive = false, order = Integer.MAX_VALUE, heading = "Database connection options:%n") protected ConnectionOptions connectionOptions; @ConfigOption private Config config; protected final Logger logger = LoggerManager.getInstance().getLogger(ImportController.class); protected final CommandHelper helper = CommandHelper.newInstance(); private final Object lock = new Object(); private volatile boolean shouldRun = true;
protected abstract IOAdapter getIOAdapter(IOAdapterManager ioManager) throws ExecutionException;
7
2023-11-19 12:29:54+00:00
16k
magmamaintained/Magma-1.12.2
src/main/java/org/bukkit/command/defaults/PluginsCommand.java
[ { "identifier": "Bukkit", "path": "src/main/java/org/bukkit/Bukkit.java", "snippet": "public final class Bukkit {\n private static Server server;\n\n /**\n * Static class cannot be initialized.\n */\n private Bukkit() {}\n\n /**\n * Gets the current {@link Server} singleton\n ...
import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap;
14,027
package org.bukkit.command.defaults; public class PluginsCommand extends BukkitCommand { public PluginsCommand(String name) { super(name); this.description = "Gets a list of plugins running on the server"; this.usageMessage = "/plugins [load|unload|reload] [name]"; this.setPermission("bukkit.command.plugins"); this.setAliases(Arrays.asList("pl")); } @Override public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) { return true; } if (args.length == 0) { sender.sendMessage("Plugins " + getPluginList()); return false; } switch (args[0].toLowerCase(Locale.ENGLISH)) { // case "load": // PluginManagers.loadPluginCommand(sender, currentAlias, args); // break; // case "unload": // PluginManagers.unloadPluginCommand(sender, currentAlias, args); // break; // case "reload": // PluginManagers.reloadPluginCommand(sender, currentAlias, args); // break; default: sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } // return true; } @Override public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { List<String> tabs = new ArrayList<String>(); if (args.length > 1) { String action = args[0].toLowerCase(); if (action.equals("unload")) {
package org.bukkit.command.defaults; public class PluginsCommand extends BukkitCommand { public PluginsCommand(String name) { super(name); this.description = "Gets a list of plugins running on the server"; this.usageMessage = "/plugins [load|unload|reload] [name]"; this.setPermission("bukkit.command.plugins"); this.setAliases(Arrays.asList("pl")); } @Override public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) { return true; } if (args.length == 0) { sender.sendMessage("Plugins " + getPluginList()); return false; } switch (args[0].toLowerCase(Locale.ENGLISH)) { // case "load": // PluginManagers.loadPluginCommand(sender, currentAlias, args); // break; // case "unload": // PluginManagers.unloadPluginCommand(sender, currentAlias, args); // break; // case "reload": // PluginManagers.reloadPluginCommand(sender, currentAlias, args); // break; default: sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } // return true; } @Override public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { List<String> tabs = new ArrayList<String>(); if (args.length > 1) { String action = args[0].toLowerCase(); if (action.equals("unload")) {
for (Plugin plugin : Bukkit.getServer().getPluginManager().getPlugins()) {
3
2023-11-22 11:25:51+00:00
16k
logaritex/assistant-api
src/test/java/com/logaritex/ai/api/samples/retrieval/KnowledgeRetrievalAssistant.java
[ { "identifier": "AssistantApi", "path": "src/main/java/com/logaritex/ai/api/AssistantApi.java", "snippet": "public class AssistantApi {\n\n\t/**\n\t * OpenAI assistant api beta marker.\n\t */\n\tpublic static final String OPEN_AI_BETA = \"OpenAI-Beta\";\n\n\t/**\n\t * OpenAI assistant api version.\n\t *...
import java.util.List; import java.util.Map; import com.logaritex.ai.api.AssistantApi; import com.logaritex.ai.api.Data; import com.logaritex.ai.api.Data.Message; import com.logaritex.ai.api.Data.Run; import com.logaritex.ai.api.FileApi; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.io.DefaultResourceLoader;
13,751
/* * Copyright 2023-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.logaritex.ai.api.samples.retrieval; /** * Knowledge Retrieval Tool - expends the knowledge of the Assistant: https://youtu.be/pq34V_V5j18?t=2014 * * This demo creates an Assistant instructed as a SpringBoot expert that can answer related question. The Retrieval Tool * is enabled to augment the Assistant with knowledge from outside its model, such as proprietary product information or * documents (e.g. the Spring Boot pdf docs). Once a doc files are uploaded and passed to the Assistant, OpenAI * automatically chunks the documents, index and store the embeddings, and implement vector search to retrieve relevant * content to answer user queries. * * The Retrieval Tool is likely a OpenAI, built-in, RAG solution with quite limited configuration options at the moment: * "Retrieval currently optimizes for quality by adding all relevant content to the context of model calls. We plan to * introduce other retrieval strategies to enable developers to choose a different tradeoff between retrieval quality * and model usage cost." * * @author Christian Tzolov */ public class KnowledgeRetrievalAssistant { private static final Log logger = LogFactory.getLog(KnowledgeRetrievalAssistant.class); public static void main(String[] args) throws InterruptedException { // Use your OpenAI api key to create the FileApi and the AssistantApi clients. logger.info("Create FileApi and AssistantApi with your OPENAI_API_KEY.");
/* * Copyright 2023-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.logaritex.ai.api.samples.retrieval; /** * Knowledge Retrieval Tool - expends the knowledge of the Assistant: https://youtu.be/pq34V_V5j18?t=2014 * * This demo creates an Assistant instructed as a SpringBoot expert that can answer related question. The Retrieval Tool * is enabled to augment the Assistant with knowledge from outside its model, such as proprietary product information or * documents (e.g. the Spring Boot pdf docs). Once a doc files are uploaded and passed to the Assistant, OpenAI * automatically chunks the documents, index and store the embeddings, and implement vector search to retrieve relevant * content to answer user queries. * * The Retrieval Tool is likely a OpenAI, built-in, RAG solution with quite limited configuration options at the moment: * "Retrieval currently optimizes for quality by adding all relevant content to the context of model calls. We plan to * introduce other retrieval strategies to enable developers to choose a different tradeoff between retrieval quality * and model usage cost." * * @author Christian Tzolov */ public class KnowledgeRetrievalAssistant { private static final Log logger = LogFactory.getLog(KnowledgeRetrievalAssistant.class); public static void main(String[] args) throws InterruptedException { // Use your OpenAI api key to create the FileApi and the AssistantApi clients. logger.info("Create FileApi and AssistantApi with your OPENAI_API_KEY.");
FileApi fileApi = new FileApi(System.getenv("OPENAI_API_KEY"));
2
2023-11-25 18:52:37+00:00
16k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/common/CommonProxy.java
[ { "identifier": "CACasingTierProperty", "path": "src/main/java/cn/gtcommunity/epimorphism/api/recipe/properties/CACasingTierProperty.java", "snippet": "public class CACasingTierProperty extends RecipeProperty<Integer> {\n\n public static final String KEY = \"machineLevel\";\n private static final ...
import cn.gtcommunity.epimorphism.api.recipe.properties.CACasingTierProperty; import cn.gtcommunity.epimorphism.api.recipe.properties.PACasingTierProperty; import cn.gtcommunity.epimorphism.api.recipe.properties.QFTCasingTierProperty; import cn.gtcommunity.epimorphism.common.blocks.EPBlockWireCoil; import cn.gtcommunity.epimorphism.common.covers.EPCoverBehavior; import cn.gtcommunity.epimorphism.api.recipe.properties.CasingTierProperty; import cn.gtcommunity.epimorphism.api.utils.EPLog; import cn.gtcommunity.epimorphism.common.blocks.EPMetablocks; import cn.gtcommunity.epimorphism.common.items.BehaviorAddition; import cn.gtcommunity.epimorphism.loaders.formula.FormulaManager; import cn.gtcommunity.epimorphism.loaders.recipe.EPRecipeManager; import cn.gtcommunity.epimorphism.loaders.recipe.components.MaterialComponents; import cn.gtcommunity.epimorphism.loaders.recipe.handlers.EPRecipeHandlerList; import gregtech.api.GregTechAPI; import gregtech.api.block.VariantItemBlock; import gregtech.api.cover.CoverDefinition; import gregtech.api.recipes.recipeproperties.FusionEUToStartProperty; import gregtech.loaders.recipe.CraftingComponent; import net.minecraft.block.Block; import net.minecraft.client.resources.I18n; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.crafting.IRecipe; import net.minecraft.util.ResourceLocation; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.registries.IForgeRegistry; import java.util.Objects; import java.util.function.Function; import static gregtech.api.GregTechAPI.HEATING_COILS;
11,606
package cn.gtcommunity.epimorphism.common; @EventBusSubscriber( modid = "epimorphism" ) public class CommonProxy { public CommonProxy() {} public void preLoad() {} @SubscribeEvent public static void syncConfigValues(ConfigChangedEvent.OnConfigChangedEvent event) {} @SubscribeEvent public static void registerBlocks(RegistryEvent.Register<Block> event) { EPLog.logger.info("Registering blocks..."); IForgeRegistry<Block> registry = event.getRegistry(); registry.register(EPMetablocks.EP_GLASS_CASING); registry.register(EPMetablocks.EP_PMMA_CASING); registry.register(EPMetablocks.EP_MULTIBLOCK_CASING); registry.register(EPMetablocks.EP_MULTIBLOCK_CASING_B); registry.register(EPMetablocks.EP_MULTIBLOCK_CASING_C); registry.register(EPMetablocks.EP_CRUCIBLE_CASING); registry.register(EPMetablocks.EP_MILL_CASING); registry.register(EPMetablocks.EP_ACTIVE_MULTIBLOCK_CASING); registry.register(EPMetablocks.EP_COMPONENT_ASSEMBLY_LINE_CASING); registry.register(EPMetablocks.EP_PCB_FACTORY_CASING); registry.register(EPMetablocks.EP_QUANTUM_FORCE_TRANSFORMER_CASING); registry.register(EPMetablocks.EP_CLEANROOM_CASING); registry.register(EPMetablocks.EP_BOILER_CASING); registry.register(EPMetablocks.EP_EXPLOSIVE_BLOCK); registry.register(EPMetablocks.EP_WIRE_COIL); registry.register(EPMetablocks.EP_TRANSPARENT_CASING); registry.register(EPMetablocks.EP_GLASS_CASING_B); registry.register(EPMetablocks.EP_ADV_GLASS_CASING); registry.register(EPMetablocks.EP_BLOCK_FUSION_CASING); } @SubscribeEvent public static void registerItems(RegistryEvent.Register<Item> event) { EPLog.logger.info("Registering Items..."); IForgeRegistry<Item> registry = event.getRegistry(); registry.register(createItemBlock(EPMetablocks.EP_GLASS_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_PMMA_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_MULTIBLOCK_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_MULTIBLOCK_CASING_B, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_MULTIBLOCK_CASING_C, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_CRUCIBLE_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_MILL_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_ACTIVE_MULTIBLOCK_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_COMPONENT_ASSEMBLY_LINE_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_PCB_FACTORY_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_QUANTUM_FORCE_TRANSFORMER_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_CLEANROOM_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_BOILER_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_EXPLOSIVE_BLOCK, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_WIRE_COIL, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_TRANSPARENT_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_GLASS_CASING_B, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_ADV_GLASS_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_BLOCK_FUSION_CASING, VariantItemBlock::new));
package cn.gtcommunity.epimorphism.common; @EventBusSubscriber( modid = "epimorphism" ) public class CommonProxy { public CommonProxy() {} public void preLoad() {} @SubscribeEvent public static void syncConfigValues(ConfigChangedEvent.OnConfigChangedEvent event) {} @SubscribeEvent public static void registerBlocks(RegistryEvent.Register<Block> event) { EPLog.logger.info("Registering blocks..."); IForgeRegistry<Block> registry = event.getRegistry(); registry.register(EPMetablocks.EP_GLASS_CASING); registry.register(EPMetablocks.EP_PMMA_CASING); registry.register(EPMetablocks.EP_MULTIBLOCK_CASING); registry.register(EPMetablocks.EP_MULTIBLOCK_CASING_B); registry.register(EPMetablocks.EP_MULTIBLOCK_CASING_C); registry.register(EPMetablocks.EP_CRUCIBLE_CASING); registry.register(EPMetablocks.EP_MILL_CASING); registry.register(EPMetablocks.EP_ACTIVE_MULTIBLOCK_CASING); registry.register(EPMetablocks.EP_COMPONENT_ASSEMBLY_LINE_CASING); registry.register(EPMetablocks.EP_PCB_FACTORY_CASING); registry.register(EPMetablocks.EP_QUANTUM_FORCE_TRANSFORMER_CASING); registry.register(EPMetablocks.EP_CLEANROOM_CASING); registry.register(EPMetablocks.EP_BOILER_CASING); registry.register(EPMetablocks.EP_EXPLOSIVE_BLOCK); registry.register(EPMetablocks.EP_WIRE_COIL); registry.register(EPMetablocks.EP_TRANSPARENT_CASING); registry.register(EPMetablocks.EP_GLASS_CASING_B); registry.register(EPMetablocks.EP_ADV_GLASS_CASING); registry.register(EPMetablocks.EP_BLOCK_FUSION_CASING); } @SubscribeEvent public static void registerItems(RegistryEvent.Register<Item> event) { EPLog.logger.info("Registering Items..."); IForgeRegistry<Item> registry = event.getRegistry(); registry.register(createItemBlock(EPMetablocks.EP_GLASS_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_PMMA_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_MULTIBLOCK_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_MULTIBLOCK_CASING_B, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_MULTIBLOCK_CASING_C, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_CRUCIBLE_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_MILL_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_ACTIVE_MULTIBLOCK_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_COMPONENT_ASSEMBLY_LINE_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_PCB_FACTORY_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_QUANTUM_FORCE_TRANSFORMER_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_CLEANROOM_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_BOILER_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_EXPLOSIVE_BLOCK, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_WIRE_COIL, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_TRANSPARENT_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_GLASS_CASING_B, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_ADV_GLASS_CASING, VariantItemBlock::new)); registry.register(createItemBlock(EPMetablocks.EP_BLOCK_FUSION_CASING, VariantItemBlock::new));
BehaviorAddition.init();
8
2023-11-26 01:56:35+00:00
16k
ZayrexDev/ZPixiv
src/main/java/xyz/zcraft/zpixiv/ui/Main.java
[ { "identifier": "PixivClient", "path": "src/main/java/xyz/zcraft/zpixiv/api/PixivClient.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class PixivClient {\n private static final Logger LOG = LogManager.getLogger(PixivClient.class);\n private static final String userAgent = \"Mozilla/5.0 ...
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONWriter; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.stage.StageStyle; import lombok.Getter; import lombok.Setter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import xyz.zcraft.zpixiv.api.PixivClient; import xyz.zcraft.zpixiv.ui.controller.InspectController; import xyz.zcraft.zpixiv.ui.controller.MainController; import xyz.zcraft.zpixiv.util.CachedImage; import xyz.zcraft.zpixiv.util.Config; import xyz.zcraft.zpixiv.util.ResourceLoader; import xyz.zcraft.zpixiv.util.SSLUtil; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Base64; import java.util.LinkedList; import java.util.Timer; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor;
11,487
package xyz.zcraft.zpixiv.ui; public class Main extends Application { @Getter public static final LinkedList<CachedImage> loginBackground = new LinkedList<>(); private static final Logger LOG = LogManager.getLogger(Main.class); @Getter private static final ThreadPoolExecutor tpe = (ThreadPoolExecutor) Executors.newCachedThreadPool(); @Getter private static final Timer timer = new Timer(); @Getter private static final Path dataPath = Path.of("data"); @Getter private static final Path configPath = dataPath.resolve("config.json"); @Getter private static final Path userPath = dataPath.resolve("user"); @Getter private static Config config; @Getter private static Stage stage = null; @Getter private static MainController mainController = null; @Getter @Setter
package xyz.zcraft.zpixiv.ui; public class Main extends Application { @Getter public static final LinkedList<CachedImage> loginBackground = new LinkedList<>(); private static final Logger LOG = LogManager.getLogger(Main.class); @Getter private static final ThreadPoolExecutor tpe = (ThreadPoolExecutor) Executors.newCachedThreadPool(); @Getter private static final Timer timer = new Timer(); @Getter private static final Path dataPath = Path.of("data"); @Getter private static final Path configPath = dataPath.resolve("config.json"); @Getter private static final Path userPath = dataPath.resolve("user"); @Getter private static Config config; @Getter private static Stage stage = null; @Getter private static MainController mainController = null; @Getter @Setter
private static PixivClient client = null;
0
2023-11-23 15:08:16+00:00
16k
myzticbean/QSFindItemAddOn
src/main/java/io/myzticbean/finditemaddon/Handlers/CommandHandler/CmdExecutorHandler.java
[ { "identifier": "ConfigSetup", "path": "src/main/java/io/myzticbean/finditemaddon/ConfigUtil/ConfigSetup.java", "snippet": "public class ConfigSetup {\n\n private static File configFile;\n private static File sampleConfigFile;\n private static FileConfiguration configFileConfiguration;\n pri...
import io.myzticbean.finditemaddon.ConfigUtil.ConfigSetup; import io.myzticbean.finditemaddon.FindItemAddOn; import io.myzticbean.finditemaddon.Handlers.GUIHandler.Menus.FoundShopsMenu; import io.myzticbean.finditemaddon.Models.FoundShopItemModel; import io.myzticbean.finditemaddon.Utils.Defaults.PlayerPerms; import io.myzticbean.finditemaddon.Utils.JsonStorageUtils.HiddenShopStorageUtil; import io.myzticbean.finditemaddon.Utils.LoggerUtils; import io.myzticbean.finditemaddon.Utils.WarpUtils.WarpUtils; import me.kodysimpson.simpapi.colors.ColorTranslator; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.maxgamer.quickshop.api.shop.Shop; import java.util.List;
12,381
package io.myzticbean.finditemaddon.Handlers.CommandHandler; /** * Handler for different parameters of /finditem command * @author ronsane */ public class CmdExecutorHandler { /** * Handles the main shop search process * @param buySellSubCommand Whether player is buying or selling * @param commandSender Who is the command sender: console or player * @param itemArg Specifies Item ID or Item name */ public void handleShopSearch(String buySellSubCommand, CommandSender commandSender, String itemArg) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_USE.value())) {
package io.myzticbean.finditemaddon.Handlers.CommandHandler; /** * Handler for different parameters of /finditem command * @author ronsane */ public class CmdExecutorHandler { /** * Handles the main shop search process * @param buySellSubCommand Whether player is buying or selling * @param commandSender Who is the command sender: console or player * @param itemArg Specifies Item ID or Item name */ public void handleShopSearch(String buySellSubCommand, CommandSender commandSender, String itemArg) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_USE.value())) {
if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)) {
1
2023-11-22 11:36:01+00:00
16k
DIDA-lJ/qiyao-12306
services/order-service/src/main/java/org/opengoofy/index12306/biz/orderservice/service/impl/OrderServiceImpl.java
[ { "identifier": "OrderCanalErrorCodeEnum", "path": "services/order-service/src/main/java/org/opengoofy/index12306/biz/orderservice/common/enums/OrderCanalErrorCodeEnum.java", "snippet": "@AllArgsConstructor\npublic enum OrderCanalErrorCodeEnum implements IErrorCode {\n\n ORDER_CANAL_UNKNOWN_ERROR(\"B...
import cn.hutool.core.collection.ListUtil; import cn.hutool.core.text.StrBuilder; import com.alibaba.fastjson2.JSON; 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.baomidou.mybatisplus.core.toolkit.Wrappers; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.client.producer.SendStatus; import org.opengoofy.index12306.biz.orderservice.common.enums.OrderCanalErrorCodeEnum; import org.opengoofy.index12306.biz.orderservice.common.enums.OrderItemStatusEnum; import org.opengoofy.index12306.biz.orderservice.common.enums.OrderStatusEnum; import org.opengoofy.index12306.biz.orderservice.dao.entity.OrderDO; import org.opengoofy.index12306.biz.orderservice.dao.entity.OrderItemDO; import org.opengoofy.index12306.biz.orderservice.dao.entity.OrderItemPassengerDO; import org.opengoofy.index12306.biz.orderservice.dao.mapper.OrderItemMapper; import org.opengoofy.index12306.biz.orderservice.dao.mapper.OrderMapper; import org.opengoofy.index12306.biz.orderservice.dto.domain.OrderStatusReversalDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.CancelTicketOrderReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderCreateReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderItemCreateReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderPageQueryReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderSelfPageQueryReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.resp.TicketOrderDetailRespDTO; import org.opengoofy.index12306.biz.orderservice.dto.resp.TicketOrderDetailSelfRespDTO; import org.opengoofy.index12306.biz.orderservice.dto.resp.TicketOrderPassengerDetailRespDTO; import org.opengoofy.index12306.biz.orderservice.mq.event.DelayCloseOrderEvent; import org.opengoofy.index12306.biz.orderservice.mq.event.PayResultCallbackOrderEvent; import org.opengoofy.index12306.biz.orderservice.mq.produce.DelayCloseOrderSendProduce; import org.opengoofy.index12306.biz.orderservice.remote.UserRemoteService; import org.opengoofy.index12306.biz.orderservice.remote.dto.UserQueryActualRespDTO; import org.opengoofy.index12306.biz.orderservice.service.OrderItemService; import org.opengoofy.index12306.biz.orderservice.service.OrderPassengerRelationService; import org.opengoofy.index12306.biz.orderservice.service.OrderService; import org.opengoofy.index12306.biz.orderservice.service.orderid.OrderIdGeneratorManager; import org.opengoofy.index12306.framework.starter.common.toolkit.BeanUtil; import org.opengoofy.index12306.framework.starter.convention.exception.ClientException; import org.opengoofy.index12306.framework.starter.convention.exception.ServiceException; import org.opengoofy.index12306.framework.starter.convention.page.PageResponse; import org.opengoofy.index12306.framework.starter.convention.result.Result; import org.opengoofy.index12306.framework.starter.database.toolkit.PageUtil; import org.opengoofy.index12306.frameworks.starter.user.core.UserContext; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Objects;
11,065
/* * 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.orderservice.service.impl; /** * 订单服务接口层实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class OrderServiceImpl implements OrderService { private final OrderMapper orderMapper; private final OrderItemMapper orderItemMapper; private final OrderItemService orderItemService; private final OrderPassengerRelationService orderPassengerRelationService; private final RedissonClient redissonClient; private final DelayCloseOrderSendProduce delayCloseOrderSendProduce; private final UserRemoteService userRemoteService; @Override public TicketOrderDetailRespDTO queryTicketOrderByOrderSn(String orderSn) { LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class) .eq(OrderDO::getOrderSn, orderSn); OrderDO orderDO = orderMapper.selectOne(queryWrapper); TicketOrderDetailRespDTO result = BeanUtil.convert(orderDO, TicketOrderDetailRespDTO.class); LambdaQueryWrapper<OrderItemDO> orderItemQueryWrapper = Wrappers.lambdaQuery(OrderItemDO.class) .eq(OrderItemDO::getOrderSn, orderSn); List<OrderItemDO> orderItemDOList = orderItemMapper.selectList(orderItemQueryWrapper);
/* * 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.orderservice.service.impl; /** * 订单服务接口层实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class OrderServiceImpl implements OrderService { private final OrderMapper orderMapper; private final OrderItemMapper orderItemMapper; private final OrderItemService orderItemService; private final OrderPassengerRelationService orderPassengerRelationService; private final RedissonClient redissonClient; private final DelayCloseOrderSendProduce delayCloseOrderSendProduce; private final UserRemoteService userRemoteService; @Override public TicketOrderDetailRespDTO queryTicketOrderByOrderSn(String orderSn) { LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class) .eq(OrderDO::getOrderSn, orderSn); OrderDO orderDO = orderMapper.selectOne(queryWrapper); TicketOrderDetailRespDTO result = BeanUtil.convert(orderDO, TicketOrderDetailRespDTO.class); LambdaQueryWrapper<OrderItemDO> orderItemQueryWrapper = Wrappers.lambdaQuery(OrderItemDO.class) .eq(OrderItemDO::getOrderSn, orderSn); List<OrderItemDO> orderItemDOList = orderItemMapper.selectList(orderItemQueryWrapper);
result.setPassengerDetails(BeanUtil.convert(orderItemDOList, TicketOrderPassengerDetailRespDTO.class));
16
2023-11-23 07:59:11+00:00
16k
estkme-group/infineon-lpa-mirror
app/src/main/java/com/infineon/esim/lpa/data/DataModel.java
[ { "identifier": "ActivationCode", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/ActivationCode.java", "snippet": "public class ActivationCode implements Parcelable {\n private String activationCode;\n\n private final Boolean isValid;\n private String acFormat;\n private String ...
import android.content.Context; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Observer; import com.infineon.esim.lpa.core.dtos.ActivationCode; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.dtos.profile.ProfileList; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult; import com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult; import com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult; import com.infineon.esim.lpa.euicc.EuiccManager; import com.infineon.esim.lpa.lpa.LocalProfileAssistant; import com.infineon.esim.lpa.ui.generic.ActionStatus; import com.infineon.esim.lpa.ui.generic.AsyncActionStatus; import com.infineon.esim.lpa.ui.generic.Error; import com.infineon.esim.lpa.util.android.OneTimeEvent; import com.infineon.esim.util.Log; import java.util.List;
12,450
/* * 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.data; public class DataModel implements StatusAndEventHandler{ private static final String TAG = DataModel.class.getName(); private static DataModel instance; private final LocalProfileAssistant lpa; private final EuiccManager euiccManager; private final MutableLiveData<AsyncActionStatus> actionStatusLiveData; private final MutableLiveData<OneTimeEvent<Error>> errorEventLiveData; private DataModel(Context context) { this.euiccManager = new EuiccManager(context, this); this.lpa = new LocalProfileAssistant(euiccManager, this); this.actionStatusLiveData = new MutableLiveData<>(); this.errorEventLiveData = new MutableLiveData<>(); euiccManager.initializeInterfaces(); actionStatusLiveData.observeForever(actionStatusObserver); } public static void initializeInstance(Context context) { if(instance == null) { instance = new DataModel(context); } } public static DataModel getInstance() { return instance; } // observing action status final Observer<AsyncActionStatus> actionStatusObserver = actionStatus -> { Log.debug(TAG, "Observed that action status changed: " + actionStatus.getActionStatus()); switch (actionStatus.getActionStatus()) { case ENABLE_PROFILE_FINISHED: case DELETE_PROFILE_FINISHED: case DISABLE_PROFILE_FINISHED: case SET_NICKNAME_FINISHED: refreshProfileList(); break; } }; // region Getter public LiveData<String> getCurrentEuiccLiveData() { return euiccManager.getCurrentEuiccLiveData(); } public LiveData<List<String>> getEuiccListLiveData() { return euiccManager.getEuiccListLiveData(); }
/* * 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.data; public class DataModel implements StatusAndEventHandler{ private static final String TAG = DataModel.class.getName(); private static DataModel instance; private final LocalProfileAssistant lpa; private final EuiccManager euiccManager; private final MutableLiveData<AsyncActionStatus> actionStatusLiveData; private final MutableLiveData<OneTimeEvent<Error>> errorEventLiveData; private DataModel(Context context) { this.euiccManager = new EuiccManager(context, this); this.lpa = new LocalProfileAssistant(euiccManager, this); this.actionStatusLiveData = new MutableLiveData<>(); this.errorEventLiveData = new MutableLiveData<>(); euiccManager.initializeInterfaces(); actionStatusLiveData.observeForever(actionStatusObserver); } public static void initializeInstance(Context context) { if(instance == null) { instance = new DataModel(context); } } public static DataModel getInstance() { return instance; } // observing action status final Observer<AsyncActionStatus> actionStatusObserver = actionStatus -> { Log.debug(TAG, "Observed that action status changed: " + actionStatus.getActionStatus()); switch (actionStatus.getActionStatus()) { case ENABLE_PROFILE_FINISHED: case DELETE_PROFILE_FINISHED: case DISABLE_PROFILE_FINISHED: case SET_NICKNAME_FINISHED: refreshProfileList(); break; } }; // region Getter public LiveData<String> getCurrentEuiccLiveData() { return euiccManager.getCurrentEuiccLiveData(); } public LiveData<List<String>> getEuiccListLiveData() { return euiccManager.getEuiccListLiveData(); }
public LiveData<ProfileList> getProfileListLiveData() {
2
2023-11-22 07:46:30+00:00
16k
phamdung2209/FAP
src/main/java/com/func/LectureHandler/Update.java
[ { "identifier": "DateOfBirth", "path": "src/main/java/com/Date/DateOfBirth.java", "snippet": "public class DateOfBirth {\n private int day;\n private int month;\n private int year;\n\n public DateOfBirth() {\n }\n\n public DateOfBirth(int day, int month, int year) {\n this.day =...
import java.util.Scanner; import com.date.DateOfBirth; import com.persons.Administrator; import com.persons.Lecturer;
11,269
package com.func.LectureHandler; public class Update { public Scanner scanner = new Scanner(System.in); public void updateLecture(Administrator admin, String lectureIdUpdate) { System.out.print("Full name: "); String uLname = scanner.nextLine(); System.out.print("Date of birth: "); int uLday = scanner.nextInt(); System.out.print("Month of birth: "); int uLmonth = scanner.nextInt(); System.out.print("Year of birth: "); int uLyear = scanner.nextInt();
package com.func.LectureHandler; public class Update { public Scanner scanner = new Scanner(System.in); public void updateLecture(Administrator admin, String lectureIdUpdate) { System.out.print("Full name: "); String uLname = scanner.nextLine(); System.out.print("Date of birth: "); int uLday = scanner.nextInt(); System.out.print("Month of birth: "); int uLmonth = scanner.nextInt(); System.out.print("Year of birth: "); int uLyear = scanner.nextInt();
DateOfBirth uLdateOfBirth = new DateOfBirth();
0
2023-11-23 18:42:19+00:00
16k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/certificate/acme/api/endpoints/account/NewAccountEndpoint.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.account.objects.ACMEAccountRequestPayload; import de.morihofi.acmeserver.certificate.acme.api.endpoints.account.objects.AccountResponse; import de.morihofi.acmeserver.certificate.objects.ACMERequestBody; import de.morihofi.acmeserver.database.Database; import de.morihofi.acmeserver.certificate.acme.security.NonceManager; import de.morihofi.acmeserver.exception.exceptions.ACMEInvalidContactException; import de.morihofi.acmeserver.exception.exceptions.ACMEMalformedException; import de.morihofi.acmeserver.tools.crypto.Crypto; import de.morihofi.acmeserver.tools.regex.EmailValidation; import io.javalin.http.Context; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import java.util.List; import java.util.UUID;
11,333
package de.morihofi.acmeserver.certificate.acme.api.endpoints.account; public class NewAccountEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass()); public NewAccountEndpoint(Provisioner provisioner) { super(provisioner); } @Override public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception { // Check nonce NonceManager.checkNonceFromDecodedProtected(acmeRequestBody.getDecodedProtected()); // Deserialize payload and protected objects ACMEAccountRequestPayload payload = gson.fromJson(acmeRequestBody.getDecodedPayload(), ACMEAccountRequestPayload.class); JSONObject reqBodyProtectedObj = new JSONObject(acmeRequestBody.getDecodedProtected()); // Check terms of service agreement if (!payload.getTermsOfServiceAgreed()) { throw new ACMEMalformedException("Terms of Service not accepted. Unable to create account"); } // Validate email addresses List<String> emails = payload.getContact(); if (emails != null) { for (String email : emails) { email = email.replace("mailto:", ""); if (!EmailValidation.isValidEmail(email) || email.split("@")[0].equals("localhost")) { log.error("E-Mail validation failed for email {}", email); throw new ACMEInvalidContactException("Mail validation failed for email " + email); } } } // Create new account in database String accountId = UUID.randomUUID().toString();
package de.morihofi.acmeserver.certificate.acme.api.endpoints.account; public class NewAccountEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass()); public NewAccountEndpoint(Provisioner provisioner) { super(provisioner); } @Override public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception { // Check nonce NonceManager.checkNonceFromDecodedProtected(acmeRequestBody.getDecodedProtected()); // Deserialize payload and protected objects ACMEAccountRequestPayload payload = gson.fromJson(acmeRequestBody.getDecodedPayload(), ACMEAccountRequestPayload.class); JSONObject reqBodyProtectedObj = new JSONObject(acmeRequestBody.getDecodedProtected()); // Check terms of service agreement if (!payload.getTermsOfServiceAgreed()) { throw new ACMEMalformedException("Terms of Service not accepted. Unable to create account"); } // Validate email addresses List<String> emails = payload.getContact(); if (emails != null) { for (String email : emails) { email = email.replace("mailto:", ""); if (!EmailValidation.isValidEmail(email) || email.split("@")[0].equals("localhost")) { log.error("E-Mail validation failed for email {}", email); throw new ACMEInvalidContactException("Mail validation failed for email " + email); } } } // Create new account in database String accountId = UUID.randomUUID().toString();
Database.createAccount(accountId, reqBodyProtectedObj.getJSONObject("jwk").toString(), emails);
5
2023-11-22 15:54:36+00:00
16k
clover/clover-tr34-host
src/main/java/com/clover/tr34/samples/CloverDevTr34KeyStoreData.java
[ { "identifier": "Tr34CryptoUtils", "path": "src/main/java/com/clover/tr34/Tr34CryptoUtils.java", "snippet": "public final class Tr34CryptoUtils {\n\n private Tr34CryptoUtils() { }\n\n public static PrivateKey parsePrivateKey(String pem) {\n if (pem.contains(\"BEGIN RSA PRIVATE KEY\")) {\n ...
import com.clover.tr34.Tr34CryptoUtils; import com.clover.tr34.Tr34KdhRevocation; import com.clover.tr34.Tr34KeyStoreData; import com.clover.tr34.Tr34ScdKeyStoreData; import java.math.BigInteger; import java.security.PrivateKey; import java.security.cert.CRLReason; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Date; import java.util.List;
14,071
"QJ2+xLT9vTZRIQFDhCbnzxkqVbq4YUSXkyeDhwIDAQABAoIBAEHscgnIHMRfRkhO\n" + "Sbk5eRTYv1ZXfbkzRV1DsNVHpmXfZlW24FwcTawvKwPF6sU5Le6Ey9TVJyVtZYid\n" + "8FzFlEqSW6GNpZMH7L8lBpLdpAY/y1k+jCNFAFDaPDm7SAqUCsvjVt6Jbo9pmSvb\n" + "HmUReHL52T/AvBrUqTQJoveZoNK68cyq9Uz54oEvyt1WrU7zaNiFGpH90Q1Qhb2J\n" + "Nlpjihpc6syqluVruYND/bJm9DJGqMLdlS6uD6fXp5aCGfixwvndLq1h6TCzEXLf\n" + "HcL8elN60SIZXUKDKPEDIQQa9jzBx6eqThErCvr7lZ6+YNqIx4F+2nkJdoZCrXN5\n" + "9a+f7fECgYEAydySZAEN/bIUlwXvN04x675rJtc4ih++dUrT7QrLouzhMz4wdIwM\n" + "RnV3/i/vkQoec1zjI7VETKlfgRDlicFjgShiyz74KJrUxmgvrfQsgO9wkNKrtAsm\n" + "936Qizh5+3WjuAPf/xtZhk31NVDR8v5IJJEDl5Miv47MAJxiCv5rSvsCgYEAw923\n" + "lJYzgRjjKdBMOFNEliVsmWaPrnwQDKKtJ809dq5THYwK9/Taz5Xx2SQBWxZF06/Z\n" + "efW2IqhNAza4unyNmVTcKiKiy/ziZwLMVl5gBudzrFuVnxSaDd7kCAlL9dTJ17dq\n" + "sf2FadgmqCvIlCgpkodi+HSXfCYdJ4rViyg9g+UCgYA4h4WTbdwuLJ2pgWbxVPuT\n" + "6jp1oRXbUHJ0xGS+4CQQ10dlo0fMi5+wZ5sX2vK66luGsP+G829SDKiLK2Esh7TG\n" + "6blo85RpQprNiUW48EU6QlOCqwycmfbqnk36PvGiItqbYLJs7YrPmqtNp/lzlBQ9\n" + "8UJRQ0oa3PFyRlkKfR8s2wKBgHqmiYH7OI9b1UxmyoPu6KEZGFNLHShHOgmfiMzG\n" + "wflimluDSY8R/j9FhyfRWyP944X2tTmg+wfi2i7sAmuM+WKN+DxOaiFQ3zlgUDK5\n" + "cGqCXzYMN7phPUL4U1UQ9Ucgk7CIg8Cnn/ayyyo+GKFmMPo322r4H7A3ccRENQqq\n" + "DTNdAoGBALKefyenQOTgjdIXlDICTIM4VRAMzrGI43wnIPKE6DEZwxhzt0jE5NYu\n" + "jWpTbaTuduIC6/b0jbiIBDefrOh/Rw4iVicXxC4lJJCoLqrNdLBfqvt9JAvBndan\n" + "KlXNyoIMUktye1+fywLHfmU+k0tWMm2PacdD7V4aUpN3G1qQeIwt\n" + "-----END RSA PRIVATE KEY-----\n"; public static final String TR34_KRD_1_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDcDCCAligAwIBAgIQbCpMOGMtYO46ksi7B0ziSTANBgkqhkiG9w0BAQsFADBT\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEgMB4GA1UEAxMXVEVTVCBDbG92ZXIgVFIzNCBLUkQgQ0EwHhcNMjMwOTAxMjIw\n" + "NjUwWhcNMzgwODE0MjIwMDA5WjBSMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xv\n" + "dmVyMREwDwYDVQQLEwhkZXZpY2VvczEfMB0GA1UEAxMWVEVTVCBDbG92ZXIgVFIz\n" + "NCBLUkQgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALhilgrs5YCt\n" + "DSiWa/Z/TX96qztN0dLlyh7rYimeBkEpEU4kJwWogRrt6CGIQ1+guSZLm4QtqWzn\n" + "bR72bDSJHLArnWi+Dx+9AHMK1AaZUrf75eC/yh5yV/sI0YFmnWp4DjV0AtGKgzDm\n" + "cjgQloIR2zrUrPXihXSUcwxJe0q/IqrMEdQ+morvZ2w+8Vlo1WszyvknhrCUWzKg\n" + "zf9DZ+9BG1fKREffS2SUruBHCFkQeXDFdP3d1RtgZznWGXQhwUXa5jkoFkR4jQYK\n" + "R8Lhj8v9YEbWcG8L7lOMkCZfRWeGzuQnjKRS9bx6D67gxvY2XJLbmfov4HNVkdxS\n" + "O68xEd8qI6UCAwEAAaNBMD8wDgYDVR0PAQH/BAQDAgeAMAwGA1UdEwEB/wQCMAAw\n" + "HwYDVR0jBBgwFoAU11VYe+bdyaYUH4MF8MFoJvdaOFkwDQYJKoZIhvcNAQELBQAD\n" + "ggEBAKdiYCU87sxKtldqs+4bNrSIXEwc/6XKCG2nCCToGNYOE2FApDWBZcOUcSEd\n" + "Lp0n7FEa/gLWVr5J/EOUkDp+5gAgmtbyvHptla8ThxVWPFHCXXbo4qlylfFwcXF1\n" + "OG8I+mwggUSh9DFoq27JUJApjaDcVyQ2Ywvdq0EcITYgrrZKZrqD7JYTEYmVXtKq\n" + "B4091HxtSM9vWophBudJDfK308x9fj+PM6AZqWRG7XCMShi3tVERiImTw0Pqn2/P\n" + "K0aEafxpvTRJh0kjsujX4HteBGXzLjjikfyjJKGz6Fyl5A8T9VAEFObqqZQ6Sa92\n" + "wMMs9Ow1xNvbr1cGImewoVhyBJU=\n" + "-----END CERTIFICATE-----"; public static final String TR34_KRD_1_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEogIBAAKCAQEAuGKWCuzlgK0NKJZr9n9Nf3qrO03R0uXKHutiKZ4GQSkRTiQn\n" + "BaiBGu3oIYhDX6C5JkubhC2pbOdtHvZsNIkcsCudaL4PH70AcwrUBplSt/vl4L/K\n" + "HnJX+wjRgWadangONXQC0YqDMOZyOBCWghHbOtSs9eKFdJRzDEl7Sr8iqswR1D6a\n" + "iu9nbD7xWWjVazPK+SeGsJRbMqDN/0Nn70EbV8pER99LZJSu4EcIWRB5cMV0/d3V\n" + "G2BnOdYZdCHBRdrmOSgWRHiNBgpHwuGPy/1gRtZwbwvuU4yQJl9FZ4bO5CeMpFL1\n" + "vHoPruDG9jZcktuZ+i/gc1WR3FI7rzER3yojpQIDAQABAoIBADJnKLLl3TrWk2FD\n" + "9VFVrV6qrsIwXKo1DJJ1L8lGnFkVm9hrg4tFa71ryWfZMumiKtqwElwIi2bswGSV\n" + "YjDeRkxWL9phEgtQBB5umFURdo46urU8WEkIYsqJt5OS9HcVSHUOOHMFVSV56UEw\n" + "L6Rwsyga2QkCGg8rQWPbdmuRYi2j0j95IFvszn7kzQZ6hcoEdbhedYX85Ij4mgR7\n" + "ydeli6SAMQ8dRIbsOFhdf07DvA5st59lRTDeC/kyYMN6SZHRl7Vr9cvsTVawJb7v\n" + "v94Q3fRqzq9rB/JdHjVjjx+NM97sc7azZFFFVtrnlOG80k4lMIZLnjH0ZMpXrkY6\n" + "4Vv7p6UCgYEA5uLIa9+vopgpgTR4CUmqAcDh6EAzAOyIRTxag5c0i2Tz+x4ffc2Y\n" + "6s7Rs9x1b8ypr+z8GKmsjhEyxlToFEG0cZTBQzQEMsQ89jJbbLz8pSglS1hM3W4Y\n" + "zDGhiBtiJRpvuA3ZJN0No09cYDbH/y5ZyM6AAgwK1uD0vu5eTvoP83MCgYEAzHDy\n" + "8rVoHfF82pHrmzz8NRhf8SuDI+rwm+ThDnphteMXmJSz9ki8lljaF2T/mMsCHn1B\n" + "o+R5WTg1b/0+YGEH7OAjKNx+6K7BCZ1dA5S+dHtZjCvp2Bp3UL7FtK3dptQEL3t+\n" + "0SnSFBZ9lpXLj8dQNTwISVM8LD7vOBtVAOZftocCgYApFqzSPcGU7v1b6AmApaJi\n" + "o3/QhDRPcsihgaceCfeo4vNkeizih4cyKlI5bv9bQRHlpAgNH4z8z2S41P1kNXk2\n" + "SWHHYudoXXH34mhQxqUzgxx39yPeuCwjkqWLgkwKDFVbbON64vf9Wy82VCltaUND\n" + "MDSpqJj5OplzrRoNdgUGrwKBgEPHrsSJIFvNFHfiqRpuva9cxXJP2sqtudf1qigC\n" + "qyKCh/AuXPvqYZv3GVdoRNWDeNBi9sA/n3vVBuJ6M5QAl4ART5bcg7bhOV7WrV/i\n" + "kMJNowK2DHF5VNWQajvc6P/Gixyy9PijxOKkEj86qqKgkhcUMCsfTXPd6bHQXf5O\n" + "Yq1BAoGAaYsPFFv1uZJSDLb4kd5wW1o2AV2a5PhKqn71dCvYal6Dtm66jQnSvWSN\n" + "Jo7ewgPInB6FGUiHkG0uxCDaWxbqMoX0Gv6qhXP70TNg6PxTFZYQIcMOtjMWtfbo\n" + "JJbzKc5rgdHayNGWor9LWY7Y3gFASuItLuHLyI8n8Xx/zuaLxv8=\n" + "-----END RSA PRIVATE KEY-----"; private final X509Certificate rootCert; private final X509Certificate krdCaCert; private final X509Certificate kdhCaCert; private final X509Certificate kdhCert; private final PrivateKey krdCaPrivateKey; private final PrivateKey kdhCaPrivateKey; private final PrivateKey kdhPrivateKey; private CloverDevTr34KeyStoreData(String kdhCertPem, String kdhPrivateKeyPem) { kdhCert = Tr34CryptoUtils.parseCert(kdhCertPem); kdhPrivateKey = Tr34CryptoUtils.parsePrivateKey(kdhPrivateKeyPem); rootCert = Tr34CryptoUtils.parseCert(TR34_Root_Cert_Pem); kdhCaCert = Tr34CryptoUtils.parseCert(TR34_KDH_CA_Cert_Pem); krdCaCert = Tr34CryptoUtils.parseCert(TR34_KRD_CA_Cert_Pem); kdhCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(TR34_KDH_CA_PrivateKey_Pem); krdCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(TR34_KRD_CA_PrivateKey_Pem); } public static final Tr34KeyStoreData KDH_1 = new CloverDevTr34KeyStoreData(TR34_KDH_1_Cert_Pem, TR34_KDH_1_PrivateKey_Pem); public static final Tr34KeyStoreData KDH_2 = new CloverDevTr34KeyStoreData(TR34_KDH_2_Cert_Pem, TR34_KDH_2_PrivateKey_Pem); @Override public X509Certificate getRootCert() { return rootCert; } @Override public X509Certificate getKdhCaCert() { return kdhCaCert; } @Override public X509Certificate getKdhCert() { return kdhCert; } @Override public X509Certificate getKrdCaCert() { return krdCaCert; } @Override
package com.clover.tr34.samples; /** * Sample TR-34 keys and certificates generated by Clover for test and development purposes. */ public final class CloverDevTr34KeyStoreData extends Tr34KeyStoreData { // Generated via https://github.corp.clover.com/clover/go-pki-helpers/tree/tr34-test/TR34-sample static final String TR34_Root_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDdDCCAlygAwIBAgIQTq9Hb668e0nzTs0Y45MgBTANBgkqhkiG9w0BAQsFADBU\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEhMB8GA1UEAxMYVEVTVCBDbG92ZXIgVFIzNCBSb290IENBMB4XDTIzMDkwMTIy\n" + "MDAwOVoXDTM4MDgyODIyMDAwOVowVDELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkNs\n" + "b3ZlcjERMA8GA1UECxMIZGV2aWNlb3MxITAfBgNVBAMTGFRFU1QgQ2xvdmVyIFRS\n" + "MzQgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANeeAxCc\n" + "XTnUkxgp2UN5mZHS7sv3KaJ7iWqo16KxHlAKpC+DaN1e+fSFaXlI6tWs9VWqDuuv\n" + "H8xBUAoIWaPE/Rm7trgmYNjKtCs2v2QLAsq6rzfo1v3SjO9DjuiuZt9W7BpqTAOb\n" + "fzNXMb/W0gwL9cRn6Y9bMioumnW+Emhou3u4pU3wxIrt3zjqpQ2MhYBadWBb1ZtF\n" + "919NgI7H91MntGVrOOoteXPSK3ygWowJ2K7qgfT37pX13N1duZserHWZXjNU7GuC\n" + "NoNDnatnxBKRnoQLc3G47gNSVr6PGA0T4PzE/8j/S+OV2kLTU7JFQoPi7hXUHeCw\n" + "D0a1yiUVDzF8B+0CAwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF\n" + "MAMBAf8wHQYDVR0OBBYEFEnohVQIi1LkEJlHSASkhosTKgiJMA0GCSqGSIb3DQEB\n" + "CwUAA4IBAQBOLLkBLVfa8cggTa4gx5WCKSucNM/1t81fC15r6B0/VjUPwKrRpd+T\n" + "akwsJ3ScjSOWk6rfWjzaXQMJfH5cKj2bmnSLPKYnVnX0UiWlckVKTGhl7oK1+eWE\n" + "QvZmPKD6oRKcsXjmi6E2ZdJEb0HzEm78eoa2Q61sCmL+aKVPBtctUuPrD84ETxd9\n" + "hNRdrzXGVJesg58q4ULGwd9qC/6eMDYbHX17E2Lf2XwM9/Aq6ITNlv8/fcBYIFPy\n" + "AVjPD+QqayNyC5LsLRGi9a76h8FDVHHKpMxg3vxbtiXIJ7Hg5vPrQWcFOpj1HQyC\n" + "L4aXPicIuSyrg3b8M1WSp24bJkMptmhj\n" + "-----END CERTIFICATE-----"; static final String TR34_Root_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEowIBAAKCAQEA154DEJxdOdSTGCnZQ3mZkdLuy/cponuJaqjXorEeUAqkL4No\n" + "3V759IVpeUjq1az1VaoO668fzEFQCghZo8T9Gbu2uCZg2Mq0Kza/ZAsCyrqvN+jW\n" + "/dKM70OO6K5m31bsGmpMA5t/M1cxv9bSDAv1xGfpj1syKi6adb4SaGi7e7ilTfDE\n" + "iu3fOOqlDYyFgFp1YFvVm0X3X02Ajsf3Uye0ZWs46i15c9IrfKBajAnYruqB9Pfu\n" + "lfXc3V25mx6sdZleM1Tsa4I2g0Odq2fEEpGehAtzcbjuA1JWvo8YDRPg/MT/yP9L\n" + "45XaQtNTskVCg+LuFdQd4LAPRrXKJRUPMXwH7QIDAQABAoIBAQCcrGejuUsQi4N6\n" + "6mXB3ukVCgWU1fs94rBefWN7B2J0XNci40TennXYFN0oUTC6pRv77D89SJo9bDQB\n" + "pkGke65B9aF2vARhYyF5ySVXR5z2vKI3aQxXkZfw/9EnCBseLGYRZ63mbSYHo1M2\n" + "B53HPSWPWsZe8bBI8GYyKjPsBDY/Vf3uvgEnS7MeGqiXTtpBo0WBPrXcbu5GWO+/\n" + "ujmUyB7FWE2V+venTxP4vsDngtcrdhdw07K+vYlE6GWFsne44VT9qI9c3Qqs/QZ5\n" + "M2pzuuV9dm6nkZVTk4frI0FXh4H7n3Ir08qtw8pmQbms4nRXHorfluWgMnwOO/MN\n" + "Vn7MXzFNAoGBAOmpCDMin9AgWjb3Q6t6lllJLxbWqF5mLv3eergOhDS3dvEQIIIw\n" + "7HmHaoVnpcHXKVhHJZwgvjWzy3dD1ctxQGi/qxN0vTzpoy8uHKG6efyFHOjEFnD3\n" + "8uB3DiNvVQEDoXvDXow+pfbZ80PCPRZbYdt+j5gS84eQQvzHpK7sNMyTAoGBAOw7\n" + "XbpxzKElbJuDN4yisscG267ooQuEzANlvATP1dhnfPRx7JhKk0cOWVHq/sHrg7Z5\n" + "+g/qA/Q86Oi1x7qfDSfWy5X2nII0MVVQPVufTErxo06ammojDzGQACTWjWH5l+cG\n" + "uCsMo4Ij2t0/Ab3p/Wi4jkQ2mIb0ypTvE58ivSl/AoGANRdWKKBGZbjkJrcaJh1t\n" + "ig4J6AuQKBrZtI9XnPiXa48ANJfwewR4xshRGMzLKfckis1nq0j5TyRyJ8A/FMG/\n" + "280pJvuQgAWqMW8tzEWdsBXi0rSzUKnWAtCqYrzKOLfFemSS2BToCuXM02mQDcNn\n" + "wcLJB8nOkc/imKMYNTKwcIcCgYAFpuX3MAHVWS/gCKOrmbjtShy3cplnzSWUbzqw\n" + "YsibBN7YemFOw3oCmTVJ4HV37kqYcxKojtDJZyurZa4BqQyHh3wXem8ELnt/rwvI\n" + "xWbt5BokJ07Ke0xBw1A9kWSQk4gu3tpJLWQ8GN+Dq54/DPojJ0dAGo5LrE+sgIvX\n" + "ot0jwQKBgAlCkynsA1AeyuPZ/G7LXKzAGuCYZinDvrOwtpWNr0nQ/Ssj7UN9kg0/\n" + "rBCqZ+f3Nt3v8Scw9qwdEt7toemTKMgFr2UHa50tgFW01kcy8anAAJLO9CDgKIsz\n" + "T8hE9bnM3CWl4E/8jNCw3tIx8+xQruGZZ3GB8XsIWML2xzVziBaT\n" + "-----END RSA PRIVATE KEY-----"; static final String TR34_KDH_CA_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDlDCCAnygAwIBAgIQTqak5H7dM9yiy3fI6yraoDANBgkqhkiG9w0BAQsFADBU\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEhMB8GA1UEAxMYVEVTVCBDbG92ZXIgVFIzNCBSb290IENBMB4XDTIzMDkwMTIy\n" + "MDAzN1oXDTM4MDgyMTIyMDAwOVowUzELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkNs\n" + "b3ZlcjERMA8GA1UECxMIZGV2aWNlb3MxIDAeBgNVBAMTF1RFU1QgQ2xvdmVyIFRS\n" + "MzQgS0RIIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqH8jmFXC\n" + "FXIfo9EMWcvo6NDDkxtkSUwFV9T/ONkqEzydA16p/+Ja5+ythXTvXjMWXjfCpg76\n" + "83QSRASq2CV7VXIMAG/YosQWlbDTIniYcJn9naMBUoIIQ4nw6Hxs4x4X3IOi0c/+\n" + "80UIxd3lCuSh3Y6iDs08BUfe1g7XI0JGUrdEjL3VVD14N3fSNCxLiwsmbhcMjPPe\n" + "KpJdZB9rXpuxybHhvy1fyktOe+sXl+j+T5AfD3gbWjSQJfC5ylOS2b5jz56cO51c\n" + "T8RK/UWGHR4hwbiF+Of+HJKU6ZDLcDQ1XmUL1RC6c8QKW/Ziha5sbxlxmspendqR\n" + "ZQOLtLbTgTh4sQIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAgQwDwYDVR0TAQH/BAUw\n" + "AwEB/zAdBgNVHQ4EFgQUbeIyuJDjaE5J/WjddKCtqKMCQ4wwHwYDVR0jBBgwFoAU\n" + "SeiFVAiLUuQQmUdIBKSGixMqCIkwDQYJKoZIhvcNAQELBQADggEBAJ36O4R+sbAz\n" + "GResQmn66zoI+0OR0rHZbGvW5b/fjllGtn4L4CoyH+1VkOtBv+HEswGu/3Q4Chfg\n" + "Mo/rAX2gIHPqQhKlmETC/4wcSFp+ml6VC1exfsYjWggoWQ17NigRh8TMFBDHmxE+\n" + "PsdsKf8vzRYw603OYpAPKPiRotzCsMS25EGw+LbzT4C3peNQSz7DKWRB4Ynk6fj6\n" + "OPzWWOMHAtSufVQ1VUqUAqjxRbi78ze/iJf31cpTjw9IJUhRMZdYIHv6okM64QbH\n" + "HaewJPOBdsbwk+6A/6RT//gilj2i6SlIo3yAjvzFTWCeOPvgxI0pUV+DGCWSRHki\n" + "zqoixiFihpE=\n" + "-----END CERTIFICATE-----"; static final String TR34_KDH_CA_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEpQIBAAKCAQEAqH8jmFXCFXIfo9EMWcvo6NDDkxtkSUwFV9T/ONkqEzydA16p\n" + "/+Ja5+ythXTvXjMWXjfCpg7683QSRASq2CV7VXIMAG/YosQWlbDTIniYcJn9naMB\n" + "UoIIQ4nw6Hxs4x4X3IOi0c/+80UIxd3lCuSh3Y6iDs08BUfe1g7XI0JGUrdEjL3V\n" + "VD14N3fSNCxLiwsmbhcMjPPeKpJdZB9rXpuxybHhvy1fyktOe+sXl+j+T5AfD3gb\n" + "WjSQJfC5ylOS2b5jz56cO51cT8RK/UWGHR4hwbiF+Of+HJKU6ZDLcDQ1XmUL1RC6\n" + "c8QKW/Ziha5sbxlxmspendqRZQOLtLbTgTh4sQIDAQABAoIBAQCDG+Ljnx9VNqcd\n" + "/gVBPiRuPDtiFTdUvV2O+YLahkhyDYETZS6cmFIqEwT2SoYTY2ctSvAf7Joio5eu\n" + "637Qj2HHm+Vw1ZbZGAGG2r9/HB1pyLkKVxMpU1sAyq31CRRlKT5h7N/dqJ32RypL\n" + "ZJzbfAnjbx/0qofgiAsBvyxyGBjGNOc0BLZLa7fIOVcq+G+SjPuWFFy3ehCcoko+\n" + "bW+zl8/21x1E8VEy4R0ftEMqsehFpUIV8Fbgj4yp+S1j6aFZ/kJqX6PdxbIyaVaf\n" + "UTGrLThHKaqYZWSXzgEv+M7e2nwBEwnUDl3KUchxsFSzNFY6zvTlT12s2xTIKa2m\n" + "gYKU5tXBAoGBANaOSHlshAdrDm/UJCREr7mTJZdpdrXQMKv7s0p0QRQp/loSms+N\n" + "+Fl35Sv7mdVyQCRJu2o5lGAto5y6YBe34NHBAcYwDU3fRBrDUfVQM6ZukSkQKgRC\n" + "0lWVYzv8hQBjyX2YxmlH1cGbflJ0Zf3KfVzxQOure/r4RR85Ej2R4AVJAoGBAMkL\n" + "PrvVZqShnVxE5SplvCgmXEQoh7l4ePta+utuX//ecnbC2AAwGoLVntK9wLRUhF2c\n" + "tziOIIUksdwunR+32RSclK6pEMblwKVz1D7Llg+7a+iZH5TzWwHOv65jL8Mro4SZ\n" + "+XQ+XJohW6l/yQKE9P+KljCqTqKynH0jhO76uqApAoGBAMQaxnldSwvwuQBTmTkh\n" + "IrBuozRSa/NgN6xqYYSS34zLmTTAvokozS8RXAEodYHXbHL+hXNg75I9BMdSvlPP\n" + "eIifbby03OQpRnljvzyGMr9TXhB3OsAsR018PnhspTAnBNpsUiWWR/Uu53X79+DR\n" + "PGZACEOfuLE6TQttwZNPCsApAoGBAKEnyHPdDlhtzKxH9cNUpc0xYsioDJQaBDDI\n" + "r1bFtWJvuCWG7orIBJhYEOYxgSWMkkZP93b4Rw0zavdqzjy8rOCe23hewboONazq\n" + "+noTzAh0Xn2nMO+/W3ZJetGZZJH4iy0iGBqcWrKahtWKP2ErnxCw0M/V1Q8KSfLt\n" + "5AOFLNBxAoGAHmCkNBjctPfG9Sl2/Tud2ERYiNZimSLdKn3UnOpY9W8Y97r6SBtP\n" + "qj8vDbVrhPwudEz8GfXsbUmwxP9LLqXndjURAosAtE79cdSckJETRbnAJBpZ756R\n" + "CDeQuo9S44CIbt0B9EfcGGN1uWKEsrfm7NdAWny5WH83y9T6jPsKOcQ=\n" + "-----END RSA PRIVATE KEY-----"; static final String TR34_KRD_CA_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDlDCCAnygAwIBAgIQHIcewFfOHCCMjreEjAm3HDANBgkqhkiG9w0BAQsFADBU\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEhMB8GA1UEAxMYVEVTVCBDbG92ZXIgVFIzNCBSb290IENBMB4XDTIzMDkwMTIy\n" + "MDY0N1oXDTM4MDgyMTIyMDAwOVowUzELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkNs\n" + "b3ZlcjERMA8GA1UECxMIZGV2aWNlb3MxIDAeBgNVBAMTF1RFU1QgQ2xvdmVyIFRS\n" + "MzQgS1JEIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzSvOA0+t\n" + "J/h2/6mZQw/s/WckpTEu6dAmi9LqtaAZMdT+0bjcPYKpLSFJ8l0p0lLOiv6OsEVd\n" + "n7kb+N5hCOpsnV1gWW1L57VSpIdBlqdPD6PggUPslu+9gxDDbyCIrvET36W628Q2\n" + "Q+nGwZV1muRU81SuR6G8Wopk2nruqLlTcR3+cnv683eQdsYvvq4mH0+wL4Sc3Se/\n" + "wIuhwy3IimZyZLlNKmZ4cXzC/qnZKEwTumTkDX0WQo3dRTGL+D+1CeuwuKIO2HeG\n" + "KjGCTWvw0xyP3IWDotEh9FJImV+9G0xKphMdfT5GJfj/+ix2J14qqvsZgQbLlHbo\n" + "S/kqwZOGZAwZywIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAgQwDwYDVR0TAQH/BAUw\n" + "AwEB/zAdBgNVHQ4EFgQU11VYe+bdyaYUH4MF8MFoJvdaOFkwHwYDVR0jBBgwFoAU\n" + "SeiFVAiLUuQQmUdIBKSGixMqCIkwDQYJKoZIhvcNAQELBQADggEBAIAEIodvCDnt\n" + "6R0OthdfOOgP9LNbkrvliitAiN4MO3U5WKvN9WAVreTMoeymYe5gpcZ/eEJHByWX\n" + "ocVN/U/dmMIAuloVknASYTijfcswYdqCHMvaBzXJyM9vZCp+TjLeyg3rpyJiru3E\n" + "Gfwrc9yzdvX0VOx8a4FBWIDr3/hrl829Re096Z8mVuBSyveF39URHuE+WWA+arPK\n" + "S1xt2nbN2Nfn7ZefcanuAmu6+0WnY4JAnyq9A4O4yrQAsRO8+2fTl7lNrOiyT28a\n" + "t1PtYLjhr0WTNDZvHhfwkolIwJJuirsLkZRuG4VAV2tJ3ZBypg6g1sY8zZDz3ZJJ\n" + "Id4Aht1VESg=\n" + "-----END CERTIFICATE-----"; static final String TR34_KRD_CA_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEpAIBAAKCAQEAzSvOA0+tJ/h2/6mZQw/s/WckpTEu6dAmi9LqtaAZMdT+0bjc\n" + "PYKpLSFJ8l0p0lLOiv6OsEVdn7kb+N5hCOpsnV1gWW1L57VSpIdBlqdPD6PggUPs\n" + "lu+9gxDDbyCIrvET36W628Q2Q+nGwZV1muRU81SuR6G8Wopk2nruqLlTcR3+cnv6\n" + "83eQdsYvvq4mH0+wL4Sc3Se/wIuhwy3IimZyZLlNKmZ4cXzC/qnZKEwTumTkDX0W\n" + "Qo3dRTGL+D+1CeuwuKIO2HeGKjGCTWvw0xyP3IWDotEh9FJImV+9G0xKphMdfT5G\n" + "Jfj/+ix2J14qqvsZgQbLlHboS/kqwZOGZAwZywIDAQABAoIBAHu3NExu2PzHKApV\n" + "3CLCEadjcIdjtuQqLXQWxIysc0THKLiRfcxhY13hOtO4NaWrZPwPLz8/NItBdYqF\n" + "nYFgygnB6n1CGIkpnyGypWwQiu3lZVTM/natLVtA2nfB6GmE2PT83EX0dLxS1RSZ\n" + "6QZzNH5dy5FKB2eZF+NeSVbYGWaVGD9l7Uy5L87zFOtFUVUPan3ONPbh3sPZA6mL\n" + "4FvaOcuNyJp6L5rFXitEC+6JdZyXid4o8xfG4p8+0JqzuDaTsdzNPPjuFVkpxBLy\n" + "8mWtGwThwvjGzpvBc7P5a5p7IyYWDpCEP4EmtMwgbrySBpgPKx1nX48YRtNIg+GO\n" + "uLTTqbECgYEA9/kOXiO05d9LBJofg6bIF4YI5r+SaddM2uW350AVVBNNhysD9Ixp\n" + "zQb2/9iBIPW0CxW4q16DMUktkIz20VKAHe4KqktbotTXyEkjRM2PPrr2DOssWR+J\n" + "CxjRi7UzdAE4/ICNlo3g6TRWMT35Jv6n+oCbsYyi6Am7qqbE2YH6bAcCgYEA09AN\n" + "OjlmxzKtPqpXLbUyxoghMed8cvyJzxNcZV3jyLSXAcnVAgeH8tCsY5Nc5ecOUq36\n" + "Ety4vBaKVorolKtVLrBtA8floEBhWYpzax7VJ3OKq8GYbafDX+eF/pXmevwDVotB\n" + "Cvo/kQwaX7lwZS4sJ4k4CQ4WRaeTB3hE1Vxl+x0CgYEArawVUAGaFNVK6TI4mDAb\n" + "O754RYQuu0o7XaQ+JQxQ482RIvYRkxk0kJAsNgwghEERlCHmcL+FCuPBsdfIldo+\n" + "OLgbaCHXUDfZ2UDAHtQJW1n+MhYTvWfEx6zeNgb2vmyMyOwQPj2oJCyvoVVSRulc\n" + "JKomYTeqcPFAKskaXWwXQ8kCgYEA0gdWZmqu0E0e3qmX4nnvTE+F4u8wRvDFUbFY\n" + "CCeui8EOj7Zr4iRHmO10UxS3pDyVxkQ/WV7GS7NqH2CEOY8e2zoUDxCzUFEmdtxD\n" + "kG+1WvZGBgPkuq8Em19/Ta+kKEUmpjVVHKaCS7idmlfN7HZ5UAbPqqLuUMlWkKyg\n" + "TJTfhr0CgYAdqiZlltOz9pJ5ZBCtduuohIc9mc5lDRabeKn9SXhPBOYZu2U+e+7a\n" + "L6WIX2bTtVq6B5qVv08/frdrBh5gzDig+mTiQxs3oQqersj5Cab89ruHVSoBYglr\n" + "/Zawxw4blDLa/R507/ipeFF1Tl2fxdN3s79/GVuoRE0LPH7zWnBsmw==\n" + "-----END RSA PRIVATE KEY-----"; public static final String TR34_KDH_1_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDcDCCAligAwIBAgIQEt6WKvHM910o6MgARZ8UyzANBgkqhkiG9w0BAQsFADBT\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEgMB4GA1UEAxMXVEVTVCBDbG92ZXIgVFIzNCBLREggQ0EwHhcNMjMwOTAxMjIw\n" + "MTQ1WhcNMzgwODE0MjIwMDA5WjBSMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xv\n" + "dmVyMREwDwYDVQQLEwhkZXZpY2VvczEfMB0GA1UEAxMWVEVTVCBDbG92ZXIgVFIz\n" + "NCBLREggMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANG3eq/n2Y9N\n" + "W+unTuzDoCT9XrHmLMukpM4qL4NCaJgBS7lXpcMBc7s9I954aw0TUKWBYDtgF6gv\n" + "s8DfMYcULW0/sH0LGVGBQ/dwUWY6vgfNfSDhtjGqEnl/JA0lwioSb7ZbxJ8pTv1H\n" + "F69GaBzkvYAbDJUcgDR5bEhCBxpel/Go2OzG3HknfVy1zaAIe9Z4z3FZ6Gp1e203\n" + "YRJjuaEhei8WsnZeUo1gVH8p3xDs9TrQsJTsS4E3IZukwemXF2dKMKgDGbo89QIc\n" + "wriJRhsDPAjvdkwCryhjCthjT+CcYkeiihSuTkrZbqSB3xU9ZNikI2aOs0suN0HW\n" + "su1+ZQppHz0CAwEAAaNBMD8wDgYDVR0PAQH/BAQDAgeAMAwGA1UdEwEB/wQCMAAw\n" + "HwYDVR0jBBgwFoAUbeIyuJDjaE5J/WjddKCtqKMCQ4wwDQYJKoZIhvcNAQELBQAD\n" + "ggEBADD96Ckbo9UFvCjZb0fMUHBbwpbZVLze/LUwxuQ2NOMDLZsP6TDtMYXMeeWN\n" + "+/VpuAmPt/2TwshUA6xuCtxV0XySsxMAhy77csGmfsA1dr0plYiMfGz0o03a+fcm\n" + "eTSO3GgCf6nJoH7Dxhfb0m4+CYIVlbvXG/C2sak98/orhux9SmjkfJ3ZtY4fYbp+\n" + "QOsMGdM6TZdXwjuG3luEVwUqrxMqLHpgJnf2I8jP9cNRvMXE9npoSq5v1MfWo6LG\n" + "WcbRVOvHwGPSlDzX1wmg+r99viY2LuHvSMmS90fs+XlxKIWJDpd20vY2UQRNBOn/\n" + "x71vA+0//1su6sE0LtPenoz2eFQ=\n" + "-----END CERTIFICATE-----"; static final String TR34_KDH_1_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEpAIBAAKCAQEA0bd6r+fZj01b66dO7MOgJP1eseYsy6Skziovg0JomAFLuVel\n" + "wwFzuz0j3nhrDRNQpYFgO2AXqC+zwN8xhxQtbT+wfQsZUYFD93BRZjq+B819IOG2\n" + "MaoSeX8kDSXCKhJvtlvEnylO/UcXr0ZoHOS9gBsMlRyANHlsSEIHGl6X8ajY7Mbc\n" + "eSd9XLXNoAh71njPcVnoanV7bTdhEmO5oSF6Lxaydl5SjWBUfynfEOz1OtCwlOxL\n" + "gTchm6TB6ZcXZ0owqAMZujz1AhzCuIlGGwM8CO92TAKvKGMK2GNP4JxiR6KKFK5O\n" + "StlupIHfFT1k2KQjZo6zSy43Qday7X5lCmkfPQIDAQABAoIBADUWazpISKyb+p7m\n" + "1XXd95YlhWknSUOrxARkbW6eyvdfrJmYdF+u6GsHiSLx/LdsokejPocJRjPPD4PN\n" + "fC4jj3ROYRDmVFxripcCmbh1OlGjVP+T45ki4lZbNvcVDde0nw7coCNiQ5qd+oLm\n" + "IcjeppHdRwwgENw3uI96F243b+M+U1bmeYucL5hYYIh0W4juRpiAQUqYDmNTtGt2\n" + "DUH+ivs5FxuMVs+k/JciVbaMiVr9hs/FFY1p9qdT3jyiIKNUI8ScoX8/cefzW+wL\n" + "wNIuyRvPhIE2mkEIRGt3UHZz3pOqpWz0Yr+eluNPi5kAB0aEFHsDkx7fLVhXTJCY\n" + "SR2KYQkCgYEA9e3Ml9vjm78j3M75OcXWNxTDhbueQ8I+b3jEHilIOwg0w3U6uQDq\n" + "sXu0LA8u7DRqdIxV4JWoQzfX8BE7FXaB6CCGZzk5NbJz9WOGYq7zIQvGvUw6OzYN\n" + "JmcJKFTbyJd7IU7A5S/vLu4S/8+aGVpHWUU4TNpmNEnrFPYShem46zcCgYEA2k4M\n" + "gCVPEMuV8G73bsuB26D25OBiW+DjCSE5QgeLhW2d+HA4RZLR+N6gja5ZdSRKfh6v\n" + "tD2Q18P1OYibQUcXXZirynxPIBKgMYzQkeqqLeXpDK9+dELI3JO8iyQc3Jqf0NiK\n" + "QXKK2MI3NsnDgrJ/jj26ysQSuZ3yo71DqbVTyysCgYEA8fVvyK0YB+ELyLB99kBW\n" + "HUU5hTbtZF8VDJl14vLc1O+i8fdBuklTnyFFR9/8W3rKjjaQO3Ei5ldoBhL93YUG\n" + "FLsDYUWkqtcTTYgI7MiR/p5Wf2IjHKR2VaUkFmE/B+E5zLBuCk+Z9MNZQAQh6fWv\n" + "ov3+gWaTDbj4KFxeJxCn1gsCgYANq6WMwMlau+T/0XMdNRFEt6e+XW7LYiHViIcV\n" + "Y3ORP3QNAroDYVZUx1w2gxyHAWbIzxMhrllLqbHJkIxoYhNMgSsA2xf5YjE16SOG\n" + "f7N4fFVDvhmlHimF5pp//BrylZw8b9L4ljurpz3d6HSd0p+6QJNZ7z1c8k8ngcqi\n" + "7f/5UQKBgQC+/nN7ErSzAY0t3IAbhG8SxKoUrsgU+5WFEDTCuO/qnvXXQIG1VZZv\n" + "SkXt/EdTUsepE9YNHTVFGsGYV+Ctu/lbwVfrssi78dCsCr6+hAA6NznG4f8RoYSJ\n" + "0HuR2t8TorC9akETtuE1AKXoofITZVx+OuSocIn7em+cLzuZ7+38MQ==\n" + "-----END RSA PRIVATE KEY-----"; public static final String TR34_KDH_2_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDcTCCAlmgAwIBAgIRAOlCYfqGO4D4ER57Qy5tGwswDQYJKoZIhvcNAQELBQAw\n" + "UzELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkNsb3ZlcjERMA8GA1UECxMIZGV2aWNl\n" + "b3MxIDAeBgNVBAMTF1RFU1QgQ2xvdmVyIFRSMzQgS0RIIENBMB4XDTIzMDkxODIw\n" + "MzYxNVoXDTM4MDgxNDIyMDAwOVowUjELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkNs\n" + "b3ZlcjERMA8GA1UECxMIZGV2aWNlb3MxHzAdBgNVBAMTFlRFU1QgQ2xvdmVyIFRS\n" + "MzQgS0RIIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCacdeuY7yK\n" + "Z8z33EqrrAxbdQLKvydy281qjLr9Rv5Gcf29m93WftqmDMSZF6buX8CGADRcU++f\n" + "17Ab2hXzkmnBItmnrs0bOtdXVqR3l4SaJM2V5fMYTFGJiBcrwdw3h/vAzU707ftb\n" + "3N04SJKR3xGqjCCqrDDKghiRkbLiOhi/oiDOAgXXZj4MM4x2/70Q6ikMSpLlsdix\n" + "yMnW8hmB5upBmodPV5Z0FAJu4lYwBNKpENz/34UEO9CwRje4lGfidmF7Zhg8G8HA\n" + "2BZIYRJqnoQRlJwIoR1+9/FAgEoKATEJV/x/4XxAnb7EtP29NlEhAUOEJufPGSpV\n" + "urhhRJeTJ4OHAgMBAAGjQTA/MA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAA\n" + "MB8GA1UdIwQYMBaAFG3iMriQ42hOSf1o3XSgraijAkOMMA0GCSqGSIb3DQEBCwUA\n" + "A4IBAQCE2+Bb/FzbnO15AJWoRpkJdLGdz3t+a4Q5eQEvSVTJHGR1lurjafn3RD3w\n" + "cRzfq1Y3iqIjgfwSdV7psM1hw2YD7z5Nm370YTNbox+QTNbyVQBWMh5X2ht2yR9G\n" + "tNU9MWMc75XIbU5dU2MdNmeIOx9Oco0NOfqAwmt3Bin7zlDTy3LMjSAjX8vut4Vm\n" + "G43iGj80kT3TIy4cAY+fA540ThdVl+n3+Ur3JfbcRMytbq+k2JIhBG1ec6o+6sxY\n" + "ZgGgDJhsPz1sQpgpsMfUwkZw80Jr4ZgZgm9KSkmHT5lCl1mbUHyJeXx9hof6Rd88\n" + "ZE5gnJg8yjk6rc2s6DIcTn1tEkTh\n" + "-----END CERTIFICATE-----\n"; public static final String TR34_KDH_2_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEowIBAAKCAQEAmnHXrmO8imfM99xKq6wMW3UCyr8nctvNaoy6/Ub+RnH9vZvd\n" + "1n7apgzEmRem7l/AhgA0XFPvn9ewG9oV85JpwSLZp67NGzrXV1akd5eEmiTNleXz\n" + "GExRiYgXK8HcN4f7wM1O9O37W9zdOEiSkd8RqowgqqwwyoIYkZGy4joYv6IgzgIF\n" + "12Y+DDOMdv+9EOopDEqS5bHYscjJ1vIZgebqQZqHT1eWdBQCbuJWMATSqRDc/9+F\n" + "BDvQsEY3uJRn4nZhe2YYPBvBwNgWSGESap6EEZScCKEdfvfxQIBKCgExCVf8f+F8\n" + "QJ2+xLT9vTZRIQFDhCbnzxkqVbq4YUSXkyeDhwIDAQABAoIBAEHscgnIHMRfRkhO\n" + "Sbk5eRTYv1ZXfbkzRV1DsNVHpmXfZlW24FwcTawvKwPF6sU5Le6Ey9TVJyVtZYid\n" + "8FzFlEqSW6GNpZMH7L8lBpLdpAY/y1k+jCNFAFDaPDm7SAqUCsvjVt6Jbo9pmSvb\n" + "HmUReHL52T/AvBrUqTQJoveZoNK68cyq9Uz54oEvyt1WrU7zaNiFGpH90Q1Qhb2J\n" + "Nlpjihpc6syqluVruYND/bJm9DJGqMLdlS6uD6fXp5aCGfixwvndLq1h6TCzEXLf\n" + "HcL8elN60SIZXUKDKPEDIQQa9jzBx6eqThErCvr7lZ6+YNqIx4F+2nkJdoZCrXN5\n" + "9a+f7fECgYEAydySZAEN/bIUlwXvN04x675rJtc4ih++dUrT7QrLouzhMz4wdIwM\n" + "RnV3/i/vkQoec1zjI7VETKlfgRDlicFjgShiyz74KJrUxmgvrfQsgO9wkNKrtAsm\n" + "936Qizh5+3WjuAPf/xtZhk31NVDR8v5IJJEDl5Miv47MAJxiCv5rSvsCgYEAw923\n" + "lJYzgRjjKdBMOFNEliVsmWaPrnwQDKKtJ809dq5THYwK9/Taz5Xx2SQBWxZF06/Z\n" + "efW2IqhNAza4unyNmVTcKiKiy/ziZwLMVl5gBudzrFuVnxSaDd7kCAlL9dTJ17dq\n" + "sf2FadgmqCvIlCgpkodi+HSXfCYdJ4rViyg9g+UCgYA4h4WTbdwuLJ2pgWbxVPuT\n" + "6jp1oRXbUHJ0xGS+4CQQ10dlo0fMi5+wZ5sX2vK66luGsP+G829SDKiLK2Esh7TG\n" + "6blo85RpQprNiUW48EU6QlOCqwycmfbqnk36PvGiItqbYLJs7YrPmqtNp/lzlBQ9\n" + "8UJRQ0oa3PFyRlkKfR8s2wKBgHqmiYH7OI9b1UxmyoPu6KEZGFNLHShHOgmfiMzG\n" + "wflimluDSY8R/j9FhyfRWyP944X2tTmg+wfi2i7sAmuM+WKN+DxOaiFQ3zlgUDK5\n" + "cGqCXzYMN7phPUL4U1UQ9Ucgk7CIg8Cnn/ayyyo+GKFmMPo322r4H7A3ccRENQqq\n" + "DTNdAoGBALKefyenQOTgjdIXlDICTIM4VRAMzrGI43wnIPKE6DEZwxhzt0jE5NYu\n" + "jWpTbaTuduIC6/b0jbiIBDefrOh/Rw4iVicXxC4lJJCoLqrNdLBfqvt9JAvBndan\n" + "KlXNyoIMUktye1+fywLHfmU+k0tWMm2PacdD7V4aUpN3G1qQeIwt\n" + "-----END RSA PRIVATE KEY-----\n"; public static final String TR34_KRD_1_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDcDCCAligAwIBAgIQbCpMOGMtYO46ksi7B0ziSTANBgkqhkiG9w0BAQsFADBT\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEgMB4GA1UEAxMXVEVTVCBDbG92ZXIgVFIzNCBLUkQgQ0EwHhcNMjMwOTAxMjIw\n" + "NjUwWhcNMzgwODE0MjIwMDA5WjBSMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xv\n" + "dmVyMREwDwYDVQQLEwhkZXZpY2VvczEfMB0GA1UEAxMWVEVTVCBDbG92ZXIgVFIz\n" + "NCBLUkQgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALhilgrs5YCt\n" + "DSiWa/Z/TX96qztN0dLlyh7rYimeBkEpEU4kJwWogRrt6CGIQ1+guSZLm4QtqWzn\n" + "bR72bDSJHLArnWi+Dx+9AHMK1AaZUrf75eC/yh5yV/sI0YFmnWp4DjV0AtGKgzDm\n" + "cjgQloIR2zrUrPXihXSUcwxJe0q/IqrMEdQ+morvZ2w+8Vlo1WszyvknhrCUWzKg\n" + "zf9DZ+9BG1fKREffS2SUruBHCFkQeXDFdP3d1RtgZznWGXQhwUXa5jkoFkR4jQYK\n" + "R8Lhj8v9YEbWcG8L7lOMkCZfRWeGzuQnjKRS9bx6D67gxvY2XJLbmfov4HNVkdxS\n" + "O68xEd8qI6UCAwEAAaNBMD8wDgYDVR0PAQH/BAQDAgeAMAwGA1UdEwEB/wQCMAAw\n" + "HwYDVR0jBBgwFoAU11VYe+bdyaYUH4MF8MFoJvdaOFkwDQYJKoZIhvcNAQELBQAD\n" + "ggEBAKdiYCU87sxKtldqs+4bNrSIXEwc/6XKCG2nCCToGNYOE2FApDWBZcOUcSEd\n" + "Lp0n7FEa/gLWVr5J/EOUkDp+5gAgmtbyvHptla8ThxVWPFHCXXbo4qlylfFwcXF1\n" + "OG8I+mwggUSh9DFoq27JUJApjaDcVyQ2Ywvdq0EcITYgrrZKZrqD7JYTEYmVXtKq\n" + "B4091HxtSM9vWophBudJDfK308x9fj+PM6AZqWRG7XCMShi3tVERiImTw0Pqn2/P\n" + "K0aEafxpvTRJh0kjsujX4HteBGXzLjjikfyjJKGz6Fyl5A8T9VAEFObqqZQ6Sa92\n" + "wMMs9Ow1xNvbr1cGImewoVhyBJU=\n" + "-----END CERTIFICATE-----"; public static final String TR34_KRD_1_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEogIBAAKCAQEAuGKWCuzlgK0NKJZr9n9Nf3qrO03R0uXKHutiKZ4GQSkRTiQn\n" + "BaiBGu3oIYhDX6C5JkubhC2pbOdtHvZsNIkcsCudaL4PH70AcwrUBplSt/vl4L/K\n" + "HnJX+wjRgWadangONXQC0YqDMOZyOBCWghHbOtSs9eKFdJRzDEl7Sr8iqswR1D6a\n" + "iu9nbD7xWWjVazPK+SeGsJRbMqDN/0Nn70EbV8pER99LZJSu4EcIWRB5cMV0/d3V\n" + "G2BnOdYZdCHBRdrmOSgWRHiNBgpHwuGPy/1gRtZwbwvuU4yQJl9FZ4bO5CeMpFL1\n" + "vHoPruDG9jZcktuZ+i/gc1WR3FI7rzER3yojpQIDAQABAoIBADJnKLLl3TrWk2FD\n" + "9VFVrV6qrsIwXKo1DJJ1L8lGnFkVm9hrg4tFa71ryWfZMumiKtqwElwIi2bswGSV\n" + "YjDeRkxWL9phEgtQBB5umFURdo46urU8WEkIYsqJt5OS9HcVSHUOOHMFVSV56UEw\n" + "L6Rwsyga2QkCGg8rQWPbdmuRYi2j0j95IFvszn7kzQZ6hcoEdbhedYX85Ij4mgR7\n" + "ydeli6SAMQ8dRIbsOFhdf07DvA5st59lRTDeC/kyYMN6SZHRl7Vr9cvsTVawJb7v\n" + "v94Q3fRqzq9rB/JdHjVjjx+NM97sc7azZFFFVtrnlOG80k4lMIZLnjH0ZMpXrkY6\n" + "4Vv7p6UCgYEA5uLIa9+vopgpgTR4CUmqAcDh6EAzAOyIRTxag5c0i2Tz+x4ffc2Y\n" + "6s7Rs9x1b8ypr+z8GKmsjhEyxlToFEG0cZTBQzQEMsQ89jJbbLz8pSglS1hM3W4Y\n" + "zDGhiBtiJRpvuA3ZJN0No09cYDbH/y5ZyM6AAgwK1uD0vu5eTvoP83MCgYEAzHDy\n" + "8rVoHfF82pHrmzz8NRhf8SuDI+rwm+ThDnphteMXmJSz9ki8lljaF2T/mMsCHn1B\n" + "o+R5WTg1b/0+YGEH7OAjKNx+6K7BCZ1dA5S+dHtZjCvp2Bp3UL7FtK3dptQEL3t+\n" + "0SnSFBZ9lpXLj8dQNTwISVM8LD7vOBtVAOZftocCgYApFqzSPcGU7v1b6AmApaJi\n" + "o3/QhDRPcsihgaceCfeo4vNkeizih4cyKlI5bv9bQRHlpAgNH4z8z2S41P1kNXk2\n" + "SWHHYudoXXH34mhQxqUzgxx39yPeuCwjkqWLgkwKDFVbbON64vf9Wy82VCltaUND\n" + "MDSpqJj5OplzrRoNdgUGrwKBgEPHrsSJIFvNFHfiqRpuva9cxXJP2sqtudf1qigC\n" + "qyKCh/AuXPvqYZv3GVdoRNWDeNBi9sA/n3vVBuJ6M5QAl4ART5bcg7bhOV7WrV/i\n" + "kMJNowK2DHF5VNWQajvc6P/Gixyy9PijxOKkEj86qqKgkhcUMCsfTXPd6bHQXf5O\n" + "Yq1BAoGAaYsPFFv1uZJSDLb4kd5wW1o2AV2a5PhKqn71dCvYal6Dtm66jQnSvWSN\n" + "Jo7ewgPInB6FGUiHkG0uxCDaWxbqMoX0Gv6qhXP70TNg6PxTFZYQIcMOtjMWtfbo\n" + "JJbzKc5rgdHayNGWor9LWY7Y3gFASuItLuHLyI8n8Xx/zuaLxv8=\n" + "-----END RSA PRIVATE KEY-----"; private final X509Certificate rootCert; private final X509Certificate krdCaCert; private final X509Certificate kdhCaCert; private final X509Certificate kdhCert; private final PrivateKey krdCaPrivateKey; private final PrivateKey kdhCaPrivateKey; private final PrivateKey kdhPrivateKey; private CloverDevTr34KeyStoreData(String kdhCertPem, String kdhPrivateKeyPem) { kdhCert = Tr34CryptoUtils.parseCert(kdhCertPem); kdhPrivateKey = Tr34CryptoUtils.parsePrivateKey(kdhPrivateKeyPem); rootCert = Tr34CryptoUtils.parseCert(TR34_Root_Cert_Pem); kdhCaCert = Tr34CryptoUtils.parseCert(TR34_KDH_CA_Cert_Pem); krdCaCert = Tr34CryptoUtils.parseCert(TR34_KRD_CA_Cert_Pem); kdhCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(TR34_KDH_CA_PrivateKey_Pem); krdCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(TR34_KRD_CA_PrivateKey_Pem); } public static final Tr34KeyStoreData KDH_1 = new CloverDevTr34KeyStoreData(TR34_KDH_1_Cert_Pem, TR34_KDH_1_PrivateKey_Pem); public static final Tr34KeyStoreData KDH_2 = new CloverDevTr34KeyStoreData(TR34_KDH_2_Cert_Pem, TR34_KDH_2_PrivateKey_Pem); @Override public X509Certificate getRootCert() { return rootCert; } @Override public X509Certificate getKdhCaCert() { return kdhCaCert; } @Override public X509Certificate getKdhCert() { return kdhCert; } @Override public X509Certificate getKrdCaCert() { return krdCaCert; } @Override
public Tr34ScdKeyStoreData getKdhKeyStoreData() {
3
2023-11-22 06:30:40+00:00
16k
Staffilon/KestraDataOrchestrator
IoT Simulator/src/main/java/net/acesinc/data/json/generator/JsonDataGenerator.java
[ { "identifier": "JSONConfigReader", "path": "IoT Simulator/src/main/java/net/acesinc/data/json/generator/config/JSONConfigReader.java", "snippet": "public class JSONConfigReader {\n private static final Logger log = LogManager.getLogger(JSONConfigReader.class);\n \n public static String getJsonC...
import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.pulsar.client.api.PulsarClientException; import org.eclipse.paho.client.mqttv3.MqttException; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import net.acesinc.data.json.generator.config.JSONConfigReader; import net.acesinc.data.json.generator.config.SimulationConfig; import net.acesinc.data.json.generator.log.AzureIoTHubLogger; import net.acesinc.data.json.generator.log.EventLogger; import net.acesinc.data.json.generator.log.FileLogger; import net.acesinc.data.json.generator.log.HttpPostLogger; import net.acesinc.data.json.generator.log.KafkaLogger; import net.acesinc.data.json.generator.log.KinesisLogger; import net.acesinc.data.json.generator.log.Log4JLogger; import net.acesinc.data.json.generator.log.MqttLogger; import net.acesinc.data.json.generator.log.NatsLogger; import net.acesinc.data.json.generator.log.PulsarLogger; import net.acesinc.data.json.generator.log.TranquilityLogger; import net.acesinc.data.json.generator.log.WampLogger;
10,909
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.acesinc.data.json.generator; /** * * @author andrewserff */ @RestController public class JsonDataGenerator { @Autowired Environment environment; private static final Logger log = LogManager.getLogger(JsonDataGenerator.class); private SimulationRunner simRunner; private String simConfigFile; public JsonDataGenerator() { } public String getFilePath(String file) { String filePath = getSimulationContentPath() + "/" + file; return filePath; } public String getSimulationContentPath() { String folder = null; if (environment != null) environment.getProperty("myApp.folder", "conf"); else folder = System.getProperty("myApp.folder", "conf"); return folder; } public JsonDataGenerator setUpSimulation(String simConfigString) { simConfigFile = simConfigString; LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(); try { log.debug("Creating Simulation Runner using Simulation Config [ " + simConfigString + " ]"); SimulationConfig simConfig = getSimConfig(); List<EventLogger> loggers = new ArrayList<>(); for (Map<String, Object> elProps : simConfig.getProducers()) { String elType = (String) elProps.get("type"); switch (elType) { case "logger": { log.info("Adding Log4JLogger Producer"); loggers.add(new Log4JLogger()); break; } case "file": { log.info("Adding File Logger with properties: " + elProps); loggers.add(new FileLogger(queue, elProps)); break; } case "kafka": { log.info("Adding Kafka Producer with properties: " + elProps); loggers.add(new KafkaLogger(queue, elProps)); break; } case "tranquility": { log.info("Adding Tranqulity Logger with properties: " + elProps); loggers.add(new TranquilityLogger(queue, elProps)); break; } case "nats": { log.info("Adding NATS Logger with properties: " + elProps); loggers.add(new NatsLogger(queue, elProps)); break; } case "http-post": { log.info("Adding HTTP Post Logger with properties: " + elProps); try { loggers.add(new HttpPostLogger(queue, elProps)); } catch (NoSuchAlgorithmException ex) { log.error("http-post Logger unable to initialize", ex); } break; } case "mqtt": { log.info("Adding MQTT Logger with properties: " + elProps); try { loggers.add(new MqttLogger(queue, elProps)); } catch (MqttException ex) { log.error("mqtt Logger unable to initialize", ex); } break; } case "iothub": { log.info("Adding Azure IoT Hub Logger with properties: " + elProps); try { loggers.add(new AzureIoTHubLogger(queue, elProps)); } catch (URISyntaxException ex) { log.error("Azure IoT Hub Logger unable to initialize", ex); } break; } case "kinesis": { log.info("Adding Kinesis Logger with properties: " + elProps); try { loggers.add(new KinesisLogger(queue, elProps)); } catch (Exception ex) { log.error("Kinesis Logger unable to initialize", ex); } break; } case "pulsar": { log.info("Adding Pulsar Logger with properties: " + elProps); try { loggers.add(new PulsarLogger(elProps)); } catch (final PulsarClientException ex) { log.error("Pulsar Logger unable to initialize", ex); } break; } case "wamp": { log.info("Adding Wamp Logger with properties: " + elProps); try {
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.acesinc.data.json.generator; /** * * @author andrewserff */ @RestController public class JsonDataGenerator { @Autowired Environment environment; private static final Logger log = LogManager.getLogger(JsonDataGenerator.class); private SimulationRunner simRunner; private String simConfigFile; public JsonDataGenerator() { } public String getFilePath(String file) { String filePath = getSimulationContentPath() + "/" + file; return filePath; } public String getSimulationContentPath() { String folder = null; if (environment != null) environment.getProperty("myApp.folder", "conf"); else folder = System.getProperty("myApp.folder", "conf"); return folder; } public JsonDataGenerator setUpSimulation(String simConfigString) { simConfigFile = simConfigString; LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(); try { log.debug("Creating Simulation Runner using Simulation Config [ " + simConfigString + " ]"); SimulationConfig simConfig = getSimConfig(); List<EventLogger> loggers = new ArrayList<>(); for (Map<String, Object> elProps : simConfig.getProducers()) { String elType = (String) elProps.get("type"); switch (elType) { case "logger": { log.info("Adding Log4JLogger Producer"); loggers.add(new Log4JLogger()); break; } case "file": { log.info("Adding File Logger with properties: " + elProps); loggers.add(new FileLogger(queue, elProps)); break; } case "kafka": { log.info("Adding Kafka Producer with properties: " + elProps); loggers.add(new KafkaLogger(queue, elProps)); break; } case "tranquility": { log.info("Adding Tranqulity Logger with properties: " + elProps); loggers.add(new TranquilityLogger(queue, elProps)); break; } case "nats": { log.info("Adding NATS Logger with properties: " + elProps); loggers.add(new NatsLogger(queue, elProps)); break; } case "http-post": { log.info("Adding HTTP Post Logger with properties: " + elProps); try { loggers.add(new HttpPostLogger(queue, elProps)); } catch (NoSuchAlgorithmException ex) { log.error("http-post Logger unable to initialize", ex); } break; } case "mqtt": { log.info("Adding MQTT Logger with properties: " + elProps); try { loggers.add(new MqttLogger(queue, elProps)); } catch (MqttException ex) { log.error("mqtt Logger unable to initialize", ex); } break; } case "iothub": { log.info("Adding Azure IoT Hub Logger with properties: " + elProps); try { loggers.add(new AzureIoTHubLogger(queue, elProps)); } catch (URISyntaxException ex) { log.error("Azure IoT Hub Logger unable to initialize", ex); } break; } case "kinesis": { log.info("Adding Kinesis Logger with properties: " + elProps); try { loggers.add(new KinesisLogger(queue, elProps)); } catch (Exception ex) { log.error("Kinesis Logger unable to initialize", ex); } break; } case "pulsar": { log.info("Adding Pulsar Logger with properties: " + elProps); try { loggers.add(new PulsarLogger(elProps)); } catch (final PulsarClientException ex) { log.error("Pulsar Logger unable to initialize", ex); } break; } case "wamp": { log.info("Adding Wamp Logger with properties: " + elProps); try {
loggers.add(new WampLogger(queue, elProps));
13
2023-11-26 10:57:17+00:00
16k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/mods/JERRats.java
[ { "identifier": "JERRenderPirat", "path": "src/main/java/com/invadermonky/justenoughmagiculture/client/render/entity/mods/rats/JERRenderPirat.java", "snippet": "public class JERRenderPirat extends JERRenderRat {\n public JERRenderPirat(RenderManager manager) {\n super(manager);\n }\n\n p...
import com.github.alexthe666.rats.RatsMod; import com.github.alexthe666.rats.server.entity.*; import com.github.alexthe666.rats.server.items.RatsItemRegistry; import com.github.alexthe666.rats.server.world.RatsWorldRegistry; import com.github.alexthe666.rats.server.world.village.RatsVillageRegistry; import com.github.alexthe666.rats.server.world.village.WorldGenPetShop; import com.github.alexthe666.rats.server.world.village.WorldGenPlagueDoctor; 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.JEMConfigRats; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.jer.villager.CustomVanillaVillagerEntry; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.jer.villager.CustomVillagerEntry; 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.ModIds; import com.invadermonky.justenoughmagiculture.util.StringHelper; import jeresources.api.conditionals.LightLevel; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerCareer; import javax.annotation.Nonnull; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.List;
12,287
EntityIllagerPiper piper = new EntityIllagerPiper(world); piper.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(RatsItemRegistry.RAT_FLUTE)); registerMob(piper, LightLevel.hostile, EntityIllagerPiper.LOOT); adjustHumanoidRenderHook(piper.getClass()); } if(jerConfig.enableRatlanteanAutomation) { registerMob(new EntityMarbleCheeseGolem(world), LightLevel.any, EntityMarbleCheeseGolem.LOOT); registerRenderHook(EntityMarbleCheeseGolem.class, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-1.1,0); GlStateManager.scale(0.8,0.8,0.8); return renderInfo; })); } if(jerConfig.enableNeoRatlantean) { registerMob(new EntityNeoRatlantean(world), LightLevel.any, EntityNeoRatlantean.LOOT); } if(jerConfig.enablePirat) { EntityPirat pirat = new EntityPirat(world); pirat.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(RatsItemRegistry.PIRAT_CUTLASS)); pirat.setItemStackToSlot(EntityEquipmentSlot.HEAD, new ItemStack(RatsItemRegistry.PIRAT_HAT)); registerMob(pirat, LightLevel.any, EntityPirat.LOOT); } if(jerConfig.enablePlagueBeast) { registerMob(new EntityPlagueBeast(world), LightLevel.any, EntityPlagueBeast.LOOT); } if(jerConfig.enablePlagueDoctor) { registerMob(new EntityPlagueDoctor(world), LightLevel.any, EntityPlagueDoctor.LOOT); adjustHumanoidRenderHook(EntityPlagueDoctor.class); } if(jerConfig.enableRat) { EntityRat rat = new EntityRat(world); registerMob(rat, LightLevel.any, EntityRat.LOOT); } if(jerConfig.enableRatlanteanSpirit) { registerMob(new EntityRatlanteanSpirit(world), LightLevel.hostile, ratlantisBiome,EntityRatlanteanSpirit.LOOT); } } @Override public void registerModVillagers() { if(JEMConfig.RATS.fixJERVillagers) { registerPetShopOwner(); registerPlagueDoctorVillager(); } } public void registerRenderOverrides() { if(JEMConfig.RATS.enableRenderFixes) { //Rats uses a depreciated method for rendering. RenderingRegistry.registerEntityRenderingHandler(EntityRat.class, new JERRenderRat(Minecraft.getMinecraft().getRenderManager())); RenderingRegistry.registerEntityRenderingHandler(EntityPirat.class, new JERRenderPirat(Minecraft.getMinecraft().getRenderManager())); } } private void registerPetShopOwner() { try { EntityVillager villager = new EntityVillager(world); villager.setProfession(RatsVillageRegistry.PET_SHOP_OWNER); villager.getProfession(); VillagerCareer career = RatsVillageRegistry.PET_SHOP_OWNER.getCareer(0); Field tradesField = career.getClass().getDeclaredField("trades"); tradesField.setAccessible(true); List<List<EntityVillager.ITradeList>> trades = (List<List<EntityVillager.ITradeList>>) tradesField.get(career); CustomVillagerRegistry.getInstance().addVillagerEntry(new CustomVanillaVillagerEntry(RatsVillageRegistry.PET_SHOP_OWNER.getRegistryName().toString(), 0, trades) { @Override public EntityLivingBase getEntity(@Nonnull Minecraft minecraft) throws IllegalAccessException, InvocationTargetException, InstantiationException { return villager; } }); } catch (Exception e) { LogHelper.warn("Failed to register Pet Shop Owner villager."); e.printStackTrace(); } } private void registerPlagueDoctorVillager() { try { VillagerCareer career = RatsVillageRegistry.PLAGUE_DOCTOR.getCareer(0); Field tradesField = career.getClass().getDeclaredField("trades"); tradesField.setAccessible(true); List<List<EntityVillager.ITradeList>> trades = (List<List<EntityVillager.ITradeList>>) tradesField.get(career); CustomVillagerRegistry.getInstance().addVillagerEntry(new CustomVillagerEntry(RatsVillageRegistry.PLAGUE_DOCTOR.getRegistryName().toString(), 0, trades) { @Override public EntityLivingBase getEntity(@Nonnull Minecraft minecraft) throws IllegalAccessException, InvocationTargetException, InstantiationException { return new EntityPlagueDoctor(world); } }); } catch (Exception e) { LogHelper.warn("Failed to register Plague Doctor villager."); e.printStackTrace(); } } private void adjustHumanoidRenderHook(Class<? extends EntityLiving> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.45,0); return renderInfo; })); } private void registerRatsDungeon(String name, ResourceLocation lootTable) { JERDungeonStrings dungeon = new JERDungeonStrings(name); registerDungeonLoot(dungeon.category, dungeon.unlocName, lootTable); } private static class JERDungeonStrings { public final String category; public final String unlocName; public JERDungeonStrings(String name) {
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERRats extends JERBase implements IJERIntegration { private static JERRats instance; JEMConfigRats.JER jerConfig = JEMConfig.RATS.JUST_ENOUGH_RESOURCES; private JERRats() {} public JERRats(boolean enableJERDungeons, boolean enableJERMobs) { if(enableJERDungeons) registerModDungeons(); if(enableJERMobs) registerModEntities(); registerModVillagers(); getInstance(); } public static JERRats getInstance() { return instance != null ? instance : (instance = new JERRats()); } @Override public void registerModDungeons() { registerRatsDungeon("pet_shop", WorldGenPetShop.LOOT); registerRatsDungeon("pet_shop_upstairs", WorldGenPetShop.UPSTAIRS_LOOT); registerRatsDungeon("plague_doctor_house", WorldGenPlagueDoctor.LOOT); } @Override public void registerModEntities() { String[] ratlantisBiome = !RatsMod.CONFIG_OPTIONS.disableRatlantis ? BiomeHelper.getBiomeNamesForBiomes(RatsWorldRegistry.RATLANTIS_BIOME) : new String[] {"None"}; if(jerConfig.enableBlackDeath) { registerMob(new EntityBlackDeath(world), LightLevel.hostile, EntityBlackDeath.LOOT); adjustHumanoidRenderHook(EntityBlackDeath.class); } if(jerConfig.enableFeralRatlantean) { registerMob(new EntityFeralRatlantean(world), LightLevel.hostile, ratlantisBiome, EntityFeralRatlantean.LOOT); } if(jerConfig.enableIllagerPiper) { EntityIllagerPiper piper = new EntityIllagerPiper(world); piper.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(RatsItemRegistry.RAT_FLUTE)); registerMob(piper, LightLevel.hostile, EntityIllagerPiper.LOOT); adjustHumanoidRenderHook(piper.getClass()); } if(jerConfig.enableRatlanteanAutomation) { registerMob(new EntityMarbleCheeseGolem(world), LightLevel.any, EntityMarbleCheeseGolem.LOOT); registerRenderHook(EntityMarbleCheeseGolem.class, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-1.1,0); GlStateManager.scale(0.8,0.8,0.8); return renderInfo; })); } if(jerConfig.enableNeoRatlantean) { registerMob(new EntityNeoRatlantean(world), LightLevel.any, EntityNeoRatlantean.LOOT); } if(jerConfig.enablePirat) { EntityPirat pirat = new EntityPirat(world); pirat.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(RatsItemRegistry.PIRAT_CUTLASS)); pirat.setItemStackToSlot(EntityEquipmentSlot.HEAD, new ItemStack(RatsItemRegistry.PIRAT_HAT)); registerMob(pirat, LightLevel.any, EntityPirat.LOOT); } if(jerConfig.enablePlagueBeast) { registerMob(new EntityPlagueBeast(world), LightLevel.any, EntityPlagueBeast.LOOT); } if(jerConfig.enablePlagueDoctor) { registerMob(new EntityPlagueDoctor(world), LightLevel.any, EntityPlagueDoctor.LOOT); adjustHumanoidRenderHook(EntityPlagueDoctor.class); } if(jerConfig.enableRat) { EntityRat rat = new EntityRat(world); registerMob(rat, LightLevel.any, EntityRat.LOOT); } if(jerConfig.enableRatlanteanSpirit) { registerMob(new EntityRatlanteanSpirit(world), LightLevel.hostile, ratlantisBiome,EntityRatlanteanSpirit.LOOT); } } @Override public void registerModVillagers() { if(JEMConfig.RATS.fixJERVillagers) { registerPetShopOwner(); registerPlagueDoctorVillager(); } } public void registerRenderOverrides() { if(JEMConfig.RATS.enableRenderFixes) { //Rats uses a depreciated method for rendering. RenderingRegistry.registerEntityRenderingHandler(EntityRat.class, new JERRenderRat(Minecraft.getMinecraft().getRenderManager())); RenderingRegistry.registerEntityRenderingHandler(EntityPirat.class, new JERRenderPirat(Minecraft.getMinecraft().getRenderManager())); } } private void registerPetShopOwner() { try { EntityVillager villager = new EntityVillager(world); villager.setProfession(RatsVillageRegistry.PET_SHOP_OWNER); villager.getProfession(); VillagerCareer career = RatsVillageRegistry.PET_SHOP_OWNER.getCareer(0); Field tradesField = career.getClass().getDeclaredField("trades"); tradesField.setAccessible(true); List<List<EntityVillager.ITradeList>> trades = (List<List<EntityVillager.ITradeList>>) tradesField.get(career); CustomVillagerRegistry.getInstance().addVillagerEntry(new CustomVanillaVillagerEntry(RatsVillageRegistry.PET_SHOP_OWNER.getRegistryName().toString(), 0, trades) { @Override public EntityLivingBase getEntity(@Nonnull Minecraft minecraft) throws IllegalAccessException, InvocationTargetException, InstantiationException { return villager; } }); } catch (Exception e) { LogHelper.warn("Failed to register Pet Shop Owner villager."); e.printStackTrace(); } } private void registerPlagueDoctorVillager() { try { VillagerCareer career = RatsVillageRegistry.PLAGUE_DOCTOR.getCareer(0); Field tradesField = career.getClass().getDeclaredField("trades"); tradesField.setAccessible(true); List<List<EntityVillager.ITradeList>> trades = (List<List<EntityVillager.ITradeList>>) tradesField.get(career); CustomVillagerRegistry.getInstance().addVillagerEntry(new CustomVillagerEntry(RatsVillageRegistry.PLAGUE_DOCTOR.getRegistryName().toString(), 0, trades) { @Override public EntityLivingBase getEntity(@Nonnull Minecraft minecraft) throws IllegalAccessException, InvocationTargetException, InstantiationException { return new EntityPlagueDoctor(world); } }); } catch (Exception e) { LogHelper.warn("Failed to register Plague Doctor villager."); e.printStackTrace(); } } private void adjustHumanoidRenderHook(Class<? extends EntityLiving> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.45,0); return renderInfo; })); } private void registerRatsDungeon(String name, ResourceLocation lootTable) { JERDungeonStrings dungeon = new JERDungeonStrings(name); registerDungeonLoot(dungeon.category, dungeon.unlocName, lootTable); } private static class JERDungeonStrings { public final String category; public final String unlocName; public JERDungeonStrings(String name) {
this.category = ModIds.RATS.MOD_ID + ":" + name;
11
2023-11-19 23:09:14+00:00
16k
Provismet/ProviHealth
src/main/java/com/provismet/provihealth/mixin/EntityRendererMixin.java
[ { "identifier": "Options", "path": "src/main/java/com/provismet/provihealth/config/Options.java", "snippet": "public class Options {\n public static final Vector3f WHITE = Vec3d.unpackRgb(0xFFFFFF).toVector3f();\n\n public static int maxHealthBarTicks = 40;\n\n public static List<String> blackl...
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import com.provismet.provihealth.config.Options; import com.provismet.provihealth.hud.TargetHealthBar; import com.provismet.provihealth.world.EntityHealthBar; import net.minecraft.client.MinecraftClient; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.entity.EntityRenderer; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.text.Text;
11,542
package com.provismet.provihealth.mixin; @Mixin(EntityRenderer.class) public abstract class EntityRendererMixin { @Inject(method="renderLabelIfPresent", at=@At("HEAD"), cancellable=true) private void cancelLabel (Entity entity, Text text, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, CallbackInfo info) {
package com.provismet.provihealth.mixin; @Mixin(EntityRenderer.class) public abstract class EntityRendererMixin { @Inject(method="renderLabelIfPresent", at=@At("HEAD"), cancellable=true) private void cancelLabel (Entity entity, Text text, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, CallbackInfo info) {
if (TargetHealthBar.disabledLabels || (Options.overrideLabels && entity instanceof LivingEntity living && Options.shouldRenderHealthFor(living))) info.cancel();
1
2023-11-26 02:46:37+00:00
16k
codingmiao/hppt
cs/src/main/java/org/wowtools/hppt/cs/service/ServerSessionService.java
[ { "identifier": "ProtoMessage", "path": "common/src/main/java/org/wowtools/hppt/common/protobuf/ProtoMessage.java", "snippet": "public final class ProtoMessage {\n private ProtoMessage() {}\n public static void registerAllExtensions(\n com.google.protobuf.ExtensionRegistryLite registry) {\n }\n\...
import com.google.protobuf.ByteString; import lombok.extern.slf4j.Slf4j; import org.wowtools.hppt.common.protobuf.ProtoMessage; import org.wowtools.hppt.common.util.Constant; import java.util.LinkedList; import java.util.List; import java.util.Map;
14,317
package org.wowtools.hppt.cs.service; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class ServerSessionService { public static ProtoMessage.MessagePb talk(String clientId, ProtoMessage.MessagePb inputMessage) { Map<Integer, ServerSession> sessionMap = ServerSessionManager.getServerSessionByClientId(clientId); List<String> commands = new LinkedList<>(); /* 收消息,发给对应sever session */ //bytes for (ProtoMessage.BytesPb bytesPb : inputMessage.getBytesPbListList()) { ServerSession session = sessionMap.get(bytesPb.getSessionId()); if (session != null) { session.putBytes(bytesPb.getBytes().toByteArray()); } } //命令 for (String command : inputMessage.getCommandListList()) { log.debug("收到客户端命令 {} ", command); char type = command.charAt(0); switch (type) {
package org.wowtools.hppt.cs.service; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class ServerSessionService { public static ProtoMessage.MessagePb talk(String clientId, ProtoMessage.MessagePb inputMessage) { Map<Integer, ServerSession> sessionMap = ServerSessionManager.getServerSessionByClientId(clientId); List<String> commands = new LinkedList<>(); /* 收消息,发给对应sever session */ //bytes for (ProtoMessage.BytesPb bytesPb : inputMessage.getBytesPbListList()) { ServerSession session = sessionMap.get(bytesPb.getSessionId()); if (session != null) { session.putBytes(bytesPb.getBytes().toByteArray()); } } //命令 for (String command : inputMessage.getCommandListList()) { log.debug("收到客户端命令 {} ", command); char type = command.charAt(0); switch (type) {
case Constant.CsCommands.CloseSession -> {
1
2023-12-22 14:14:27+00:00
16k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/modules/misc/Speedmine.java
[ { "identifier": "Phobot", "path": "src/main/java/me/earth/phobot/Phobot.java", "snippet": "@Getter\n@RequiredArgsConstructor\n@SuppressWarnings(\"ClassCanBeRecord\")\npublic class Phobot {\n public static final String NAME = \"Phobot\";\n\n private final PingBypass pingBypass;\n private final E...
import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.earth.phobot.Phobot; import me.earth.phobot.event.*; import me.earth.phobot.modules.PhobotModule; import me.earth.phobot.modules.client.anticheat.StrictDirection; import me.earth.phobot.services.PlayerPosition; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.util.ResetUtil; import me.earth.phobot.util.math.MathUtil; import me.earth.phobot.util.math.PositionUtil; import me.earth.phobot.util.math.RaytraceUtil; import me.earth.phobot.util.math.RotationUtil; import me.earth.phobot.util.render.Renderer; import me.earth.phobot.util.time.StopWatch; import me.earth.phobot.util.world.BlockStateLevel; import me.earth.phobot.util.world.PredictionUtil; import me.earth.pingbypass.PingBypassApi; import me.earth.pingbypass.api.event.event.CancellableEvent; import me.earth.pingbypass.api.event.listeners.generic.Listener; import me.earth.pingbypass.api.module.impl.Categories; import me.earth.pingbypass.api.setting.Setting; import me.earth.pingbypass.api.setting.impl.Complexities; import me.earth.pingbypass.commons.event.SafeListener; import me.earth.pingbypass.commons.event.network.PacketEvent; import net.minecraft.ChatFormatting; 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.chat.Component; import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket; import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; import net.minecraft.tags.FluidTags; import net.minecraft.world.InteractionHand; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import org.apache.commons.lang3.mutable.MutableObject; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Objects;
12,425
package me.earth.phobot.modules.misc; // TODO: test what happens when target is out of range more, instead of just aborting // TODO: make the rendering a bit smarter @Slf4j public class Speedmine extends PhobotModule { private final Setting<Boolean> fast = bool("Fast", true, "Allows you mine blocks quicker if you place them on the same position."); private final Setting<Boolean> silentSwitch = bool("Switch", true, "Silently switches to your tool to mine."); private final Setting<Boolean> noGlitchBlocks = bool("NoGlitchBlocks", false, "If off sets the block to air on the clientside immediately."); private final Setting<Boolean> swing = bool("Swing", false, "Swings every tick."); private final Setting<Boolean> addTick = boolBuilder("AddTick", false).withDescription("Waits another tick before breaking.").withComplexity(Complexities.DEV).register(this); private final StopWatch.ForSingleThread expectingAirTimer = new StopWatch.ForSingleThread(); private final StopWatch.ForSingleThread timer = new StopWatch.ForSingleThread(); @Getter private BlockPos currentPos = null; private BlockState currentState = Blocks.AIR.defaultBlockState(); private List<AABB> renderBBs = Collections.emptyList(); private float renderDamageDelta = 0.0f; private int renderTicks = 0; private boolean sendAbortNextTick = true; private boolean expectingAir;
package me.earth.phobot.modules.misc; // TODO: test what happens when target is out of range more, instead of just aborting // TODO: make the rendering a bit smarter @Slf4j public class Speedmine extends PhobotModule { private final Setting<Boolean> fast = bool("Fast", true, "Allows you mine blocks quicker if you place them on the same position."); private final Setting<Boolean> silentSwitch = bool("Switch", true, "Silently switches to your tool to mine."); private final Setting<Boolean> noGlitchBlocks = bool("NoGlitchBlocks", false, "If off sets the block to air on the clientside immediately."); private final Setting<Boolean> swing = bool("Swing", false, "Swings every tick."); private final Setting<Boolean> addTick = boolBuilder("AddTick", false).withDescription("Waits another tick before breaking.").withComplexity(Complexities.DEV).register(this); private final StopWatch.ForSingleThread expectingAirTimer = new StopWatch.ForSingleThread(); private final StopWatch.ForSingleThread timer = new StopWatch.ForSingleThread(); @Getter private BlockPos currentPos = null; private BlockState currentState = Blocks.AIR.defaultBlockState(); private List<AABB> renderBBs = Collections.emptyList(); private float renderDamageDelta = 0.0f; private int renderTicks = 0; private boolean sendAbortNextTick = true; private boolean expectingAir;
public Speedmine(Phobot phobot) {
0
2023-12-22 14:32:16+00:00
16k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/gui/WaypointsGUI.java
[ { "identifier": "AutoRoom", "path": "build/sources/main/java/io/github/quantizr/core/AutoRoom.java", "snippet": "public class AutoRoom {\n Minecraft mc = Minecraft.getMinecraft();\n\n static int tickAmount = 1;\n public static List<String> autoTextOutput = null;\n public static boolean chatT...
import io.github.quantizr.core.AutoRoom; import io.github.quantizr.core.Waypoints; import io.github.quantizr.handlers.ConfigHandler; import io.github.quantizr.handlers.TextRenderer; import io.github.quantizr.utils.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumChatFormatting; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
14,334
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class WaypointsGUI extends GuiScreen { private GuiButton waypointsEnabled; private GuiButton showEntrance; private GuiButton showSuperboom; private GuiButton showSecrets; private GuiButton showFairySouls; private GuiButton disableWhenAllFound; private GuiButton sneakToDisable; private GuiButton close; public static List<GuiButton> secretButtonList = new ArrayList<>(Arrays.asList(new GuiButton[9])); private static boolean waypointGuiOpened = false; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); waypointGuiOpened = true; ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); waypointsEnabled = new GuiButton(0, width / 2 - 100, height / 6, 200, 20, waypointBtnText());
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class WaypointsGUI extends GuiScreen { private GuiButton waypointsEnabled; private GuiButton showEntrance; private GuiButton showSuperboom; private GuiButton showSecrets; private GuiButton showFairySouls; private GuiButton disableWhenAllFound; private GuiButton sneakToDisable; private GuiButton close; public static List<GuiButton> secretButtonList = new ArrayList<>(Arrays.asList(new GuiButton[9])); private static boolean waypointGuiOpened = false; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); waypointGuiOpened = true; ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); waypointsEnabled = new GuiButton(0, width / 2 - 100, height / 6, 200, 20, waypointBtnText());
showEntrance = new GuiButton(1, (width / 2 - 100) - 110, height / 6 + 30, 200, 20, "Show Entrance Waypoints: " + getOnOff(Waypoints.showEntrance));
1
2023-12-22 04:44:39+00:00
16k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/entrypoints/LauncherActivity.java
[ { "identifier": "BadgeCard", "path": "app/src/main/java/net/lonelytransistor/launcher/BadgeCard.java", "snippet": "public class BadgeCard extends Card {\n public String title;\n public Object badgeImage;\n public String badgeText;\n public Object mainImage;\n public Object statusIcon;\n ...
import android.app.AppOpsManager; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.PowerManager; import android.provider.Settings; import android.util.Log; import android.view.View; import android.view.ViewTreeObserver; import androidx.annotation.NonNull; import net.lonelytransistor.launcher.BadgeCard; import net.lonelytransistor.launcher.Card; import net.lonelytransistor.launcher.LauncherBar; import net.lonelytransistor.launcher.MovieCard; import net.lonelytransistor.launcher.R; import net.lonelytransistor.launcher.WidgetBar; import net.lonelytransistor.launcher.generics.GenericActivity;
11,721
package net.lonelytransistor.launcher.entrypoints; public class LauncherActivity extends GenericActivity implements ViewTreeObserver.OnGlobalFocusChangeListener { private static final String TAG = "LauncherActivity"; private static final String PERMISSION_READ_TV_LISTINGS = "android.permission.READ_TV_LISTINGS"; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); for (int res : grantResults) { if (res != PackageManager.PERMISSION_GRANTED) { finish(); return; } } start(); } private boolean isUsageAccessGranted() { try { PackageManager packageManager = getPackageManager(); ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0); AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); int mode = appOpsManager.unsafeCheckOpRaw(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName); return (mode == AppOpsManager.MODE_ALLOWED); } catch (PackageManager.NameNotFoundException e) { return false; } } private boolean isIgnoringBatteryOptimizations() { PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); return powerManager.isIgnoringBatteryOptimizations(getPackageName()); } private void start() { if (checkCallingOrSelfPermission(PERMISSION_READ_TV_LISTINGS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{PERMISSION_READ_TV_LISTINGS}, 0); } else { if (!isUsageAccessGranted()) { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); intent.putExtra(Intent.EXTRA_PACKAGE_NAME, getPackageName()); startActivity(intent); } else if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else /*if (!isIgnoringBatteryOptimizations()) { Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else*/ { BackgroundService.showLauncher(this); finish(); } } } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); widgetBar.onStop(); } WidgetBar widgetBar; @Override public void onGlobalFocusChanged(View oldFocus, View newFocus) { Log.i(TAG, "Focus: " + newFocus); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the global focus change listener //getWindow().getDecorView().getRootView().getViewTreeObserver().addOnGlobalFocusChangeListener(this); if (true) { start(); } else if (true) { setContentView(R.layout.activity_main); LauncherBar bar = findViewById(R.id.launcherBar); widgetBar = findViewById(R.id.widgetBar); //widgetBar.constructor(this); int row = bar.addRow(new BadgeCard("Title", "Test0", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null)); bar.addItems(row, widgetBar.getAllWidgetCards()); row = bar.addRow(new BadgeCard("Title",
package net.lonelytransistor.launcher.entrypoints; public class LauncherActivity extends GenericActivity implements ViewTreeObserver.OnGlobalFocusChangeListener { private static final String TAG = "LauncherActivity"; private static final String PERMISSION_READ_TV_LISTINGS = "android.permission.READ_TV_LISTINGS"; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); for (int res : grantResults) { if (res != PackageManager.PERMISSION_GRANTED) { finish(); return; } } start(); } private boolean isUsageAccessGranted() { try { PackageManager packageManager = getPackageManager(); ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0); AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); int mode = appOpsManager.unsafeCheckOpRaw(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName); return (mode == AppOpsManager.MODE_ALLOWED); } catch (PackageManager.NameNotFoundException e) { return false; } } private boolean isIgnoringBatteryOptimizations() { PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); return powerManager.isIgnoringBatteryOptimizations(getPackageName()); } private void start() { if (checkCallingOrSelfPermission(PERMISSION_READ_TV_LISTINGS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{PERMISSION_READ_TV_LISTINGS}, 0); } else { if (!isUsageAccessGranted()) { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); intent.putExtra(Intent.EXTRA_PACKAGE_NAME, getPackageName()); startActivity(intent); } else if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else /*if (!isIgnoringBatteryOptimizations()) { Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else*/ { BackgroundService.showLauncher(this); finish(); } } } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); widgetBar.onStop(); } WidgetBar widgetBar; @Override public void onGlobalFocusChanged(View oldFocus, View newFocus) { Log.i(TAG, "Focus: " + newFocus); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the global focus change listener //getWindow().getDecorView().getRootView().getViewTreeObserver().addOnGlobalFocusChangeListener(this); if (true) { start(); } else if (true) { setContentView(R.layout.activity_main); LauncherBar bar = findViewById(R.id.launcherBar); widgetBar = findViewById(R.id.widgetBar); //widgetBar.constructor(this); int row = bar.addRow(new BadgeCard("Title", "Test0", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null)); bar.addItems(row, widgetBar.getAllWidgetCards()); row = bar.addRow(new BadgeCard("Title",
"Test2", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, new Card.Callback() {
1
2023-12-28 18:24:12+00:00
16k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/view/ChessGameFrame.java
[ { "identifier": "Main", "path": "CS109_2022_Fall/Chess/Main.java", "snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素...
import Chess.Main; import Chess.chessComponent.EatenComponent; import Chess.chessComponent.SquareComponent; import Chess.controller.GameController; import Chess.model.ChessColor; import Chess.model.ChessboardPoint; import Chess.utils.FileUtils; import Chess.utils.GeneralUtils; import Chess.utils.ImageUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import static Chess.Main.*; import static Chess.utils.GeneralUtils.log; import static Chess.utils.ImageUtils.changeImageSize;
11,895
private void addScoreLabel() { JLabel jLabel = new JLabel("红 - 黑"); jLabel.setLocation((int) (WIDTH * 11.14 / 15 + 5), (int) (HEIGHT / 13 * 9.3)); jLabel.setSize(200, 60); jLabel.setFont(sansFont.deriveFont(Font.BOLD, 23)); jLabel.setForeground(ChessColor.BLACK.getColor()); add(jLabel); scoreLabel = new JLabel("00 - 00"); scoreLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 9.85)); scoreLabel.setSize(200, 60); scoreLabel.setFont(sansFont.deriveFont(Font.BOLD, 23)); scoreLabel.setForeground(ChessColor.BLACK.getColor()); add(scoreLabel); } public static JLabel getStatusLabel() { return statusLabel; } public static JLabel getScoreLabel() { return scoreLabel; } public static JLabel getBlackEatenLabel() { return blackEatenLabel; } public static JLabel getRedEatenLabel() { return redEatenLabel; } /** * 在游戏窗体中增加一个按钮,如果按下的话就会显示Hello, world! */ private void addBackButton() { JButton button = new JButton("返回"); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); button.addActionListener((e) -> { Main.backStart(); Main.playNotifyMusic("click"); }); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13); button.setSize(80, 40); StartFrame.setButtonBg(button, 80, 40); add(button); } private void addLoadButton() { JButton button = new JButton("存档"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 45); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { System.out.println("Click load"); Main.playNotifyMusic("click"); int option = JOptionPane.showOptionDialog(this, "选择是要保存存档还是导入存档?", "请选择", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{"保存存档", "导入存档"}, "导入存档"); if (option == 1) { String path = JOptionPane.showInputDialog(this, "在这里输入存档的文件绝对路径"); gameController.loadGSon(path); } else { gameController.toGSon(); } }); } private void addRefreshButton() { JButton button = new JButton("重置"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 90); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { Main.playNotifyMusic("click"); Main.refreshGame(); }); } private void addThemeButton() { JButton button = new JButton("主题"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 135); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { System.out.println("Click theme"); Main.playNotifyMusic("click"); String path = JOptionPane.showInputDialog(this, "在下方输入主题的名字以选择主题(可选主题有像素、典雅、激情):"); if (path == null) { JOptionPane.showMessageDialog(this, "不能输入空内容!"); } else if (path.equals(Main.themeList[0]) || path.equals(Main.themeList[1]) || path.equals(Main.themeList[2])) { log("SELECT " + path); Main.theme = path; data.put("theme", gson.toJsonTree(theme, new TypeToken<String>() { }.getType())); FileUtils.saveDataToFile("data", gson.toJson(data), "json"); Main.startGame(Main.mode); } else { JOptionPane.showMessageDialog(this, "没有这个主题,请重新选择!"); } }); } private void addBg() { InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("bg")); JLabel lbBg = null; try {
package Chess.view; /** * 这个类表示游戏窗体,窗体上包含: * 1 Chessboard: 棋盘 * 2 JLabel: 标签 * 3 JButton: 按钮 */ public class ChessGameFrame extends JFrame { private final int WIDTH; private final int HEIGHT; public final int CHESSBOARD_SIZE; private GameController gameController; private static JLabel statusLabel, scoreLabel, blackEatenLabel, redEatenLabel; private static JPanel eatenPanel; public static String redEatenList, blackEatenList; private Gson gson = new Gson(); private static EatenComponent[][] eatenComponents = new EatenComponent[2][7]; private static String[][] nameList = { {"將", "士", "象", "車", "馬", "卒", "砲"}, {"帥", "仕", "相", "俥", "傌", "兵", "炮"}}; private static int redEaten[] = {0, 0, 0, 0, 0, 0, 0}, blackEaten[] = {0, 0, 0, 0, 0, 0, 0}; public ChessGameFrame(int width, int height, int mode) { setTitle("翻翻棋~"); this.WIDTH = width; this.HEIGHT = height; this.CHESSBOARD_SIZE = HEIGHT * 4 / 5; redEatenList = ""; blackEatenList = ""; setResizable(false); setSize(WIDTH, HEIGHT); setLocationRelativeTo(null); // Center the window. getContentPane().setBackground(Color.WHITE); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(null); addChessboard(mode); addStatusLabel(); addScoreLabel(); addBlackEatenLabel(); addRedEatenLabel(); addEatenList(); addBackButton(); addLoadButton(); addRefreshButton(); addThemeButton(); addBg(); } /** * 在游戏窗体中添加棋盘 */ private void addChessboard(int mode) { Chessboard chessboard = new Chessboard(CHESSBOARD_SIZE / 2 + 100, CHESSBOARD_SIZE, mode); gameController = new GameController(chessboard); chessboard.setLocation(HEIGHT / 13, HEIGHT / 13); add(chessboard); } private void addEatenList() { eatenPanel = new JPanel(); eatenPanel.setBounds(WIDTH * 11 / 15 + 2, (int) (HEIGHT / 13 * 6.04), 75, 185); GridLayout gridLayout = new GridLayout(7, 2); eatenPanel.setLayout(gridLayout); eatenPanel.setBackground(Color.WHITE); eatenPanel.setOpaque(false);//workaround keep opaque after repainted add(eatenPanel); setEatenList(); } private static void setEatenList() { parseEatenLists(); for (int j = 0; j < 7; j++) { for (int i = 0; i < 2; i++) { if (eatenComponents[i][j] != null) eatenPanel.remove(eatenComponents[i][j]); eatenComponents[i][j] = new EatenComponent(nameList[i][j], (i == 0) ? blackEaten[j] : redEaten[j], i, j, (i == 0) ? "b" : "r"); eatenPanel.add(eatenComponents[i][j]); } } } private static void parseEatenLists() { Arrays.fill(redEaten, 0); Arrays.fill(blackEaten, 0); String[] red = redEatenList.split(" "), black = blackEatenList.split(" "); for (String s : red) { switch (s) { case "帥" -> redEaten[0]++; case "仕" -> redEaten[1]++; case "相" -> redEaten[2]++; case "俥" -> redEaten[3]++; case "傌" -> redEaten[4]++; case "兵" -> redEaten[5]++; case "炮" -> redEaten[6]++; } } for (String s : black) { switch (s) { case "將" -> blackEaten[0]++; case "士" -> blackEaten[1]++; case "象" -> blackEaten[2]++; case "車" -> blackEaten[3]++; case "馬" -> blackEaten[4]++; case "卒" -> blackEaten[5]++; case "砲" -> blackEaten[6]++; } } } /** * 在游戏窗体中添加标签 */ private void addStatusLabel() { statusLabel = new JLabel("红走棋"); statusLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 10.65)); statusLabel.setSize(200, 60); statusLabel.setFont(sansFont.deriveFont(Font.BOLD, 23)); statusLabel.setForeground(Main.getThemeColor("indicatorRed")); add(statusLabel); } private void addRedEatenLabel() { redEatenLabel = new JLabel(); redEatenLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 5.05)); redEatenLabel.setSize(100, 200); redEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14)); redEatenLabel.setForeground(Main.getThemeColor("indicatorBlack")); JlabelSetText(redEatenLabel, "红被吃:----"); redEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14)); //add(redEatenLabel); } private void addBlackEatenLabel() { blackEatenLabel = new JLabel(); blackEatenLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 6.65)); blackEatenLabel.setSize(100, 200); blackEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14)); blackEatenLabel.setForeground(Main.getThemeColor("indicatorBlack")); JlabelSetText(blackEatenLabel, "黑被吃:----"); blackEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14)); //add(blackEatenLabel); } public static void appendBlackEatenLabel(String str) { blackEatenList += " " + str; setEatenList(); //JlabelSetText(blackEatenLabel, "黑被吃:<br/>" + blackEatenList); } public static void appendRedEatenLabel(String str) { redEatenList += " " + str; setEatenList(); //JlabelSetText(redEatenLabel, "红被吃:<br/>" + redEatenList); } public static void popBlackEatenLabel() { blackEatenList = blackEatenList.substring(0, blackEatenList.lastIndexOf(" ")); setEatenList(); /*if (blackEatenList.strip().length() > 0) JlabelSetText(blackEatenLabel, "黑被吃:<br/>" + blackEatenList); else JlabelSetText(blackEatenLabel, "黑被吃:----");*/ } public static void popRedEatenLabel() { redEatenList = redEatenList.substring(0, redEatenList.lastIndexOf(" ")); setEatenList(); /*if (redEatenList.strip().length() > 0) JlabelSetText(redEatenLabel, "红被吃:<br/>" + redEatenList); else JlabelSetText(redEatenLabel, "红被吃:----");*/ } public static void setBlackEatenLabel(String str) { blackEatenList = str; setEatenList(); //JlabelSetText(blackEatenLabel, "黑被吃:<br/>" + blackEatenList); } public static void setRedEatenLabel(String str) { redEatenList = str; setEatenList(); //JlabelSetText(redEatenLabel, "红被吃:<br/>" + redEatenList); } private static void JlabelSetText(JLabel jLabel, String longString) { StringBuilder builder = new StringBuilder("<html>" + longString.substring(0, 7)); char[] chars = longString.toCharArray(); FontMetrics fontMetrics = jLabel.getFontMetrics(jLabel.getFont()); int start = 8; int len = 0; while (start + len < longString.length()) { while (true) { len++; if (start + len > longString.length()) break; if (fontMetrics.charsWidth(chars, start, len) > jLabel.getWidth()) { break; } } builder.append(chars, start, len - 1).append("<br/>"); start = start + len - 1; len = 0; } builder.append(chars, start, longString.length() - start); builder.append("</html>"); jLabel.setText(builder.toString()); } private void addScoreLabel() { JLabel jLabel = new JLabel("红 - 黑"); jLabel.setLocation((int) (WIDTH * 11.14 / 15 + 5), (int) (HEIGHT / 13 * 9.3)); jLabel.setSize(200, 60); jLabel.setFont(sansFont.deriveFont(Font.BOLD, 23)); jLabel.setForeground(ChessColor.BLACK.getColor()); add(jLabel); scoreLabel = new JLabel("00 - 00"); scoreLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 9.85)); scoreLabel.setSize(200, 60); scoreLabel.setFont(sansFont.deriveFont(Font.BOLD, 23)); scoreLabel.setForeground(ChessColor.BLACK.getColor()); add(scoreLabel); } public static JLabel getStatusLabel() { return statusLabel; } public static JLabel getScoreLabel() { return scoreLabel; } public static JLabel getBlackEatenLabel() { return blackEatenLabel; } public static JLabel getRedEatenLabel() { return redEatenLabel; } /** * 在游戏窗体中增加一个按钮,如果按下的话就会显示Hello, world! */ private void addBackButton() { JButton button = new JButton("返回"); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); button.addActionListener((e) -> { Main.backStart(); Main.playNotifyMusic("click"); }); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13); button.setSize(80, 40); StartFrame.setButtonBg(button, 80, 40); add(button); } private void addLoadButton() { JButton button = new JButton("存档"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 45); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { System.out.println("Click load"); Main.playNotifyMusic("click"); int option = JOptionPane.showOptionDialog(this, "选择是要保存存档还是导入存档?", "请选择", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{"保存存档", "导入存档"}, "导入存档"); if (option == 1) { String path = JOptionPane.showInputDialog(this, "在这里输入存档的文件绝对路径"); gameController.loadGSon(path); } else { gameController.toGSon(); } }); } private void addRefreshButton() { JButton button = new JButton("重置"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 90); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { Main.playNotifyMusic("click"); Main.refreshGame(); }); } private void addThemeButton() { JButton button = new JButton("主题"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 135); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { System.out.println("Click theme"); Main.playNotifyMusic("click"); String path = JOptionPane.showInputDialog(this, "在下方输入主题的名字以选择主题(可选主题有像素、典雅、激情):"); if (path == null) { JOptionPane.showMessageDialog(this, "不能输入空内容!"); } else if (path.equals(Main.themeList[0]) || path.equals(Main.themeList[1]) || path.equals(Main.themeList[2])) { log("SELECT " + path); Main.theme = path; data.put("theme", gson.toJsonTree(theme, new TypeToken<String>() { }.getType())); FileUtils.saveDataToFile("data", gson.toJson(data), "json"); Main.startGame(Main.mode); } else { JOptionPane.showMessageDialog(this, "没有这个主题,请重新选择!"); } }); } private void addBg() { InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("bg")); JLabel lbBg = null; try {
lbBg = new JLabel(ImageUtils.changeImageSize(new ImageIcon(stream.readAllBytes()), 0.3f));
8
2023-12-31 05:50:13+00:00
16k
psobiech/opengr8on
client/src/main/java/pl/psobiech/opengr8on/client/Main.java
[ { "identifier": "CLUDevice", "path": "lib/src/main/java/pl/psobiech/opengr8on/client/device/CLUDevice.java", "snippet": "public class CLUDevice {\n private final String name;\n\n private final Long serialNumber;\n\n private final String macAddress;\n\n private Inet4Address address;\n\n pr...
import java.io.IOException; import java.net.Inet4Address; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.util.Map; import java.util.Optional; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.psobiech.opengr8on.client.device.CLUDevice; import pl.psobiech.opengr8on.client.device.CLUDeviceConfig; import pl.psobiech.opengr8on.client.device.CipherTypeEnum; import pl.psobiech.opengr8on.exceptions.UnexpectedException; import pl.psobiech.opengr8on.util.FileUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; import pl.psobiech.opengr8on.util.ObjectMapperFactory; import pl.psobiech.opengr8on.util.RandomUtil; import pl.psobiech.opengr8on.util.Util; import pl.psobiech.opengr8on.xml.interfaces.CLU; import pl.psobiech.opengr8on.xml.interfaces.InterfaceRegistry; import pl.psobiech.opengr8on.xml.omp.OmpReader;
13,217
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class Main { private static final Duration DEFAULT_LONG_TIMEOUT = Duration.ofMillis(30_000); private static final int TIMEOUT = 4_000; private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final Map<Long, byte[]> PRIVATE_KEYS = Map.of( 0x0L, "00000000".getBytes() ); private static final Inet4Address MIN_IP = IPv4AddressUtil.parseIPv4("10.72.144.1"); private Main() { // NOP } public static void main(String[] args) throws Exception { final CommandLine commandLine = new DefaultParser().parse(CLIParameters.OPTIONS, args); if (commandLine.hasOption(CLIParameters.HELP_OPTION)) { new HelpFormatter() .printHelp("java -jar client.jar", CLIParameters.OPTIONS); System.exit(0); } // final NetworkInterfaceDto networkInterface = CLIParameters.getNetworkInterface(commandLine); LOGGER.debug("Using network interface: {}", networkInterface); if (commandLine.hasOption(CLIParameters.DISCOVER_OPTION)) {
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class Main { private static final Duration DEFAULT_LONG_TIMEOUT = Duration.ofMillis(30_000); private static final int TIMEOUT = 4_000; private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final Map<Long, byte[]> PRIVATE_KEYS = Map.of( 0x0L, "00000000".getBytes() ); private static final Inet4Address MIN_IP = IPv4AddressUtil.parseIPv4("10.72.144.1"); private Main() { // NOP } public static void main(String[] args) throws Exception { final CommandLine commandLine = new DefaultParser().parse(CLIParameters.OPTIONS, args); if (commandLine.hasOption(CLIParameters.HELP_OPTION)) { new HelpFormatter() .printHelp("java -jar client.jar", CLIParameters.OPTIONS); System.exit(0); } // final NetworkInterfaceDto networkInterface = CLIParameters.getNetworkInterface(commandLine); LOGGER.debug("Using network interface: {}", networkInterface); if (commandLine.hasOption(CLIParameters.DISCOVER_OPTION)) {
final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine);
11
2023-12-23 09:56:14+00:00
16k
Prototik/TheConfigLib
test-common/src/main/java/dev/tcl/test/GuiTest.java
[ { "identifier": "RequireRestartScreen", "path": "common/src/main/java/dev/tcl/gui/RequireRestartScreen.java", "snippet": "@Environment(EnvType.CLIENT)\npublic class RequireRestartScreen extends ConfirmScreen {\n public RequireRestartScreen(@Nullable Screen parent) {\n super(option -> {\n ...
import dev.tcl.api.*; import dev.tcl.api.controller.*; import dev.tcl.gui.RequireRestartScreen; import dev.tcl.gui.controllers.ColorController; import dev.tcl.gui.controllers.LabelController; import dev.tcl.gui.controllers.TickBoxController; import dev.tcl.gui.controllers.cycling.EnumController; import dev.tcl.gui.controllers.slider.DoubleSliderController; import dev.tcl.gui.controllers.slider.FloatSliderController; import dev.tcl.gui.controllers.slider.IntegerSliderController; import dev.tcl.gui.controllers.slider.LongSliderController; import dev.tcl.gui.controllers.string.StringController; import dev.tcl.gui.controllers.string.number.DoubleFieldController; import dev.tcl.gui.controllers.string.number.FloatFieldController; import dev.tcl.gui.controllers.string.number.IntegerFieldController; import dev.tcl.gui.controllers.string.number.LongFieldController; import net.minecraft.ChatFormatting; import net.minecraft.Util; import net.minecraft.client.GraphicsStatus; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.toasts.SystemToast; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.HoverEvent; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import org.apache.commons.lang3.StringUtils; import java.awt.*; import java.nio.file.Path; import java.util.List; import java.util.concurrent.atomic.AtomicReference;
12,027
.name(Component.literal("Wiki")) .option(ButtonOption.createBuilder() .name(Component.literal("Get Started")) .action((screen, opt) -> Minecraft.getInstance().setScreen(getWikiGetStarted(screen))) .build()) .build()) .build()) ) .generateScreen(parent); } private static Screen getFullTestSuite(Screen parent) { AtomicReference<Option<Boolean>> booleanOption = new AtomicReference<>(); return TheConfigLib.create(ConfigTest.GSON, (defaults, config, builder) -> builder .title(Component.literal("Test GUI")) .category(ConfigCategory.createBuilder() .name(Component.literal("Control Examples")) .tooltip(Component.literal("Example Category Description")) .group(OptionGroup.createBuilder() .name(Component.literal("Boolean Controllers")) .option(Util.make(() -> { var opt = Option.<Boolean>createBuilder() .name(Component.literal("Boolean Toggle")) .description(OptionDescription.createBuilder() .text(Component.empty() .append(Component.literal("a").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("a"))))) .append(Component.literal("b").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("b"))))) .append(Component.literal("c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("c"))))) .append(Component.literal("e").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("e"))))) .withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://isxander.dev"))) ) .webpImage(new ResourceLocation("tcl_test", "reach-around-placement.webp")) .build()) .binding( defaults.booleanToggle, () -> config.booleanToggle, (value) -> config.booleanToggle = value ) .controller(BoolControllerBuilder::create) .flag(OptionFlag.GAME_RESTART) .build(); booleanOption.set(opt); return opt; })) .option(Option.<Boolean>createBuilder() .name(Component.literal("Custom Boolean Toggle")) .description(val -> OptionDescription.createBuilder() .text(Component.literal("You can customize controllers like so! " + TheConfigLib.SHORT_NAME + " is truly infinitely customizable! This tooltip is long in order to demonstrate the cool, smooth scrolling of these descriptions. Did you know, they are also super clickable?! I know, cool right, " + TheConfigLib.SHORT_NAME + " really is amazing.")) .image(Path.of("D:\\Xander\\Downloads\\_MG_0860-Enhanced-NR.png"), new ResourceLocation("tcl_test", "f.webp")) // TODO: Add img file to git? .build()) .binding( defaults.customBooleanToggle, () -> config.customBooleanToggle, (value) -> config.customBooleanToggle = value ) .controller(opt -> BoolControllerBuilder.create(opt) .formatValue(state -> state ? Component.literal("Amazing") : Component.literal("Not Amazing")) .coloured(true)) .listener((opt, val) -> booleanOption.get().setAvailable(val)) .build()) .option(Option.<Boolean>createBuilder() .name(Component.literal("Tick Box")) .description(OptionDescription.of(Component.literal("There are even alternate methods of displaying the same data type!"))) .binding( defaults.tickbox, () -> config.tickbox, (value) -> config.tickbox = value ) .controller(TickBoxControllerBuilder::create) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Slider Controllers")) .option(Option.<Integer>createBuilder() .name(Component.literal("Int Slider")) .binding( defaults.intSlider, () -> config.intSlider, value -> config.intSlider = value ) .customController(opt -> new IntegerSliderController(opt, 0, 3, 1)) .build()) .option(Option.<Double>createBuilder() .name(Component.literal("Double Slider")) .binding( defaults.doubleSlider, () -> config.doubleSlider, (value) -> config.doubleSlider = value ) .customController(opt -> new DoubleSliderController(opt, 0, 3, 0.05)) .build()) .option(Option.<Float>createBuilder() .name(Component.literal("Float Slider")) .binding( defaults.floatSlider, () -> config.floatSlider, (value) -> config.floatSlider = value ) .customController(opt -> new FloatSliderController(opt, 0, 3, 0.1f)) .build()) .option(Option.<Long>createBuilder() .name(Component.literal("Long Slider")) .binding( defaults.longSlider, () -> config.longSlider, (value) -> config.longSlider = value ) .customController(opt -> new LongSliderController(opt, 0, 1_000_000, 100)) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Input Field Controllers")) .option(Option.<String>createBuilder() .name(Component.literal("Component Option")) .binding( defaults.textField, () -> config.textField, value -> config.textField = value )
package dev.tcl.test; public class GuiTest { public static Screen getModConfigScreenFactory(Screen parent) { return TheConfigLib.create(ConfigTest.GSON, (defaults, config, builder) -> builder .title(Component.literal("Test Suites")) .category(ConfigCategory.createBuilder() .name(Component.literal("Suites")) .option(ButtonOption.createBuilder() .name(Component.literal("Full Test Suite")) .action((screen, opt) -> Minecraft.getInstance().setScreen(getFullTestSuite(screen))) .build()) .option(ButtonOption.createBuilder() .name(Component.literal("Auto-gen test")) .action((screen, opt) -> { Minecraft.getInstance().setScreen(AutogenConfigTest.INSTANCE.generateGui().generateScreen(screen)); }) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Wiki")) .option(ButtonOption.createBuilder() .name(Component.literal("Get Started")) .action((screen, opt) -> Minecraft.getInstance().setScreen(getWikiGetStarted(screen))) .build()) .build()) .build()) ) .generateScreen(parent); } private static Screen getFullTestSuite(Screen parent) { AtomicReference<Option<Boolean>> booleanOption = new AtomicReference<>(); return TheConfigLib.create(ConfigTest.GSON, (defaults, config, builder) -> builder .title(Component.literal("Test GUI")) .category(ConfigCategory.createBuilder() .name(Component.literal("Control Examples")) .tooltip(Component.literal("Example Category Description")) .group(OptionGroup.createBuilder() .name(Component.literal("Boolean Controllers")) .option(Util.make(() -> { var opt = Option.<Boolean>createBuilder() .name(Component.literal("Boolean Toggle")) .description(OptionDescription.createBuilder() .text(Component.empty() .append(Component.literal("a").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("a"))))) .append(Component.literal("b").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("b"))))) .append(Component.literal("c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("c"))))) .append(Component.literal("e").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("e"))))) .withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://isxander.dev"))) ) .webpImage(new ResourceLocation("tcl_test", "reach-around-placement.webp")) .build()) .binding( defaults.booleanToggle, () -> config.booleanToggle, (value) -> config.booleanToggle = value ) .controller(BoolControllerBuilder::create) .flag(OptionFlag.GAME_RESTART) .build(); booleanOption.set(opt); return opt; })) .option(Option.<Boolean>createBuilder() .name(Component.literal("Custom Boolean Toggle")) .description(val -> OptionDescription.createBuilder() .text(Component.literal("You can customize controllers like so! " + TheConfigLib.SHORT_NAME + " is truly infinitely customizable! This tooltip is long in order to demonstrate the cool, smooth scrolling of these descriptions. Did you know, they are also super clickable?! I know, cool right, " + TheConfigLib.SHORT_NAME + " really is amazing.")) .image(Path.of("D:\\Xander\\Downloads\\_MG_0860-Enhanced-NR.png"), new ResourceLocation("tcl_test", "f.webp")) // TODO: Add img file to git? .build()) .binding( defaults.customBooleanToggle, () -> config.customBooleanToggle, (value) -> config.customBooleanToggle = value ) .controller(opt -> BoolControllerBuilder.create(opt) .formatValue(state -> state ? Component.literal("Amazing") : Component.literal("Not Amazing")) .coloured(true)) .listener((opt, val) -> booleanOption.get().setAvailable(val)) .build()) .option(Option.<Boolean>createBuilder() .name(Component.literal("Tick Box")) .description(OptionDescription.of(Component.literal("There are even alternate methods of displaying the same data type!"))) .binding( defaults.tickbox, () -> config.tickbox, (value) -> config.tickbox = value ) .controller(TickBoxControllerBuilder::create) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Slider Controllers")) .option(Option.<Integer>createBuilder() .name(Component.literal("Int Slider")) .binding( defaults.intSlider, () -> config.intSlider, value -> config.intSlider = value ) .customController(opt -> new IntegerSliderController(opt, 0, 3, 1)) .build()) .option(Option.<Double>createBuilder() .name(Component.literal("Double Slider")) .binding( defaults.doubleSlider, () -> config.doubleSlider, (value) -> config.doubleSlider = value ) .customController(opt -> new DoubleSliderController(opt, 0, 3, 0.05)) .build()) .option(Option.<Float>createBuilder() .name(Component.literal("Float Slider")) .binding( defaults.floatSlider, () -> config.floatSlider, (value) -> config.floatSlider = value ) .customController(opt -> new FloatSliderController(opt, 0, 3, 0.1f)) .build()) .option(Option.<Long>createBuilder() .name(Component.literal("Long Slider")) .binding( defaults.longSlider, () -> config.longSlider, (value) -> config.longSlider = value ) .customController(opt -> new LongSliderController(opt, 0, 1_000_000, 100)) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Input Field Controllers")) .option(Option.<String>createBuilder() .name(Component.literal("Component Option")) .binding( defaults.textField, () -> config.textField, value -> config.textField = value )
.customController(StringController::new)
9
2023-12-25 14:48:27+00:00
16k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/labels/StandardXYSeriesLabelGeneratorTest.java
[ { "identifier": "TestUtilities", "path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java", "snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</cod...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.jfree.chart.TestUtilities; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.util.PublicCloneable; import org.junit.Test;
13,858
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------------- * StandardXYSeriesLabelGeneratorTest.java * --------------------------------------- * (C) Copyright 2006-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 24-Nov-2006 : Version 1 (DG); * 23-Apr-2008 : Added testPublicCloneable() (DG) * */ package org.jfree.chart.labels; /** * Tests for the {@link StandardXYSeriesLabelGenerator} class. */ public class StandardXYSeriesLabelGeneratorTest { /** * Some checks for the generalLabel() method. */ @Test public void testGenerateLabel() { StandardXYSeriesLabelGenerator g = new StandardXYSeriesLabelGenerator("Series {0}");
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------------- * StandardXYSeriesLabelGeneratorTest.java * --------------------------------------- * (C) Copyright 2006-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 24-Nov-2006 : Version 1 (DG); * 23-Apr-2008 : Added testPublicCloneable() (DG) * */ package org.jfree.chart.labels; /** * Tests for the {@link StandardXYSeriesLabelGenerator} class. */ public class StandardXYSeriesLabelGeneratorTest { /** * Some checks for the generalLabel() method. */ @Test public void testGenerateLabel() { StandardXYSeriesLabelGenerator g = new StandardXYSeriesLabelGenerator("Series {0}");
XYSeriesCollection dataset = new XYSeriesCollection();
2
2023-12-24 12:36:47+00:00
16k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/module/impl/render/ESP.java
[ { "identifier": "MayOBees", "path": "src/main/java/com/github/may2beez/mayobees/MayOBees.java", "snippet": "@Mod(modid = \"mayobees\", useMetadata=true)\npublic class MayOBees {\n public static final MayOBeesConfig CONFIG = new MayOBeesConfig();\n public static final Gson GSON = new GsonBuilder()....
import cc.polyfrost.oneconfig.config.core.OneColor; import com.github.may2beez.mayobees.MayOBees; import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.event.ClickEvent; import com.github.may2beez.mayobees.handler.GameStateHandler; import com.github.may2beez.mayobees.module.IModule; import com.github.may2beez.mayobees.util.HeadUtils; import com.github.may2beez.mayobees.util.RenderUtils; import com.google.gson.reflect.TypeToken; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.Vec3; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors;
13,674
return instance; } @Override public String getName() { return "ESP"; } public ESP() { try { if (!clickedFairySoulsFile.getParentFile().exists()) { clickedFairySoulsFile.getParentFile().mkdirs(); } if (!clickedFairySoulsFile.exists()) { clickedFairySoulsFile.createNewFile(); // fill it with empty array FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(clickedFairySoulsFile); String json = MayOBees.GSON.toJson(clickedFairySouls); fileOutputStream.write(json.getBytes()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } catch (IOException e) { throw new RuntimeException(e); } FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(clickedFairySoulsFile); byte[] bytes = new byte[fileInputStream.available()]; fileInputStream.read(bytes); String json = new String(bytes); if (json.isEmpty()) return; Type type = new TypeToken<HashMap<String, List<Location>>>() { }.getType(); try { HashMap<String, List<Location>> locations = MayOBees.GSON.fromJson(json, type); if (locations == null) return; clickedFairySouls.putAll(locations); } catch (Exception e) { e.printStackTrace(); saveClickedFairySouls(); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileInputStream != null) try { fileInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } private void saveClickedFairySouls() { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(clickedFairySoulsFile); String json = MayOBees.GSON.toJson(clickedFairySouls); fileOutputStream.write(json.getBytes()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } public void resetClickedFairySouls() { clickedFairySouls.clear(); saveClickedFairySouls(); } public void resetClickedFairySoulsOnlyCurrentIsland() { clickedFairySouls.remove(GameStateHandler.getInstance().getLocation().getName()); saveClickedFairySouls(); } public void addAllVisibleFairySoulsToClickedList() { List<Location> thisLocationFairySouls = clickedFairySouls.computeIfAbsent(GameStateHandler.getInstance().getLocation().getName(), k -> new ArrayList<>()); for (EntityArmorStand entityArmorStand : visibleFairySouls) { if (listHasElement(thisLocationFairySouls, Location.of(entityArmorStand.getPosition()))) continue; thisLocationFairySouls.add(Location.of(entityArmorStand.getPosition())); } clickedFairySouls.put(GameStateHandler.getInstance().getLocation().getName(), thisLocationFairySouls); saveClickedFairySouls(); } public void resetClickedGifts() { clickedGifts.clear(); } @Override public boolean isRunning() { return MayOBeesConfig.chestESP || MayOBeesConfig.fairySoulESP || MayOBeesConfig.giftESP; } @SubscribeEvent public void onRender(RenderWorldLastEvent event) { if (!isRunning()) return; if (mc.thePlayer == null || mc.theWorld == null) return; if (GameStateHandler.getInstance().getLocation() == GameStateHandler.Location.TELEPORTING || GameStateHandler.getInstance().getLocation() == GameStateHandler.Location.PRIVATE_ISLAND) return; if (MayOBeesConfig.chestESP) { for (TileEntity tileEntityChest : mc.theWorld.loadedTileEntityList.stream().filter(tileEntity -> tileEntity instanceof TileEntityChest).collect(Collectors.toList())) { Block block = mc.theWorld.getBlockState(tileEntityChest.getPos()).getBlock(); block.setBlockBoundsBasedOnState(mc.theWorld, tileEntityChest.getPos()); AxisAlignedBB bb = block.getSelectedBoundingBox(mc.theWorld, tileEntityChest.getPos()).expand(0.002, 0.002, 0.002).offset(-mc.getRenderManager().viewerPosX, -mc.getRenderManager().viewerPosY, -mc.getRenderManager().viewerPosZ);
package com.github.may2beez.mayobees.module.impl.render; public class ESP implements IModule { private final Minecraft mc = Minecraft.getMinecraft(); private final HashMap<String, List<Location>> clickedFairySouls = new HashMap<>(); private final CopyOnWriteArrayList<EntityArmorStand> visibleFairySouls = new CopyOnWriteArrayList<>(); private final List<BlockPos> clickedGifts = new ArrayList<>(); private final File clickedFairySoulsFile = new File(mc.mcDataDir + "/config/mayobees/clickedFairySouls.json"); private static ESP instance; public static ESP getInstance() { if (instance == null) { instance = new ESP(); } return instance; } @Override public String getName() { return "ESP"; } public ESP() { try { if (!clickedFairySoulsFile.getParentFile().exists()) { clickedFairySoulsFile.getParentFile().mkdirs(); } if (!clickedFairySoulsFile.exists()) { clickedFairySoulsFile.createNewFile(); // fill it with empty array FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(clickedFairySoulsFile); String json = MayOBees.GSON.toJson(clickedFairySouls); fileOutputStream.write(json.getBytes()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } catch (IOException e) { throw new RuntimeException(e); } FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(clickedFairySoulsFile); byte[] bytes = new byte[fileInputStream.available()]; fileInputStream.read(bytes); String json = new String(bytes); if (json.isEmpty()) return; Type type = new TypeToken<HashMap<String, List<Location>>>() { }.getType(); try { HashMap<String, List<Location>> locations = MayOBees.GSON.fromJson(json, type); if (locations == null) return; clickedFairySouls.putAll(locations); } catch (Exception e) { e.printStackTrace(); saveClickedFairySouls(); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileInputStream != null) try { fileInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } private void saveClickedFairySouls() { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(clickedFairySoulsFile); String json = MayOBees.GSON.toJson(clickedFairySouls); fileOutputStream.write(json.getBytes()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } public void resetClickedFairySouls() { clickedFairySouls.clear(); saveClickedFairySouls(); } public void resetClickedFairySoulsOnlyCurrentIsland() { clickedFairySouls.remove(GameStateHandler.getInstance().getLocation().getName()); saveClickedFairySouls(); } public void addAllVisibleFairySoulsToClickedList() { List<Location> thisLocationFairySouls = clickedFairySouls.computeIfAbsent(GameStateHandler.getInstance().getLocation().getName(), k -> new ArrayList<>()); for (EntityArmorStand entityArmorStand : visibleFairySouls) { if (listHasElement(thisLocationFairySouls, Location.of(entityArmorStand.getPosition()))) continue; thisLocationFairySouls.add(Location.of(entityArmorStand.getPosition())); } clickedFairySouls.put(GameStateHandler.getInstance().getLocation().getName(), thisLocationFairySouls); saveClickedFairySouls(); } public void resetClickedGifts() { clickedGifts.clear(); } @Override public boolean isRunning() { return MayOBeesConfig.chestESP || MayOBeesConfig.fairySoulESP || MayOBeesConfig.giftESP; } @SubscribeEvent public void onRender(RenderWorldLastEvent event) { if (!isRunning()) return; if (mc.thePlayer == null || mc.theWorld == null) return; if (GameStateHandler.getInstance().getLocation() == GameStateHandler.Location.TELEPORTING || GameStateHandler.getInstance().getLocation() == GameStateHandler.Location.PRIVATE_ISLAND) return; if (MayOBeesConfig.chestESP) { for (TileEntity tileEntityChest : mc.theWorld.loadedTileEntityList.stream().filter(tileEntity -> tileEntity instanceof TileEntityChest).collect(Collectors.toList())) { Block block = mc.theWorld.getBlockState(tileEntityChest.getPos()).getBlock(); block.setBlockBoundsBasedOnState(mc.theWorld, tileEntityChest.getPos()); AxisAlignedBB bb = block.getSelectedBoundingBox(mc.theWorld, tileEntityChest.getPos()).expand(0.002, 0.002, 0.002).offset(-mc.getRenderManager().viewerPosX, -mc.getRenderManager().viewerPosY, -mc.getRenderManager().viewerPosZ);
RenderUtils.drawBox(bb, MayOBeesConfig.chestESPColor.toJavaColor());
6
2023-12-24 15:39:11+00:00
16k
Trodev-IT/ScanHub
app/src/main/java/com/trodev/scanhub/HomeFragment.java
[ { "identifier": "EmailActivity", "path": "app/src/main/java/com/trodev/scanhub/activities/EmailActivity.java", "snippet": "public class EmailActivity extends AppCompatActivity {\n\n public final static int QRCodeWidth = 500;\n Bitmap bitmap;\n private Button make_btn, save_btn, downloadBtn;\n ...
import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.google.android.material.card.MaterialCardView; import com.trodev.scanhub.activities.EmailActivity; import com.trodev.scanhub.activities.LocationActivity; import com.trodev.scanhub.activities.ProductQrActivity; import com.trodev.scanhub.activities.ScanGalleryActivity; import com.trodev.scanhub.activities.ScannerActivity; import com.trodev.scanhub.activities.SmsActivity; import com.trodev.scanhub.activities.URLActivity; import com.trodev.scanhub.activities.WifiQrActivity;
12,452
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() { startActivity(new Intent(getContext(), URLActivity.class)); } private void goto_location() { startActivity(new Intent(getContext(), LocationActivity.class)); } private void goto_email() { startActivity(new Intent(getContext(), EmailActivity.class)); } private void goto_wifi() {
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() { startActivity(new Intent(getContext(), URLActivity.class)); } private void goto_location() { startActivity(new Intent(getContext(), LocationActivity.class)); } private void goto_email() { startActivity(new Intent(getContext(), EmailActivity.class)); } private void goto_wifi() {
startActivity(new Intent(getContext(), WifiQrActivity.class));
7
2023-12-26 05:10:38+00:00
16k
piovas-lu/condominio
src/main/java/app/condominio/service/RelatorioServiceImpl.java
[ { "identifier": "Categoria", "path": "src/main/java/app/condominio/domain/Categoria.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"categorias\")\r\npublic class Categoria implements Serializable, Comparable<Categoria> {\r\n\r\n\tpublic static final int NIVEL_MAX = 4;\r\n\...
import java.math.BigDecimal; import java.time.LocalDate; import java.time.YearMonth; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import app.condominio.domain.Categoria; import app.condominio.domain.Cobranca; import app.condominio.domain.Conta; import app.condominio.domain.Moradia; import app.condominio.domain.Movimento; import app.condominio.domain.Orcamento; import app.condominio.domain.Periodo; import app.condominio.domain.Subcategoria; import app.condominio.domain.enums.TipoCategoria;
11,183
} if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public BigDecimal[] receitaDespesaMesAtual() { List<Conta> contas = contaService.listar(); YearMonth mesAtual = YearMonth.from(LocalDate.now()); // mesAtual = mesAtual.minusMonths(1); // Mês anterior para testes return receitaDespesaEntre(contas, mesAtual.atDay(1), mesAtual.atEndOfMonth()); } @Override public BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); return receitaDespesaEntre(contas, inicio, fim); } @Override public BigDecimal[] receitaDespesaRealizadaPeriodoAtual() { List<Conta> contas = contaService.listar(); Periodo periodoAtual = periodoService.ler(LocalDate.now()); if (periodoAtual != null) { return receitaDespesaEntre(contas, periodoAtual.getInicio(), periodoAtual.getFim()); } else { BigDecimal[] resultado = new BigDecimal[2]; resultado[0] = BigDecimal.ZERO.setScale(2); resultado[1] = BigDecimal.ZERO.setScale(2); return resultado; } } @Override public BigDecimal[] receitaDespesaOrcadaPeriodoAtual() { Periodo periodoAtual = periodoService.ler(LocalDate.now()); BigDecimal[] resultado = new BigDecimal[2]; if (periodoAtual != null) { resultado[0] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.R); resultado[1] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.D); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public List<Movimento> lancamentosEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Movimento> lancamentos = new ArrayList<>(); lancamentos.addAll(movimentoService.listarLancamentosEntre(contas, inicio, fim)); return lancamentos; } return new ArrayList<>(); } @Override public BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial) { if (saldoInicial == null) { saldoInicial = BigDecimal.ZERO.setScale(2); } if (!movimentos.isEmpty()) { BigDecimal[] saldos = new BigDecimal[movimentos.size()]; Movimento movimento = movimentos.get(0); // Preenche o primeiro saldo if (movimento.getReducao()) { saldos[0] = saldoInicial.subtract(movimento.getValor()); } else { saldos[0] = saldoInicial.add(movimento.getValor()); } // Preenche os outros saldos for (int i = 1; i < saldos.length; i++) { movimento = movimentos.get(i); if (movimento.getReducao()) { saldos[i] = saldos[i - 1].subtract(movimento.getValor()); } else { saldos[i] = saldos[i - 1].add(movimento.getValor()); } } return saldos; } else { BigDecimal[] vazio = new BigDecimal[1]; vazio[0] = saldoInicial; return vazio; } } @Override public SortedMap<Subcategoria, BigDecimal> somasPorTipoEntre(LocalDate inicio, LocalDate fim, TipoCategoria tipoCategoria) { SortedMap<Subcategoria, BigDecimal> map = new TreeMap<>(); List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Subcategoria> subcategorias; if (TipoCategoria.R.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarReceitas(); } else if (TipoCategoria.D.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarDespesas(); } else { return map; } for (Subcategoria subcategoria : subcategorias) { BigDecimal soma = movimentoService.somaLancamentosEntre(contas, inicio, fim, subcategoria); if (soma != null && soma.compareTo(BigDecimal.ZERO) != 0) { map.put(subcategoria, soma); } } } return map; } @Override
package app.condominio.service; @Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class RelatorioServiceImpl implements RelatorioService { @Autowired ContaService contaService; @Autowired MovimentoService movimentoService; @Autowired CobrancaService cobrancaService; @Autowired OrcamentoService orcamentoService; @Autowired PeriodoService periodoService; @Autowired SubcategoriaService subcategoriaService; @Autowired CategoriaService categoriaService; @Override public BigDecimal saldoAtualTodasContas() { return contaService.saldoAtual(); } @Override public BigDecimal saldoInicialTodasContasEm(LocalDate data) { BigDecimal saldo = contaService.saldoAtual(); BigDecimal[] lancamentos = receitaDespesaDesde(contaService.listar(), data); return saldo.subtract(lancamentos[0]).add(lancamentos[1]); } @Override public BigDecimal saldoFinalTodasContasEm(LocalDate data) { return saldoInicialTodasContasEm(data.plusDays(1)); } @Override public BigDecimal inadimplenciaAtual() { return cobrancaService.inadimplencia(); } private BigDecimal[] receitaDespesaEntre(Collection<Conta> contas, LocalDate inicio, LocalDate fim) { BigDecimal[] resultado = new BigDecimal[2]; if (!contas.isEmpty()) { resultado[0] = movimentoService.somaLancamentosEntre(contas, inicio, fim, Boolean.FALSE); resultado[1] = movimentoService.somaLancamentosEntre(contas, inicio, fim, Boolean.TRUE); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } private BigDecimal[] receitaDespesaDesde(Collection<Conta> contas, LocalDate inicio) { BigDecimal[] resultado = new BigDecimal[2]; if (!contas.isEmpty()) { resultado[0] = movimentoService.somaLancamentosDesde(contas, inicio, Boolean.FALSE); resultado[1] = movimentoService.somaLancamentosDesde(contas, inicio, Boolean.TRUE); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public BigDecimal[] receitaDespesaMesAtual() { List<Conta> contas = contaService.listar(); YearMonth mesAtual = YearMonth.from(LocalDate.now()); // mesAtual = mesAtual.minusMonths(1); // Mês anterior para testes return receitaDespesaEntre(contas, mesAtual.atDay(1), mesAtual.atEndOfMonth()); } @Override public BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); return receitaDespesaEntre(contas, inicio, fim); } @Override public BigDecimal[] receitaDespesaRealizadaPeriodoAtual() { List<Conta> contas = contaService.listar(); Periodo periodoAtual = periodoService.ler(LocalDate.now()); if (periodoAtual != null) { return receitaDespesaEntre(contas, periodoAtual.getInicio(), periodoAtual.getFim()); } else { BigDecimal[] resultado = new BigDecimal[2]; resultado[0] = BigDecimal.ZERO.setScale(2); resultado[1] = BigDecimal.ZERO.setScale(2); return resultado; } } @Override public BigDecimal[] receitaDespesaOrcadaPeriodoAtual() { Periodo periodoAtual = periodoService.ler(LocalDate.now()); BigDecimal[] resultado = new BigDecimal[2]; if (periodoAtual != null) { resultado[0] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.R); resultado[1] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.D); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public List<Movimento> lancamentosEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Movimento> lancamentos = new ArrayList<>(); lancamentos.addAll(movimentoService.listarLancamentosEntre(contas, inicio, fim)); return lancamentos; } return new ArrayList<>(); } @Override public BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial) { if (saldoInicial == null) { saldoInicial = BigDecimal.ZERO.setScale(2); } if (!movimentos.isEmpty()) { BigDecimal[] saldos = new BigDecimal[movimentos.size()]; Movimento movimento = movimentos.get(0); // Preenche o primeiro saldo if (movimento.getReducao()) { saldos[0] = saldoInicial.subtract(movimento.getValor()); } else { saldos[0] = saldoInicial.add(movimento.getValor()); } // Preenche os outros saldos for (int i = 1; i < saldos.length; i++) { movimento = movimentos.get(i); if (movimento.getReducao()) { saldos[i] = saldos[i - 1].subtract(movimento.getValor()); } else { saldos[i] = saldos[i - 1].add(movimento.getValor()); } } return saldos; } else { BigDecimal[] vazio = new BigDecimal[1]; vazio[0] = saldoInicial; return vazio; } } @Override public SortedMap<Subcategoria, BigDecimal> somasPorTipoEntre(LocalDate inicio, LocalDate fim, TipoCategoria tipoCategoria) { SortedMap<Subcategoria, BigDecimal> map = new TreeMap<>(); List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Subcategoria> subcategorias; if (TipoCategoria.R.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarReceitas(); } else if (TipoCategoria.D.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarDespesas(); } else { return map; } for (Subcategoria subcategoria : subcategorias) { BigDecimal soma = movimentoService.somaLancamentosEntre(contas, inicio, fim, subcategoria); if (soma != null && soma.compareTo(BigDecimal.ZERO) != 0) { map.put(subcategoria, soma); } } } return map; } @Override
public SortedMap<Moradia, List<Cobranca>> inadimplenciaAtualDetalhada() {
3
2023-12-29 22:19:42+00:00
16k
HuXin0817/shop_api
framework/src/main/java/cn/lili/modules/member/serviceimpl/GoodsCollectionServiceImpl.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.exception.ServiceException; import cn.lili.common.security.context.UserContext; import cn.lili.common.vo.PageVO; import cn.lili.modules.member.entity.dos.GoodsCollection; import cn.lili.modules.member.entity.vo.GoodsCollectionVO; import cn.lili.modules.member.mapper.GoodsCollectionMapper; import cn.lili.modules.member.service.GoodsCollectionService; import cn.lili.mybatis.util.PageUtil; 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.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional;
12,269
package cn.lili.modules.member.serviceimpl; /** * 会员收藏业务层实现 * * @author Chopper * @since 2020/11/18 2:25 下午 */ @Service public class GoodsCollectionServiceImpl extends ServiceImpl<GoodsCollectionMapper, GoodsCollection> implements GoodsCollectionService { @Override public IPage<GoodsCollectionVO> goodsCollection(PageVO pageVo) { QueryWrapper<GoodsCollectionVO> queryWrapper = new QueryWrapper(); queryWrapper.eq("gc.member_id", UserContext.getCurrentUser().getId()); queryWrapper.groupBy("gc.id"); queryWrapper.orderByDesc("gc.create_time"); return this.baseMapper.goodsCollectionVOList(PageUtil.initPage(pageVo), queryWrapper); } @Override public boolean isCollection(String skuId) { QueryWrapper<GoodsCollection> queryWrapper = new QueryWrapper(); queryWrapper.eq("member_id", UserContext.getCurrentUser().getId()); queryWrapper.eq(skuId != null, "sku_id", skuId); return Optional.ofNullable(this.getOne(queryWrapper)).isPresent(); } @Override public GoodsCollection addGoodsCollection(String skuId) { GoodsCollection goodsCollection = this.getOne(new LambdaUpdateWrapper<GoodsCollection>() .eq(GoodsCollection::getMemberId, UserContext.getCurrentUser().getId()) .eq(GoodsCollection::getSkuId, skuId)); if (goodsCollection == null) { goodsCollection = new GoodsCollection(UserContext.getCurrentUser().getId(), skuId); this.save(goodsCollection); return goodsCollection; }
package cn.lili.modules.member.serviceimpl; /** * 会员收藏业务层实现 * * @author Chopper * @since 2020/11/18 2:25 下午 */ @Service public class GoodsCollectionServiceImpl extends ServiceImpl<GoodsCollectionMapper, GoodsCollection> implements GoodsCollectionService { @Override public IPage<GoodsCollectionVO> goodsCollection(PageVO pageVo) { QueryWrapper<GoodsCollectionVO> queryWrapper = new QueryWrapper(); queryWrapper.eq("gc.member_id", UserContext.getCurrentUser().getId()); queryWrapper.groupBy("gc.id"); queryWrapper.orderByDesc("gc.create_time"); return this.baseMapper.goodsCollectionVOList(PageUtil.initPage(pageVo), queryWrapper); } @Override public boolean isCollection(String skuId) { QueryWrapper<GoodsCollection> queryWrapper = new QueryWrapper(); queryWrapper.eq("member_id", UserContext.getCurrentUser().getId()); queryWrapper.eq(skuId != null, "sku_id", skuId); return Optional.ofNullable(this.getOne(queryWrapper)).isPresent(); } @Override public GoodsCollection addGoodsCollection(String skuId) { GoodsCollection goodsCollection = this.getOne(new LambdaUpdateWrapper<GoodsCollection>() .eq(GoodsCollection::getMemberId, UserContext.getCurrentUser().getId()) .eq(GoodsCollection::getSkuId, skuId)); if (goodsCollection == null) { goodsCollection = new GoodsCollection(UserContext.getCurrentUser().getId(), skuId); this.save(goodsCollection); return goodsCollection; }
throw new ServiceException(ResultCode.USER_COLLECTION_EXIST);
1
2023-12-24 19:45:18+00:00
16k
huidongyin/kafka-2.7.2
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/WorkerTaskTest.java
[ { "identifier": "Time", "path": "clients/src/main/java/org/apache/kafka/common/utils/Time.java", "snippet": "public interface Time {\n\n Time SYSTEM = new SystemTime();\n\n /**\n * Returns the current time in milliseconds.\n */\n long milliseconds();\n\n /**\n * Returns the value...
import org.apache.kafka.common.utils.Time; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.runtime.WorkerTask.TaskMetricsGroup; import org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator; import org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperatorTest; import org.apache.kafka.connect.sink.SinkTask; import org.apache.kafka.connect.storage.StatusBackingStore; import org.apache.kafka.connect.util.ConnectorTaskId; import org.apache.kafka.common.utils.MockTime; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.easymock.Mock; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.partialMockBuilder; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals;
12,519
EasyMock.expectLastCall(); replay(workerTask); workerTask.initialize(TASK_CONFIG); workerTask.stop(); workerTask.awaitStop(1000L); // now run should not do anything workerTask.run(); verify(workerTask); } @Test public void cancelBeforeStopping() throws Exception { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask workerTask = partialMockBuilder(WorkerTask.class) .withConstructor( ConnectorTaskId.class, TaskStatus.Listener.class, TargetState.class, ClassLoader.class, ConnectMetrics.class, RetryWithToleranceOperator.class, Time.class, StatusBackingStore.class ) .withArgs(taskId, statusListener, TargetState.STARTED, loader, metrics, retryWithToleranceOperator, Time.SYSTEM, statusBackingStore) .addMockedMethod("initialize") .addMockedMethod("initializeAndStart") .addMockedMethod("execute") .addMockedMethod("close") .createStrictMock(); final CountDownLatch stopped = new CountDownLatch(1); final Thread thread = new Thread() { @Override public void run() { try { stopped.await(); } catch (Exception e) { } } }; workerTask.initialize(TASK_CONFIG); EasyMock.expectLastCall(); workerTask.initializeAndStart(); EasyMock.expectLastCall(); workerTask.execute(); expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { thread.start(); return null; } }); statusListener.onStartup(taskId); expectLastCall(); workerTask.close(); expectLastCall(); // there should be no call to onShutdown() replay(workerTask); workerTask.initialize(TASK_CONFIG); workerTask.run(); workerTask.stop(); workerTask.cancel(); stopped.countDown(); thread.join(); verify(workerTask); } @Test public void updateMetricsOnListenerEventsForStartupPauseResumeAndShutdown() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); ConnectMetrics metrics = new MockConnectMetrics(); TaskMetricsGroup group = new TaskMetricsGroup(taskId, metrics, statusListener); statusListener.onStartup(taskId); expectLastCall(); statusListener.onPause(taskId); expectLastCall(); statusListener.onResume(taskId); expectLastCall(); statusListener.onShutdown(taskId); expectLastCall(); replay(statusListener); group.onStartup(taskId); assertRunningMetric(group); group.onPause(taskId); assertPausedMetric(group); group.onResume(taskId); assertRunningMetric(group); group.onShutdown(taskId); assertStoppedMetric(group); verify(statusListener); } @Test public void updateMetricsOnListenerEventsForStartupPauseResumeAndFailure() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); MockConnectMetrics metrics = new MockConnectMetrics();
/* * 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.connect.runtime; @RunWith(PowerMockRunner.class) @PrepareForTest({WorkerTask.class}) @PowerMockIgnore("javax.management.*") public class WorkerTaskTest { private static final Map<String, String> TASK_PROPS = new HashMap<>(); static { TASK_PROPS.put(TaskConfig.TASK_CLASS_CONFIG, TestSinkTask.class.getName()); } private static final TaskConfig TASK_CONFIG = new TaskConfig(TASK_PROPS); private ConnectMetrics metrics; @Mock private TaskStatus.Listener statusListener; @Mock private ClassLoader loader; RetryWithToleranceOperator retryWithToleranceOperator; @Mock StatusBackingStore statusBackingStore; @Before public void setup() { metrics = new MockConnectMetrics(); retryWithToleranceOperator = RetryWithToleranceOperatorTest.NOOP_OPERATOR; } @After public void tearDown() { if (metrics != null) metrics.stop(); } @Test public void standardStartup() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask workerTask = partialMockBuilder(WorkerTask.class) .withConstructor( ConnectorTaskId.class, TaskStatus.Listener.class, TargetState.class, ClassLoader.class, ConnectMetrics.class, RetryWithToleranceOperator.class, Time.class, StatusBackingStore.class ) .withArgs(taskId, statusListener, TargetState.STARTED, loader, metrics, retryWithToleranceOperator, Time.SYSTEM, statusBackingStore) .addMockedMethod("initialize") .addMockedMethod("initializeAndStart") .addMockedMethod("execute") .addMockedMethod("close") .createStrictMock(); workerTask.initialize(TASK_CONFIG); expectLastCall(); workerTask.initializeAndStart(); expectLastCall(); workerTask.execute(); expectLastCall(); statusListener.onStartup(taskId); expectLastCall(); workerTask.close(); expectLastCall(); statusListener.onShutdown(taskId); expectLastCall(); replay(workerTask); workerTask.initialize(TASK_CONFIG); workerTask.run(); workerTask.stop(); workerTask.awaitStop(1000L); verify(workerTask); } @Test public void stopBeforeStarting() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask workerTask = partialMockBuilder(WorkerTask.class) .withConstructor( ConnectorTaskId.class, TaskStatus.Listener.class, TargetState.class, ClassLoader.class, ConnectMetrics.class, RetryWithToleranceOperator.class, Time.class, StatusBackingStore.class ) .withArgs(taskId, statusListener, TargetState.STARTED, loader, metrics, retryWithToleranceOperator, Time.SYSTEM, statusBackingStore) .addMockedMethod("initialize") .addMockedMethod("execute") .addMockedMethod("close") .createStrictMock(); workerTask.initialize(TASK_CONFIG); EasyMock.expectLastCall(); workerTask.close(); EasyMock.expectLastCall(); replay(workerTask); workerTask.initialize(TASK_CONFIG); workerTask.stop(); workerTask.awaitStop(1000L); // now run should not do anything workerTask.run(); verify(workerTask); } @Test public void cancelBeforeStopping() throws Exception { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask workerTask = partialMockBuilder(WorkerTask.class) .withConstructor( ConnectorTaskId.class, TaskStatus.Listener.class, TargetState.class, ClassLoader.class, ConnectMetrics.class, RetryWithToleranceOperator.class, Time.class, StatusBackingStore.class ) .withArgs(taskId, statusListener, TargetState.STARTED, loader, metrics, retryWithToleranceOperator, Time.SYSTEM, statusBackingStore) .addMockedMethod("initialize") .addMockedMethod("initializeAndStart") .addMockedMethod("execute") .addMockedMethod("close") .createStrictMock(); final CountDownLatch stopped = new CountDownLatch(1); final Thread thread = new Thread() { @Override public void run() { try { stopped.await(); } catch (Exception e) { } } }; workerTask.initialize(TASK_CONFIG); EasyMock.expectLastCall(); workerTask.initializeAndStart(); EasyMock.expectLastCall(); workerTask.execute(); expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { thread.start(); return null; } }); statusListener.onStartup(taskId); expectLastCall(); workerTask.close(); expectLastCall(); // there should be no call to onShutdown() replay(workerTask); workerTask.initialize(TASK_CONFIG); workerTask.run(); workerTask.stop(); workerTask.cancel(); stopped.countDown(); thread.join(); verify(workerTask); } @Test public void updateMetricsOnListenerEventsForStartupPauseResumeAndShutdown() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); ConnectMetrics metrics = new MockConnectMetrics(); TaskMetricsGroup group = new TaskMetricsGroup(taskId, metrics, statusListener); statusListener.onStartup(taskId); expectLastCall(); statusListener.onPause(taskId); expectLastCall(); statusListener.onResume(taskId); expectLastCall(); statusListener.onShutdown(taskId); expectLastCall(); replay(statusListener); group.onStartup(taskId); assertRunningMetric(group); group.onPause(taskId); assertPausedMetric(group); group.onResume(taskId); assertRunningMetric(group); group.onShutdown(taskId); assertStoppedMetric(group); verify(statusListener); } @Test public void updateMetricsOnListenerEventsForStartupPauseResumeAndFailure() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); MockConnectMetrics metrics = new MockConnectMetrics();
MockTime time = metrics.time();
8
2023-12-23 07:12:18+00:00
16k
IGinX-THU/Parquet
src/main/java/org/apache/parquet/local/filter2/compat/RowGroupFilter.java
[ { "identifier": "ParquetFileReader", "path": "src/main/java/org/apache/parquet/local/ParquetFileReader.java", "snippet": "public class ParquetFileReader implements Closeable {\n\n private static final Logger LOG = LoggerFactory.getLogger(ParquetFileReader.class);\n\n private final ParquetMetadataConve...
import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.apache.parquet.filter2.compat.FilterCompat; import org.apache.parquet.filter2.compat.FilterCompat.Filter; import org.apache.parquet.filter2.compat.FilterCompat.NoOpFilter; import org.apache.parquet.filter2.compat.FilterCompat.Visitor; import org.apache.parquet.filter2.dictionarylevel.DictionaryFilter; import org.apache.parquet.filter2.predicate.FilterPredicate; import org.apache.parquet.filter2.predicate.SchemaCompatibilityValidator; import org.apache.parquet.filter2.statisticslevel.StatisticsFilter; import org.apache.parquet.hadoop.metadata.BlockMetaData; import org.apache.parquet.local.ParquetFileReader; import org.apache.parquet.local.filter2.bloomfilterlevel.BloomFilterImpl; import org.apache.parquet.schema.MessageType;
13,191
/* * 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.parquet.local.filter2.compat; /** * Given a {@link Filter} applies it to a list of BlockMetaData (row groups) If the Filter is an * {@link org.apache.parquet.filter.UnboundRecordFilter} or the no op filter, no filtering will be * performed. */ public class RowGroupFilter implements Visitor<List<BlockMetaData>> { private final List<BlockMetaData> blocks; private final MessageType schema; private final List<FilterLevel> levels;
/* * 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.parquet.local.filter2.compat; /** * Given a {@link Filter} applies it to a list of BlockMetaData (row groups) If the Filter is an * {@link org.apache.parquet.filter.UnboundRecordFilter} or the no op filter, no filtering will be * performed. */ public class RowGroupFilter implements Visitor<List<BlockMetaData>> { private final List<BlockMetaData> blocks; private final MessageType schema; private final List<FilterLevel> levels;
private final ParquetFileReader reader;
0
2023-12-29 01:48:28+00:00
16k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/util/MyTaskUtils.java
[ { "identifier": "systemSetting", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/systemSetting.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class systemSetting {\n /**\n * 绑定IP和端口\n */\n private String bing;\n /**\n * 请求的超时时间\n */\n...
import com.tokensTool.pandoraNext.pojo.systemSetting; import com.tokensTool.pandoraNext.service.impl.apiServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Service; import java.util.concurrent.ScheduledFuture;
11,786
package com.tokensTool.pandoraNext.util; @Slf4j @Service public class MyTaskUtils { private final TaskScheduler taskScheduler; @Autowired
package com.tokensTool.pandoraNext.util; @Slf4j @Service public class MyTaskUtils { private final TaskScheduler taskScheduler; @Autowired
private apiServiceImpl apiService;
1
2023-11-17 11:37:37+00:00
16k
quarkiverse/quarkus-langchain4j
core/deployment/src/main/java/io/quarkiverse/langchain4j/deployment/AiServicesProcessor.java
[ { "identifier": "illegalConfigurationForMethod", "path": "core/deployment/src/main/java/io/quarkiverse/langchain4j/deployment/ExceptionUtil.java", "snippet": "static IllegalConfigurationException illegalConfigurationForMethod(String message, MethodInfo offendingMethod) {\n String effectiveMessage = m...
import static dev.langchain4j.exception.IllegalConfigurationException.illegalConfiguration; import static dev.langchain4j.service.ServiceOutputParser.outputFormatInstructions; import static io.quarkiverse.langchain4j.deployment.ExceptionUtil.illegalConfigurationForMethod; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.ClassType; import org.jboss.jandex.DotName; import org.jboss.jandex.IndexView; import org.jboss.jandex.MethodInfo; import org.jboss.jandex.MethodParameterInfo; import org.jboss.jandex.ParameterizedType; import org.jboss.jandex.Type; import org.jboss.logging.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.AnalyzerException; import dev.langchain4j.exception.IllegalConfigurationException; import dev.langchain4j.service.V; import io.quarkiverse.langchain4j.deployment.items.SelectedChatModelProviderBuildItem; import io.quarkiverse.langchain4j.runtime.AiServicesRecorder; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceClassCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceMethodCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceMethodImplementationSupport; import io.quarkiverse.langchain4j.runtime.aiservice.ChatMemoryRemovable; import io.quarkiverse.langchain4j.runtime.aiservice.DeclarativeAiServiceCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.MetricsCountedWrapper; import io.quarkiverse.langchain4j.runtime.aiservice.MetricsTimedWrapper; import io.quarkiverse.langchain4j.runtime.aiservice.QuarkusAiServiceContext; import io.quarkiverse.langchain4j.runtime.aiservice.SpanWrapper; import io.quarkus.arc.Arc; import io.quarkus.arc.ArcContainer; import io.quarkus.arc.InstanceHandle; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.arc.deployment.GeneratedBeanBuildItem; import io.quarkus.arc.deployment.GeneratedBeanGizmoAdaptor; import io.quarkus.arc.deployment.SyntheticBeanBuildItem; import io.quarkus.arc.deployment.UnremovableBeanBuildItem; import io.quarkus.arc.processor.BuiltinScope; import io.quarkus.arc.processor.ScopeInfo; import io.quarkus.builder.item.MultiBuildItem; import io.quarkus.deployment.Capabilities; import io.quarkus.deployment.Capability; import io.quarkus.deployment.GeneratedClassGizmoAdaptor; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.ExecutionTime; import io.quarkus.deployment.annotations.Record; import io.quarkus.deployment.builditem.CombinedIndexBuildItem; import io.quarkus.deployment.builditem.GeneratedClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; import io.quarkus.deployment.metrics.MetricsCapabilityBuildItem; import io.quarkus.gizmo.ClassCreator; import io.quarkus.gizmo.ClassOutput; import io.quarkus.gizmo.FieldDescriptor; import io.quarkus.gizmo.Gizmo; import io.quarkus.gizmo.MethodCreator; import io.quarkus.gizmo.MethodDescriptor; import io.quarkus.gizmo.ResultHandle; import io.quarkus.runtime.metrics.MetricsFactory;
13,163
new Type[] { ClassType.create(Langchain4jDotNames.TEXT_SEGMENT) }, null) }, null)); needsRetrieverBean = true; } if (Langchain4jDotNames.BEAN_IF_EXISTS_AUDIT_SERVICE_SUPPLIER.toString().equals(auditServiceClassSupplierName)) { configurator.addInjectionPoint(ParameterizedType.create(CDI_INSTANCE, new Type[] { ClassType.create(Langchain4jDotNames.AUDIT_SERVICE) }, null)); needsAuditServiceBean = true; } if (Langchain4jDotNames.BEAN_MODERATION_MODEL_SUPPLIER.toString().equals(moderationModelSupplierClassName)) { configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.MODERATION_MODEL)); needsModerationModelBean = true; } syntheticBeanProducer.produce(configurator.done()); } if (needsChatModelBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.CHAT_MODEL)); } if (needsChatMemoryProviderBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.CHAT_MEMORY_PROVIDER)); } if (needsRetrieverBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.RETRIEVER)); } if (needsAuditServiceBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.AUDIT_SERVICE)); } if (needsModerationModelBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.MODERATION_MODEL)); } if (!allToolNames.isEmpty()) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(allToolNames)); } } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void handleAiServices(AiServicesRecorder recorder, CombinedIndexBuildItem indexBuildItem, List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems, BuildProducer<GeneratedClassBuildItem> generatedClassProducer, BuildProducer<GeneratedBeanBuildItem> generatedBeanProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer, BuildProducer<AiServicesMethodBuildItem> aiServicesMethodProducer, BuildProducer<AdditionalBeanBuildItem> additionalBeanProducer, Optional<MetricsCapabilityBuildItem> metricsCapability, Capabilities capabilities) { IndexView index = indexBuildItem.getIndex(); List<AiServicesUseAnalyzer.Result.Entry> aiServicesAnalysisResults = new ArrayList<>(); for (ClassInfo classInfo : index.getKnownUsers(Langchain4jDotNames.AI_SERVICES)) { String className = classInfo.name().toString(); if (className.startsWith("io.quarkiverse.langchain4j") || className.startsWith("dev.langchain4j")) { // TODO: this can be made smarter if needed continue; } try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( className.replace('.', '/') + ".class")) { if (is == null) { return; } var cn = new ClassNode(Gizmo.ASM_API_VERSION); var cr = new ClassReader(is); cr.accept(cn, 0); for (MethodNode method : cn.methods) { aiServicesAnalysisResults.addAll(AiServicesUseAnalyzer.analyze(cn, method).entries); } } catch (IOException e) { throw new UncheckedIOException("Reading bytecode of class '" + className + "' failed", e); } catch (AnalyzerException e) { log.debug("Unable to analyze bytecode of class '" + className + "'", e); } } Map<String, Boolean> nameToUsed = aiServicesAnalysisResults.stream() .collect(Collectors.toMap(e -> e.createdClassName, e -> e.chatMemoryProviderUsed, (u1, u2) -> u1 || u2)); for (var entry : nameToUsed.entrySet()) { String className = entry.getKey(); ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { continue; } if (!classInfo.annotations(Langchain4jDotNames.MEMORY_ID).isEmpty() && !entry.getValue()) { log.warn("Class '" + className + "' is used in AiServices and while it leverages @MemoryId, a ChatMemoryProvider has not been configured. This will likely result in an exception being thrown when the service is used."); } } Set<String> detectedForCreate = new HashSet<>(nameToUsed.keySet()); addCreatedAware(index, detectedForCreate); addIfacesWithMessageAnns(index, detectedForCreate); Set<String> registeredAiServiceClassNames = declarativeAiServiceItems.stream() .map(bi -> bi.getServiceClassInfo().name().toString()).collect( Collectors.toUnmodifiableSet()); detectedForCreate.addAll(registeredAiServiceClassNames); Set<ClassInfo> ifacesForCreate = new HashSet<>(); for (String className : detectedForCreate) { ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { log.warn("'" + className + "' used for creating an AiService was not found in the Quarkus index. Attempting to create " + "an AiService using this class will fail"); continue; } if (!classInfo.isInterface()) { log.warn("'" + className + "' used for creating an AiService is not an interface. Attempting to create an AiService " + "using this class will fail"); } ifacesForCreate.add(classInfo); } var addMicrometerMetrics = metricsCapability.isPresent() && metricsCapability.get().metricsSupported(MetricsFactory.MICROMETER); if (addMicrometerMetrics) {
package io.quarkiverse.langchain4j.deployment; @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public class AiServicesProcessor { private static final Logger log = Logger.getLogger(AiServicesProcessor.class); private static final DotName V = DotName.createSimple(V.class); public static final DotName MICROMETER_TIMED = DotName.createSimple("io.micrometer.core.annotation.Timed"); public static final DotName MICROMETER_COUNTED = DotName.createSimple("io.micrometer.core.annotation.Counted"); private static final String DEFAULT_DELIMITER = "\n"; private static final Predicate<AnnotationInstance> IS_METHOD_PARAMETER_ANNOTATION = ai -> ai.target() .kind() == AnnotationTarget.Kind.METHOD_PARAMETER; private static final Function<AnnotationInstance, Integer> METHOD_PARAMETER_POSITION_FUNCTION = ai -> Integer .valueOf(ai.target() .asMethodParameter().position()); public static final MethodDescriptor OBJECT_CONSTRUCTOR = MethodDescriptor.ofConstructor(Object.class); private static final MethodDescriptor RECORDER_METHOD_CREATE_INFO = MethodDescriptor.ofMethod(AiServicesRecorder.class, "getAiServiceMethodCreateInfo", AiServiceMethodCreateInfo.class, String.class, String.class); private static final MethodDescriptor SUPPORT_IMPLEMENT = MethodDescriptor.ofMethod( AiServiceMethodImplementationSupport.class, "implement", Object.class, AiServiceMethodImplementationSupport.Input.class); private static final MethodDescriptor QUARKUS_AI_SERVICES_CONTEXT_CLOSE = MethodDescriptor.ofMethod( QuarkusAiServiceContext.class, "close", void.class); private static final MethodDescriptor QUARKUS_AI_SERVICES_CONTEXT_REMOVE_CHAT_MEMORY_IDS = MethodDescriptor.ofMethod( QuarkusAiServiceContext.class, "removeChatMemoryIds", void.class, Object[].class); public static final DotName CDI_INSTANCE = DotName.createSimple(Instance.class); private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final String METRICS_DEFAULT_NAME = "langchain4j.aiservices"; @BuildStep public void nativeSupport(CombinedIndexBuildItem indexBuildItem, List<AiServicesMethodBuildItem> aiServicesMethodBuildItems, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer) { IndexView index = indexBuildItem.getIndex(); Collection<AnnotationInstance> instances = index.getAnnotations(Langchain4jDotNames.DESCRIPTION); Set<ClassInfo> classesUsingDescription = new HashSet<>(); for (AnnotationInstance instance : instances) { if (instance.target().kind() != AnnotationTarget.Kind.FIELD) { continue; } classesUsingDescription.add(instance.target().asField().declaringClass()); } if (!classesUsingDescription.isEmpty()) { reflectiveClassProducer.produce(ReflectiveClassBuildItem .builder(classesUsingDescription.stream().map(i -> i.name().toString()).toArray(String[]::new)).fields(true) .build()); } Set<DotName> returnTypesToRegister = new HashSet<>(); for (AiServicesMethodBuildItem aiServicesMethodBuildItem : aiServicesMethodBuildItems) { Type type = aiServicesMethodBuildItem.methodInfo.returnType(); if (type.kind() == Type.Kind.PRIMITIVE) { continue; } DotName returnTypeName = type.name(); if (returnTypeName.toString().startsWith("java.")) { continue; } returnTypesToRegister.add(returnTypeName); } if (!returnTypesToRegister.isEmpty()) { reflectiveClassProducer.produce(ReflectiveClassBuildItem .builder(returnTypesToRegister.stream().map(DotName::toString).toArray(String[]::new)) .constructors(false) .build()); } } @BuildStep public void findDeclarativeServices(CombinedIndexBuildItem indexBuildItem, BuildProducer<RequestChatModelBeanBuildItem> requestChatModelBeanProducer, BuildProducer<RequestModerationModelBeanBuildItem> requestModerationModelBeanProducer, BuildProducer<DeclarativeAiServiceBuildItem> declarativeAiServiceProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer) { IndexView index = indexBuildItem.getIndex(); boolean needChatModelBean = false; boolean needModerationModelBean = false; for (AnnotationInstance instance : index.getAnnotations(Langchain4jDotNames.REGISTER_AI_SERVICES)) { if (instance.target().kind() != AnnotationTarget.Kind.CLASS) { continue; // should never happen } ClassInfo declarativeAiServiceClassInfo = instance.target().asClass(); DotName chatLanguageModelSupplierClassDotName = null; AnnotationValue chatLanguageModelSupplierValue = instance.value("chatLanguageModelSupplier"); if (chatLanguageModelSupplierValue != null) { chatLanguageModelSupplierClassDotName = chatLanguageModelSupplierValue.asClass().name(); if (chatLanguageModelSupplierClassDotName.equals(Langchain4jDotNames.BEAN_CHAT_MODEL_SUPPLIER)) { // this is the case where the default was set, so we just ignore it chatLanguageModelSupplierClassDotName = null; } else { validateSupplierAndRegisterForReflection(chatLanguageModelSupplierClassDotName, index, reflectiveClassProducer); } } if (chatLanguageModelSupplierClassDotName == null) { needChatModelBean = true; } List<DotName> toolDotNames = Collections.emptyList(); AnnotationValue toolsInstance = instance.value("tools"); if (toolsInstance != null) { toolDotNames = Arrays.stream(toolsInstance.asClassArray()).map(Type::name) .collect(Collectors.toList()); } // the default value depends on whether tools exists or not - if they do, then we require a ChatMemoryProvider bean DotName chatMemoryProviderSupplierClassDotName = Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER; AnnotationValue chatMemoryProviderSupplierValue = instance.value("chatMemoryProviderSupplier"); if (chatMemoryProviderSupplierValue != null) { chatMemoryProviderSupplierClassDotName = chatMemoryProviderSupplierValue.asClass().name(); if (!chatMemoryProviderSupplierClassDotName .equals(Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER)) { validateSupplierAndRegisterForReflection(chatMemoryProviderSupplierClassDotName, index, reflectiveClassProducer); } } DotName retrieverSupplierClassDotName = Langchain4jDotNames.BEAN_IF_EXISTS_RETRIEVER_SUPPLIER; AnnotationValue retrieverSupplierValue = instance.value("retrieverSupplier"); if (retrieverSupplierValue != null) { retrieverSupplierClassDotName = retrieverSupplierValue.asClass().name(); if (!retrieverSupplierClassDotName.equals(Langchain4jDotNames.BEAN_RETRIEVER_SUPPLIER)) { validateSupplierAndRegisterForReflection(retrieverSupplierClassDotName, index, reflectiveClassProducer); } } DotName auditServiceSupplierClassName = Langchain4jDotNames.BEAN_IF_EXISTS_AUDIT_SERVICE_SUPPLIER; AnnotationValue auditServiceSupplierValue = instance.value("auditServiceSupplier"); if (auditServiceSupplierValue != null) { auditServiceSupplierClassName = auditServiceSupplierValue.asClass().name(); validateSupplierAndRegisterForReflection(auditServiceSupplierClassName, index, reflectiveClassProducer); } DotName moderationModelSupplierClassName = null; AnnotationValue moderationModelSupplierValue = instance.value("moderationModelSupplier"); if (moderationModelSupplierValue != null) { moderationModelSupplierClassName = moderationModelSupplierValue.asClass().name(); if (Langchain4jDotNames.NO_MODERATION_MODEL_SUPPLIER.equals(moderationModelSupplierClassName)) { moderationModelSupplierClassName = null; } else if (Langchain4jDotNames.BEAN_MODERATION_MODEL_SUPPLIER.equals(moderationModelSupplierClassName)) { needModerationModelBean = true; } else { validateSupplierAndRegisterForReflection(moderationModelSupplierClassName, index, reflectiveClassProducer); } } BuiltinScope declaredScope = BuiltinScope.from(declarativeAiServiceClassInfo); ScopeInfo cdiScope = declaredScope != null ? declaredScope.getInfo() : BuiltinScope.REQUEST.getInfo(); declarativeAiServiceProducer.produce( new DeclarativeAiServiceBuildItem( declarativeAiServiceClassInfo, chatLanguageModelSupplierClassDotName, toolDotNames, chatMemoryProviderSupplierClassDotName, retrieverSupplierClassDotName, auditServiceSupplierClassName, moderationModelSupplierClassName, cdiScope)); } if (needChatModelBean) { requestChatModelBeanProducer.produce(new RequestChatModelBeanBuildItem()); } if (needModerationModelBean) { requestModerationModelBeanProducer.produce(new RequestModerationModelBeanBuildItem()); } } private void validateSupplierAndRegisterForReflection(DotName supplierDotName, IndexView index, BuildProducer<ReflectiveClassBuildItem> producer) { ClassInfo classInfo = index.getClassByName(supplierDotName); if (classInfo == null) { log.warn("'" + supplierDotName.toString() + "' cannot be indexed"); // TODO: maybe this should be an error return; } if (!classInfo.hasNoArgsConstructor()) { throw new IllegalConfigurationException( "Class '" + supplierDotName.toString() + "' which must contain a no-args constructor."); } producer.produce(ReflectiveClassBuildItem.builder(supplierDotName.toString()).constructors(true).build()); } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void handleDeclarativeServices(AiServicesRecorder recorder, List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems, Optional<SelectedChatModelProviderBuildItem> selectedChatModelProvider, BuildProducer<SyntheticBeanBuildItem> syntheticBeanProducer, BuildProducer<UnremovableBeanBuildItem> unremoveableProducer) { boolean needsChatModelBean = false; boolean needsChatMemoryProviderBean = false; boolean needsRetrieverBean = false; boolean needsAuditServiceBean = false; boolean needsModerationModelBean = false; Set<DotName> allToolNames = new HashSet<>(); for (DeclarativeAiServiceBuildItem bi : declarativeAiServiceItems) { ClassInfo declarativeAiServiceClassInfo = bi.getServiceClassInfo(); String serviceClassName = declarativeAiServiceClassInfo.name().toString(); String chatLanguageModelSupplierClassName = (bi.getLanguageModelSupplierClassDotName() != null ? bi.getLanguageModelSupplierClassDotName().toString() : null); List<String> toolClassNames = bi.getToolDotNames().stream().map(DotName::toString).collect(Collectors.toList()); String chatMemoryProviderSupplierClassName = bi.getChatMemoryProviderSupplierClassDotName() != null ? bi.getChatMemoryProviderSupplierClassDotName().toString() : null; String retrieverSupplierClassName = bi.getRetrieverSupplierClassDotName() != null ? bi.getRetrieverSupplierClassDotName().toString() : null; String auditServiceClassSupplierName = bi.getAuditServiceClassSupplierDotName() != null ? bi.getAuditServiceClassSupplierDotName().toString() : null; String moderationModelSupplierClassName = (bi.getModerationModelSupplierDotName() != null ? bi.getModerationModelSupplierDotName().toString() : null); SyntheticBeanBuildItem.ExtendedBeanConfigurator configurator = SyntheticBeanBuildItem .configure(QuarkusAiServiceContext.class) .createWith(recorder.createDeclarativeAiService( new DeclarativeAiServiceCreateInfo(serviceClassName, chatLanguageModelSupplierClassName, toolClassNames, chatMemoryProviderSupplierClassName, retrieverSupplierClassName, auditServiceClassSupplierName, moderationModelSupplierClassName))) .setRuntimeInit() .addQualifier() .annotation(Langchain4jDotNames.QUARKUS_AI_SERVICE_CONTEXT_QUALIFIER).addValue("value", serviceClassName) .done() .scope(Dependent.class); if ((chatLanguageModelSupplierClassName == null) && selectedChatModelProvider.isPresent()) { // TODO: is second condition needed? configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.CHAT_MODEL)); needsChatModelBean = true; } if (!toolClassNames.isEmpty()) { for (String toolClassName : toolClassNames) { DotName dotName = DotName.createSimple(toolClassName); configurator.addInjectionPoint(ClassType.create(dotName)); allToolNames.add(dotName); } } if (Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER.toString().equals(chatMemoryProviderSupplierClassName)) { configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.CHAT_MEMORY_PROVIDER)); needsChatMemoryProviderBean = true; } if (Langchain4jDotNames.BEAN_RETRIEVER_SUPPLIER.toString().equals(retrieverSupplierClassName)) { configurator.addInjectionPoint(ParameterizedType.create(Langchain4jDotNames.RETRIEVER, new Type[] { ClassType.create(Langchain4jDotNames.TEXT_SEGMENT) }, null)); needsRetrieverBean = true; } else if (Langchain4jDotNames.BEAN_IF_EXISTS_RETRIEVER_SUPPLIER.toString() .equals(retrieverSupplierClassName)) { configurator.addInjectionPoint(ParameterizedType.create(CDI_INSTANCE, new Type[] { ParameterizedType.create(Langchain4jDotNames.RETRIEVER, new Type[] { ClassType.create(Langchain4jDotNames.TEXT_SEGMENT) }, null) }, null)); needsRetrieverBean = true; } if (Langchain4jDotNames.BEAN_IF_EXISTS_AUDIT_SERVICE_SUPPLIER.toString().equals(auditServiceClassSupplierName)) { configurator.addInjectionPoint(ParameterizedType.create(CDI_INSTANCE, new Type[] { ClassType.create(Langchain4jDotNames.AUDIT_SERVICE) }, null)); needsAuditServiceBean = true; } if (Langchain4jDotNames.BEAN_MODERATION_MODEL_SUPPLIER.toString().equals(moderationModelSupplierClassName)) { configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.MODERATION_MODEL)); needsModerationModelBean = true; } syntheticBeanProducer.produce(configurator.done()); } if (needsChatModelBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.CHAT_MODEL)); } if (needsChatMemoryProviderBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.CHAT_MEMORY_PROVIDER)); } if (needsRetrieverBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.RETRIEVER)); } if (needsAuditServiceBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.AUDIT_SERVICE)); } if (needsModerationModelBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.MODERATION_MODEL)); } if (!allToolNames.isEmpty()) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(allToolNames)); } } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void handleAiServices(AiServicesRecorder recorder, CombinedIndexBuildItem indexBuildItem, List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems, BuildProducer<GeneratedClassBuildItem> generatedClassProducer, BuildProducer<GeneratedBeanBuildItem> generatedBeanProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer, BuildProducer<AiServicesMethodBuildItem> aiServicesMethodProducer, BuildProducer<AdditionalBeanBuildItem> additionalBeanProducer, Optional<MetricsCapabilityBuildItem> metricsCapability, Capabilities capabilities) { IndexView index = indexBuildItem.getIndex(); List<AiServicesUseAnalyzer.Result.Entry> aiServicesAnalysisResults = new ArrayList<>(); for (ClassInfo classInfo : index.getKnownUsers(Langchain4jDotNames.AI_SERVICES)) { String className = classInfo.name().toString(); if (className.startsWith("io.quarkiverse.langchain4j") || className.startsWith("dev.langchain4j")) { // TODO: this can be made smarter if needed continue; } try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( className.replace('.', '/') + ".class")) { if (is == null) { return; } var cn = new ClassNode(Gizmo.ASM_API_VERSION); var cr = new ClassReader(is); cr.accept(cn, 0); for (MethodNode method : cn.methods) { aiServicesAnalysisResults.addAll(AiServicesUseAnalyzer.analyze(cn, method).entries); } } catch (IOException e) { throw new UncheckedIOException("Reading bytecode of class '" + className + "' failed", e); } catch (AnalyzerException e) { log.debug("Unable to analyze bytecode of class '" + className + "'", e); } } Map<String, Boolean> nameToUsed = aiServicesAnalysisResults.stream() .collect(Collectors.toMap(e -> e.createdClassName, e -> e.chatMemoryProviderUsed, (u1, u2) -> u1 || u2)); for (var entry : nameToUsed.entrySet()) { String className = entry.getKey(); ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { continue; } if (!classInfo.annotations(Langchain4jDotNames.MEMORY_ID).isEmpty() && !entry.getValue()) { log.warn("Class '" + className + "' is used in AiServices and while it leverages @MemoryId, a ChatMemoryProvider has not been configured. This will likely result in an exception being thrown when the service is used."); } } Set<String> detectedForCreate = new HashSet<>(nameToUsed.keySet()); addCreatedAware(index, detectedForCreate); addIfacesWithMessageAnns(index, detectedForCreate); Set<String> registeredAiServiceClassNames = declarativeAiServiceItems.stream() .map(bi -> bi.getServiceClassInfo().name().toString()).collect( Collectors.toUnmodifiableSet()); detectedForCreate.addAll(registeredAiServiceClassNames); Set<ClassInfo> ifacesForCreate = new HashSet<>(); for (String className : detectedForCreate) { ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { log.warn("'" + className + "' used for creating an AiService was not found in the Quarkus index. Attempting to create " + "an AiService using this class will fail"); continue; } if (!classInfo.isInterface()) { log.warn("'" + className + "' used for creating an AiService is not an interface. Attempting to create an AiService " + "using this class will fail"); } ifacesForCreate.add(classInfo); } var addMicrometerMetrics = metricsCapability.isPresent() && metricsCapability.get().metricsSupported(MetricsFactory.MICROMETER); if (addMicrometerMetrics) {
additionalBeanProducer.produce(AdditionalBeanBuildItem.builder().addBeanClass(MetricsTimedWrapper.class).build());
9
2023-11-13 09:10:27+00:00
16k
qiusunshine/xiu
clinglibrary/src/main/java/org/fourthline/cling/transport/RouterImpl.java
[ { "identifier": "UpnpServiceConfiguration", "path": "clinglibrary/src/main/java/org/fourthline/cling/UpnpServiceConfiguration.java", "snippet": "public interface UpnpServiceConfiguration {\n\n /**\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.NetworkAddressFactory} i...
import org.fourthline.cling.UpnpServiceConfiguration; import org.fourthline.cling.model.NetworkAddress; import org.fourthline.cling.model.message.IncomingDatagramMessage; import org.fourthline.cling.model.message.OutgoingDatagramMessage; import org.fourthline.cling.model.message.StreamRequestMessage; import org.fourthline.cling.model.message.StreamResponseMessage; import org.fourthline.cling.protocol.ProtocolCreationException; import org.fourthline.cling.protocol.ProtocolFactory; import org.fourthline.cling.protocol.ReceivingAsync; import org.fourthline.cling.transport.spi.DatagramIO; import org.fourthline.cling.transport.spi.InitializationException; import org.fourthline.cling.transport.spi.MulticastReceiver; import org.fourthline.cling.transport.spi.NetworkAddressFactory; import org.fourthline.cling.transport.spi.NoNetworkException; import org.fourthline.cling.transport.spi.StreamClient; import org.fourthline.cling.transport.spi.StreamServer; import org.fourthline.cling.transport.spi.UpnpStream; import org.seamless.util.Exceptions; import java.net.BindException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.enterprise.inject.Default; import javax.inject.Inject;
11,156
@Override public void handleStartFailure(InitializationException ex) throws InitializationException { if (ex instanceof NoNetworkException) { log.info("Unable to initialize network router, no network found."); } else { log.severe("Unable to initialize network router: " + ex); log.severe("Cause: " + Exceptions.unwrap(ex)); } } public List<NetworkAddress> getActiveStreamServers(InetAddress preferredAddress) throws RouterException { lock(readLock); try { if (enabled && streamServers.size() > 0) { List<NetworkAddress> streamServerAddresses = new ArrayList<>(); StreamServer preferredServer; if (preferredAddress != null && (preferredServer = streamServers.get(preferredAddress)) != null) { streamServerAddresses.add( new NetworkAddress( preferredAddress, preferredServer.getPort(), networkAddressFactory.getHardwareAddress(preferredAddress) ) ); return streamServerAddresses; } for (Map.Entry<InetAddress, StreamServer> entry : streamServers.entrySet()) { byte[] hardwareAddress = networkAddressFactory.getHardwareAddress(entry.getKey()); streamServerAddresses.add( new NetworkAddress(entry.getKey(), entry.getValue().getPort(), hardwareAddress) ); } return streamServerAddresses; } else { return Collections.EMPTY_LIST; } } finally { unlock(readLock); } } /** * Obtains the asynchronous protocol {@code Executor} and runs the protocol created * by the {@link org.fourthline.cling.protocol.ProtocolFactory} for the given message. * <p> * If the factory doesn't create a protocol, the message is dropped immediately without * creating another thread or consuming further resources. This means we can filter the * datagrams in the protocol factory and e.g. completely disable discovery or only * allow notification message from some known services we'd like to work with. * </p> * * @param msg The received datagram message. */ public void received(IncomingDatagramMessage msg) { if (!enabled) { log.fine("Router disabled, ignoring incoming message: " + msg); return; } try { ReceivingAsync protocol = getProtocolFactory().createReceivingAsync(msg); if (protocol == null) { if (log.isLoggable(Level.FINEST)) log.finest("No protocol, ignoring received message: " + msg); return; } if (log.isLoggable(Level.FINE)) log.fine("Received asynchronous message: " + msg); getConfiguration().getAsyncProtocolExecutor().execute(protocol); } catch (ProtocolCreationException ex) { log.warning("Handling received datagram failed - " + Exceptions.unwrap(ex).toString()); } } /** * Obtains the synchronous protocol {@code Executor} and runs the * {@link org.fourthline.cling.transport.spi.UpnpStream} directly. * * @param stream The received {@link org.fourthline.cling.transport.spi.UpnpStream}. */ public void received(UpnpStream stream) { if (!enabled) { log.fine("Router disabled, ignoring incoming: " + stream); return; } log.fine("Received synchronous stream: " + stream); getConfiguration().getSyncProtocolExecutorService().execute(stream); } /** * Sends the UDP datagram on all bound {@link org.fourthline.cling.transport.spi.DatagramIO}s. * * @param msg The UDP datagram message to send. */ public void send(OutgoingDatagramMessage msg) throws RouterException { lock(readLock); try { if (enabled) { for (DatagramIO datagramIO : datagramIOs.values()) { datagramIO.send(msg); } } else { log.fine("Router disabled, not sending datagram: " + msg); } } finally { unlock(readLock); } } /** * Sends the TCP stream request with the {@link org.fourthline.cling.transport.spi.StreamClient}. * * @param msg The TCP (HTTP) stream message to send. * @return The return value of the {@link org.fourthline.cling.transport.spi.StreamClient#sendRequest(StreamRequestMessage)} * method or <code>null</code> if no <code>StreamClient</code> is available. */
/* * Copyright (C) 2013 4th Line GmbH, Switzerland * * The contents of this file are subject to the terms of either the GNU * Lesser General Public License Version 2 or later ("LGPL") or the * Common Development and Distribution License Version 1 or later * ("CDDL") (collectively, the "License"). You may not use this file * except in compliance with the License. See LICENSE.txt for more * information. * * 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. */ package org.fourthline.cling.transport; /** * Default implementation of network message router. * <p> * Initializes and starts listening for data on the network when enabled. * </p> * * @author Christian Bauer */ @ApplicationScoped public class RouterImpl implements Router { private static Logger log = Logger.getLogger(Router.class.getName()); protected UpnpServiceConfiguration configuration; protected ProtocolFactory protocolFactory; protected volatile boolean enabled; protected ReentrantReadWriteLock routerLock = new ReentrantReadWriteLock(true); protected Lock readLock = routerLock.readLock(); protected Lock writeLock = routerLock.writeLock(); // These are created/destroyed when the router is enabled/disabled protected NetworkAddressFactory networkAddressFactory; protected StreamClient streamClient; protected final Map<NetworkInterface, MulticastReceiver> multicastReceivers = new HashMap<>(); protected final Map<InetAddress, DatagramIO> datagramIOs = new HashMap<>(); protected final Map<InetAddress, StreamServer> streamServers = new HashMap<>(); protected RouterImpl() { } /** * @param configuration The configuration used by this router. * @param protocolFactory The protocol factory used by this router. */ @Inject public RouterImpl(UpnpServiceConfiguration configuration, ProtocolFactory protocolFactory) { log.info("Creating Router: " + getClass().getName()); this.configuration = configuration; this.protocolFactory = protocolFactory; } public boolean enable(@Observes @Default EnableRouter event) throws RouterException { return enable(); } public boolean disable(@Observes @Default DisableRouter event) throws RouterException { return disable(); } public UpnpServiceConfiguration getConfiguration() { return configuration; } public ProtocolFactory getProtocolFactory() { return protocolFactory; } /** * Initializes listening services: First an instance of {@link org.fourthline.cling.transport.spi.MulticastReceiver} * is bound to each network interface. Then an instance of {@link org.fourthline.cling.transport.spi.DatagramIO} and * {@link org.fourthline.cling.transport.spi.StreamServer} is bound to each bind address returned by the network * address factory, respectively. There is only one instance of * {@link org.fourthline.cling.transport.spi.StreamClient} created and managed by this router. */ @Override public boolean enable() throws RouterException { lock(writeLock); try { if (!enabled) { try { log.fine("Starting networking services..."); networkAddressFactory = getConfiguration().createNetworkAddressFactory(); startInterfaceBasedTransports(networkAddressFactory.getNetworkInterfaces()); startAddressBasedTransports(networkAddressFactory.getBindAddresses()); // The transports possibly removed some unusable network interfaces/addresses if (!networkAddressFactory.hasUsableNetwork()) { throw new NoNetworkException( "No usable network interface and/or addresses available, check the log for errors." ); } // Start the HTTP client last, we don't even have to try if there is no network streamClient = getConfiguration().createStreamClient(); enabled = true; return true; } catch (InitializationException ex) { handleStartFailure(ex); } } return false; } finally { unlock(writeLock); } } @Override public boolean disable() throws RouterException { lock(writeLock); try { if (enabled) { log.fine("Disabling network services..."); if (streamClient != null) { log.fine("Stopping stream client connection management/pool"); streamClient.stop(); streamClient = null; } for (Map.Entry<InetAddress, StreamServer> entry : streamServers.entrySet()) { log.fine("Stopping stream server on address: " + entry.getKey()); entry.getValue().stop(); } streamServers.clear(); for (Map.Entry<NetworkInterface, MulticastReceiver> entry : multicastReceivers.entrySet()) { log.fine("Stopping multicast receiver on interface: " + entry.getKey().getDisplayName()); entry.getValue().stop(); } multicastReceivers.clear(); for (Map.Entry<InetAddress, DatagramIO> entry : datagramIOs.entrySet()) { log.fine("Stopping datagram I/O on address: " + entry.getKey()); entry.getValue().stop(); } datagramIOs.clear(); networkAddressFactory = null; enabled = false; return true; } return false; } finally { unlock(writeLock); } } @Override public void shutdown() throws RouterException { disable(); } @Override public boolean isEnabled() { return enabled; } @Override public void handleStartFailure(InitializationException ex) throws InitializationException { if (ex instanceof NoNetworkException) { log.info("Unable to initialize network router, no network found."); } else { log.severe("Unable to initialize network router: " + ex); log.severe("Cause: " + Exceptions.unwrap(ex)); } } public List<NetworkAddress> getActiveStreamServers(InetAddress preferredAddress) throws RouterException { lock(readLock); try { if (enabled && streamServers.size() > 0) { List<NetworkAddress> streamServerAddresses = new ArrayList<>(); StreamServer preferredServer; if (preferredAddress != null && (preferredServer = streamServers.get(preferredAddress)) != null) { streamServerAddresses.add( new NetworkAddress( preferredAddress, preferredServer.getPort(), networkAddressFactory.getHardwareAddress(preferredAddress) ) ); return streamServerAddresses; } for (Map.Entry<InetAddress, StreamServer> entry : streamServers.entrySet()) { byte[] hardwareAddress = networkAddressFactory.getHardwareAddress(entry.getKey()); streamServerAddresses.add( new NetworkAddress(entry.getKey(), entry.getValue().getPort(), hardwareAddress) ); } return streamServerAddresses; } else { return Collections.EMPTY_LIST; } } finally { unlock(readLock); } } /** * Obtains the asynchronous protocol {@code Executor} and runs the protocol created * by the {@link org.fourthline.cling.protocol.ProtocolFactory} for the given message. * <p> * If the factory doesn't create a protocol, the message is dropped immediately without * creating another thread or consuming further resources. This means we can filter the * datagrams in the protocol factory and e.g. completely disable discovery or only * allow notification message from some known services we'd like to work with. * </p> * * @param msg The received datagram message. */ public void received(IncomingDatagramMessage msg) { if (!enabled) { log.fine("Router disabled, ignoring incoming message: " + msg); return; } try { ReceivingAsync protocol = getProtocolFactory().createReceivingAsync(msg); if (protocol == null) { if (log.isLoggable(Level.FINEST)) log.finest("No protocol, ignoring received message: " + msg); return; } if (log.isLoggable(Level.FINE)) log.fine("Received asynchronous message: " + msg); getConfiguration().getAsyncProtocolExecutor().execute(protocol); } catch (ProtocolCreationException ex) { log.warning("Handling received datagram failed - " + Exceptions.unwrap(ex).toString()); } } /** * Obtains the synchronous protocol {@code Executor} and runs the * {@link org.fourthline.cling.transport.spi.UpnpStream} directly. * * @param stream The received {@link org.fourthline.cling.transport.spi.UpnpStream}. */ public void received(UpnpStream stream) { if (!enabled) { log.fine("Router disabled, ignoring incoming: " + stream); return; } log.fine("Received synchronous stream: " + stream); getConfiguration().getSyncProtocolExecutorService().execute(stream); } /** * Sends the UDP datagram on all bound {@link org.fourthline.cling.transport.spi.DatagramIO}s. * * @param msg The UDP datagram message to send. */ public void send(OutgoingDatagramMessage msg) throws RouterException { lock(readLock); try { if (enabled) { for (DatagramIO datagramIO : datagramIOs.values()) { datagramIO.send(msg); } } else { log.fine("Router disabled, not sending datagram: " + msg); } } finally { unlock(readLock); } } /** * Sends the TCP stream request with the {@link org.fourthline.cling.transport.spi.StreamClient}. * * @param msg The TCP (HTTP) stream message to send. * @return The return value of the {@link org.fourthline.cling.transport.spi.StreamClient#sendRequest(StreamRequestMessage)} * method or <code>null</code> if no <code>StreamClient</code> is available. */
public StreamResponseMessage send(StreamRequestMessage msg) throws RouterException {
4
2023-11-10 14:28:40+00:00
16k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/commandexecutors/DeityCommand.java
[ { "identifier": "Deity", "path": "src/main/java/me/xidentified/devotions/Deity.java", "snippet": "public class Deity {\n private final Devotions plugin;\n // Getter methods below\n @Getter public final String name;\n @Getter private final String lore;\n @Getter private final String alignm...
import de.cubbossa.tinytranslations.GlobalMessages; import me.xidentified.devotions.Deity; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.managers.FavorManager; import me.xidentified.devotions.util.Messages; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.UUID;
12,975
package me.xidentified.devotions.commandexecutors; public class DeityCommand implements CommandExecutor, TabCompleter { private final Devotions plugin; public DeityCommand(Devotions plugin) { this.plugin = plugin; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length < 1) { plugin.sendMessage(player, Messages.DEITY_CMD_USAGE); return true; } String subCommand = args[0].toLowerCase(); switch (subCommand) { case "list" -> { return handleList(player); } case "select" -> { return handleSelect(player, args); } case "info" -> { return handleInfo(player, args); } default -> { plugin.sendMessage(player,Messages.DEITY_CMD_USAGE); return true; } } } private boolean handleSelect(Player player, String[] args) { if (args.length < 2) { plugin.sendMessage(player, Messages.DEITY_CMD_SPECIFY_DEITY); return true; } String deityName = args[1]; Deity selectedDeity = plugin.getDevotionManager().getDeityByName(deityName); if (selectedDeity == null) { plugin.sendMessage(player, Messages.DEITY_NOT_FOUND); return false; } // Fetch or create the player's FavorManager UUID playerUniqueId = player.getUniqueId();
package me.xidentified.devotions.commandexecutors; public class DeityCommand implements CommandExecutor, TabCompleter { private final Devotions plugin; public DeityCommand(Devotions plugin) { this.plugin = plugin; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length < 1) { plugin.sendMessage(player, Messages.DEITY_CMD_USAGE); return true; } String subCommand = args[0].toLowerCase(); switch (subCommand) { case "list" -> { return handleList(player); } case "select" -> { return handleSelect(player, args); } case "info" -> { return handleInfo(player, args); } default -> { plugin.sendMessage(player,Messages.DEITY_CMD_USAGE); return true; } } } private boolean handleSelect(Player player, String[] args) { if (args.length < 2) { plugin.sendMessage(player, Messages.DEITY_CMD_SPECIFY_DEITY); return true; } String deityName = args[1]; Deity selectedDeity = plugin.getDevotionManager().getDeityByName(deityName); if (selectedDeity == null) { plugin.sendMessage(player, Messages.DEITY_NOT_FOUND); return false; } // Fetch or create the player's FavorManager UUID playerUniqueId = player.getUniqueId();
FavorManager favorManager = plugin.getDevotionManager().getPlayerDevotion(playerUniqueId);
2
2023-11-10 07:03:24+00:00
16k
SplitfireUptown/datalinkx
datalinkx-server/src/main/java/com/datalinkx/dataserver/service/impl/JobService.java
[ { "identifier": "JOB_STATUS_STOP", "path": "datalinkx-common/src/main/java/com/datalinkx/common/constants/MetaConstants.java", "snippet": "public static final int JOB_STATUS_STOP = 5;" }, { "identifier": "JOB_STATUS_SYNC", "path": "datalinkx-common/src/main/java/com/datalinkx/common/constant...
import static com.datalinkx.common.constants.MetaConstants.JobStatus.JOB_STATUS_STOP; import static com.datalinkx.common.constants.MetaConstants.JobStatus.JOB_STATUS_SYNC; import static com.datalinkx.common.utils.IdUtils.genKey; import static com.datalinkx.common.utils.JsonUtils.toJson; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Resource; import com.datalinkx.common.constants.MessageHubConstants; import com.datalinkx.common.constants.MetaConstants; import com.datalinkx.driver.dsdriver.DsDriverFactory; import com.datalinkx.driver.dsdriver.IDsReader; import com.datalinkx.driver.dsdriver.base.model.TableField; import com.datalinkx.driver.model.DataTransJobDetail; import com.datalinkx.common.result.StatusCode; import com.datalinkx.common.utils.JsonUtils; import com.datalinkx.dataserver.bean.domain.DsBean; import com.datalinkx.dataserver.bean.domain.DsTbBean; import com.datalinkx.dataserver.bean.domain.JobBean; import com.datalinkx.dataserver.bean.domain.JobLogBean; import com.datalinkx.dataserver.bean.dto.JobDto; import com.datalinkx.dataserver.bean.vo.JobVo; import com.datalinkx.dataserver.bean.vo.PageVo; import com.datalinkx.dataserver.client.xxljob.JobClientApi; import com.datalinkx.dataserver.client.xxljob.request.DataTransJobParam; import com.datalinkx.dataserver.controller.form.JobForm; import com.datalinkx.dataserver.controller.form.JobStateForm; import com.datalinkx.common.exception.DatalinkXServerException; import com.datalinkx.dataserver.repository.DsRepository; import com.datalinkx.dataserver.repository.DsTbRepository; import com.datalinkx.dataserver.repository.JobLogRepository; import com.datalinkx.dataserver.repository.JobRepository; import com.datalinkx.dataserver.service.DtsJobService; import com.datalinkx.messagehub.bean.form.ProducerAdapterForm; import com.datalinkx.messagehub.service.MessageHubService; import lombok.SneakyThrows; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ObjectUtils;
13,727
DsBean fromDs = dsRepository .findByDsId(jobBean.getReaderDsId()) .orElseThrow( () -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, "from ds not exist") ); List<DataTransJobDetail.Column> fromCols = jobConf.stream() .map(x -> DataTransJobDetail.Column.builder() .name(x.getSourceField()) .build()) .collect(Collectors.toList()); DsTbBean tbBean = dsTbRepository.findByTbId(jobBean.getFromTbId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.TB_NOT_EXISTS, "xtable not exist")); // 处理增量条件 IDsReader dsReader = DsDriverFactory.getDsReader(dsService.getConnectId(fromDs)); Map<String, String> typeMappings = dsReader.getFields(fromDs.getDatabase(), fromDs.getSchema(), fromDs.getName()) .stream().collect(Collectors.toMap(TableField::getName, TableField::getRawType)); JobForm.SyncModeForm syncModeForm = JsonUtils.toObject(jobBean.getSyncMode(), JobForm.SyncModeForm.class); DataTransJobDetail.Sync.SyncCondition syncCond = this.getSyncCond(syncModeForm, fromCols, typeMappings); DataTransJobDetail.Sync sync = DataTransJobDetail.Sync .builder() .type(syncModeForm.getMode()) .syncCondition(syncCond) .build(); return DataTransJobDetail.Reader .builder() .tableId(tbBean.getTbId()) .connectId(dsService.getConnectId(fromDs)) .type(dsService.genTypeToDbNameMap().get(fromDs.getType())) .schema(fromDs.getDatabase()) .sync(sync) .maxValue(syncModeForm.getIncreateValue()) .tableName(tbBean.getName()) .realName(tbBean.getName()) .columns(fromCols) .build(); } private DataTransJobDetail.Sync.SyncCondition getSyncCond(JobForm.SyncModeForm exportMode, List<DataTransJobDetail.Column> syncFields, Map<String, String> typeMappings) { DataTransJobDetail.Sync.SyncCondition syncCon = null; if ("increment".equalsIgnoreCase(exportMode.getMode())) { for (DataTransJobDetail.Column field : syncFields) { if (!ObjectUtils.nullSafeEquals(field.getName(), exportMode.getIncreateField())) { continue; } String synFieldType = typeMappings.getOrDefault(field.getName(), "string"); syncCon = DataTransJobDetail.Sync.SyncCondition.builder() .field(field.getName()) .fieldType(synFieldType) .start(DataTransJobDetail.Sync.SyncCondition.Conditon .builder() .enable(1) .operator(">") .value(exportMode.getIncreateValue()) .build()) .end(DataTransJobDetail.Sync.SyncCondition.Conditon .builder() .enable(0) .build()) .build(); } } return syncCon; } @SneakyThrows private DataTransJobDetail.Writer getWriter(JobBean jobBean, List<JobForm.FieldMappingForm> jobConf) { DsBean toDs = dsRepository .findByDsId(jobBean.getReaderDsId()) .orElseThrow( () -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, "to ds not exist") ); DsTbBean dsTbBean = dsTbRepository.findByTbId(jobBean.getToTbId()) .orElseThrow(() -> new DatalinkXServerException(StatusCode.XTB_NOT_EXISTS, "xtb not found")); IDsReader dsReader = DsDriverFactory.getDsReader(dsService.getConnectId(toDs)); Map<String, String> typeMappings = dsReader.getFields(toDs.getDatabase(), toDs.getSchema(), dsTbBean.getName()) .stream().collect(Collectors.toMap(TableField::getName, TableField::getRawType)); List<DataTransJobDetail.Column> toCols = jobConf .stream() .map(x -> DataTransJobDetail .Column .builder() .name(x.getTargetField()) .type(typeMappings.getOrDefault(x.getTargetField(), x.getMappingValue())) .build() ) .collect(Collectors.toList()); DsTbBean tbBean = dsTbRepository.findByTbId(jobBean.getToTbId()) .orElseThrow(() -> new DatalinkXServerException(StatusCode.TB_NOT_EXISTS, "xtable not exist")); return DataTransJobDetail.Writer.builder() .schema(toDs.getDatabase()).connectId(dsService.getConnectId(toDs)) .tableId(jobBean.getToTbId()).type(dsService.genTypeToDbNameMap().get(toDs.getType())) .tableName(tbBean.getName()).columns(toCols).build(); } @Transactional(rollbackFor = Exception.class) @Override public String updateJobStatus(JobStateForm jobStateForm) { JobBean jobBean = jobRepository.findByJobId(jobStateForm.getJobId()) .orElseThrow(() -> new DatalinkXServerException(StatusCode.JOB_NOT_EXISTS, "job not exist")); int status = jobStateForm.getJobStatus();
package com.datalinkx.dataserver.service.impl; @Component @Service @Log4j2 public class JobService implements DtsJobService { private static final int FAILED = 3; private static final int SUCCESS = 2; @Autowired private JobRepository jobRepository; @Autowired DsService dsService; @Autowired DsRepository dsRepository; @Autowired DsTbRepository dsTbRepository; @Autowired JobLogRepository jobLogRepository; @Autowired JobClientApi jobClientApi; @Resource(name = "messageHubServiceImpl") MessageHubService messageHubService; @Transactional(rollbackFor = Exception.class) public String jobCreate(JobForm.JobCreateForm form) { this.validJobForm(form); String jobId = genKey("job"); JobBean jobBean = new JobBean(); jobBean.setJobId(jobId); jobBean.setReaderDsId(form.getFromDsId()); jobBean.setWriterDsId(form.getToDsId()); jobBean.setConfig(toJson(form.getFieldMappings())); jobBean.setFromTbId(getXtbId(form.getFromTbName(), form.getFromDsId())); jobBean.setToTbId(getXtbId(form.getToTbName(), form.getFromDsId())); jobBean.setStatus(MetaConstants.JobStatus.JOB_TABLE_CREATE); jobBean.setCrontab(form.getSchedulerConf()); jobBean.setSyncMode(JsonUtils.toJson(form.getSyncMode())); // 创建 xxljob String xxlJobId = jobClientApi.add(jobId, form.getSchedulerConf(), DataTransJobParam.builder().jobId(jobId).build()); jobBean.setXxlId(xxlJobId); jobRepository.save(jobBean); return jobId; } public String jobModify(JobForm.JobModifyForm form) { this.validJobForm(form); JobBean jobBean = jobRepository.findByJobId(form.getJobId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.JOB_NOT_EXISTS, "job not exist")); jobBean.setReaderDsId(form.getFromDsId()); jobBean.setWriterDsId(form.getToDsId()); jobBean.setConfig(toJson(form.getFieldMappings())); jobBean.setFromTbId(getXtbId(form.getFromTbName(), form.getFromDsId())); jobBean.setToTbId(getXtbId(form.getToTbName(), form.getFromDsId())); jobBean.setCrontab(form.getSchedulerConf()); jobBean.setSyncMode(JsonUtils.toJson(form.getSyncMode())); jobRepository.save(jobBean); return form.getJobId(); } private void validJobForm(JobForm.JobCreateForm form) { DsBean fromDsBean = dsRepository.findByDsId(form.getFromDsId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, "来源数据源不存在")); DsBean toBean = dsRepository.findByDsId(form.getToDsId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, "目标数据源不存在")); if (MetaConstants.JobSyncMode.INCREMENT_MODE.equals(form.getSyncMode().getMode()) && ObjectUtils.isEmpty(form.getSyncMode().getIncreateField())) { throw new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, "增量模式必须指定增量字段"); } if (MetaConstants.JobSyncMode.INCREMENT_MODE.equals(form.getSyncMode().getMode())) { try { IDsReader dsReader = DsDriverFactory.getDsReader(dsService.getConnectId(fromDsBean)); Boolean isIncremental = dsReader.judgeIncrementalField(fromDsBean.getDatabase(), fromDsBean.getSchema(), form.getFromTbName(), form.getSyncMode().getIncreateField()); if (!isIncremental) { throw new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, "增量字段必须是日期或数值类型"); } } catch (Exception e) { throw new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, e.getMessage()); } } if (ObjectUtils.isEmpty(form.getSchedulerConf())) { throw new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, "流转任务需要配置crontab表达式"); } } private String getXtbId(String tbName, String dsId) { DsTbBean xtbBean = dsTbRepository.findTopByNameAndDsId(tbName, dsId); if (!ObjectUtils.isEmpty(xtbBean)) { return xtbBean.getTbId(); } return dsService.xtbCreate(tbName, dsId); } @Override public DataTransJobDetail getJobExecInfo(String jobId, List<String> tableIds, Boolean tbDetail) { JobBean jobBean = jobRepository.findByJobId(jobId).orElseThrow(() -> new DatalinkXServerException(StatusCode.JOB_NOT_EXISTS, "job not exist")); List<JobForm.FieldMappingForm> fieldMappingForms = JsonUtils.toList(jobBean.getConfig(), JobForm.FieldMappingForm.class); DataTransJobDetail.SyncUnit syncUnit = DataTransJobDetail.SyncUnit .builder() .taskId(jobId) .reader(this.getReader(jobBean, fieldMappingForms)) .writer(this.getWriter(jobBean, fieldMappingForms)) .build(); return DataTransJobDetail.builder().jobId(jobId).syncUnits(Collections.singletonList(syncUnit)).build(); } @SneakyThrows private DataTransJobDetail.Reader getReader(JobBean jobBean, List<JobForm.FieldMappingForm> jobConf) { DsBean fromDs = dsRepository .findByDsId(jobBean.getReaderDsId()) .orElseThrow( () -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, "from ds not exist") ); List<DataTransJobDetail.Column> fromCols = jobConf.stream() .map(x -> DataTransJobDetail.Column.builder() .name(x.getSourceField()) .build()) .collect(Collectors.toList()); DsTbBean tbBean = dsTbRepository.findByTbId(jobBean.getFromTbId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.TB_NOT_EXISTS, "xtable not exist")); // 处理增量条件 IDsReader dsReader = DsDriverFactory.getDsReader(dsService.getConnectId(fromDs)); Map<String, String> typeMappings = dsReader.getFields(fromDs.getDatabase(), fromDs.getSchema(), fromDs.getName()) .stream().collect(Collectors.toMap(TableField::getName, TableField::getRawType)); JobForm.SyncModeForm syncModeForm = JsonUtils.toObject(jobBean.getSyncMode(), JobForm.SyncModeForm.class); DataTransJobDetail.Sync.SyncCondition syncCond = this.getSyncCond(syncModeForm, fromCols, typeMappings); DataTransJobDetail.Sync sync = DataTransJobDetail.Sync .builder() .type(syncModeForm.getMode()) .syncCondition(syncCond) .build(); return DataTransJobDetail.Reader .builder() .tableId(tbBean.getTbId()) .connectId(dsService.getConnectId(fromDs)) .type(dsService.genTypeToDbNameMap().get(fromDs.getType())) .schema(fromDs.getDatabase()) .sync(sync) .maxValue(syncModeForm.getIncreateValue()) .tableName(tbBean.getName()) .realName(tbBean.getName()) .columns(fromCols) .build(); } private DataTransJobDetail.Sync.SyncCondition getSyncCond(JobForm.SyncModeForm exportMode, List<DataTransJobDetail.Column> syncFields, Map<String, String> typeMappings) { DataTransJobDetail.Sync.SyncCondition syncCon = null; if ("increment".equalsIgnoreCase(exportMode.getMode())) { for (DataTransJobDetail.Column field : syncFields) { if (!ObjectUtils.nullSafeEquals(field.getName(), exportMode.getIncreateField())) { continue; } String synFieldType = typeMappings.getOrDefault(field.getName(), "string"); syncCon = DataTransJobDetail.Sync.SyncCondition.builder() .field(field.getName()) .fieldType(synFieldType) .start(DataTransJobDetail.Sync.SyncCondition.Conditon .builder() .enable(1) .operator(">") .value(exportMode.getIncreateValue()) .build()) .end(DataTransJobDetail.Sync.SyncCondition.Conditon .builder() .enable(0) .build()) .build(); } } return syncCon; } @SneakyThrows private DataTransJobDetail.Writer getWriter(JobBean jobBean, List<JobForm.FieldMappingForm> jobConf) { DsBean toDs = dsRepository .findByDsId(jobBean.getReaderDsId()) .orElseThrow( () -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, "to ds not exist") ); DsTbBean dsTbBean = dsTbRepository.findByTbId(jobBean.getToTbId()) .orElseThrow(() -> new DatalinkXServerException(StatusCode.XTB_NOT_EXISTS, "xtb not found")); IDsReader dsReader = DsDriverFactory.getDsReader(dsService.getConnectId(toDs)); Map<String, String> typeMappings = dsReader.getFields(toDs.getDatabase(), toDs.getSchema(), dsTbBean.getName()) .stream().collect(Collectors.toMap(TableField::getName, TableField::getRawType)); List<DataTransJobDetail.Column> toCols = jobConf .stream() .map(x -> DataTransJobDetail .Column .builder() .name(x.getTargetField()) .type(typeMappings.getOrDefault(x.getTargetField(), x.getMappingValue())) .build() ) .collect(Collectors.toList()); DsTbBean tbBean = dsTbRepository.findByTbId(jobBean.getToTbId()) .orElseThrow(() -> new DatalinkXServerException(StatusCode.TB_NOT_EXISTS, "xtable not exist")); return DataTransJobDetail.Writer.builder() .schema(toDs.getDatabase()).connectId(dsService.getConnectId(toDs)) .tableId(jobBean.getToTbId()).type(dsService.genTypeToDbNameMap().get(toDs.getType())) .tableName(tbBean.getName()).columns(toCols).build(); } @Transactional(rollbackFor = Exception.class) @Override public String updateJobStatus(JobStateForm jobStateForm) { JobBean jobBean = jobRepository.findByJobId(jobStateForm.getJobId()) .orElseThrow(() -> new DatalinkXServerException(StatusCode.JOB_NOT_EXISTS, "job not exist")); int status = jobStateForm.getJobStatus();
ProducerAdapterForm producerAdapterForm = new ProducerAdapterForm();
29
2023-11-16 02:22:52+00:00
16k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/utils/EnviroUtils.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.awt.Color; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.util.ArrayList; import cpw.mods.fml.common.Loader; import net.minecraft.block.*; import org.apache.logging.log4j.Level; import enviromine.core.EM_ConfigHandler.EnumLogVerbosity; import enviromine.core.EM_Settings; import enviromine.core.EnviroMine; import enviromine.handlers.ObjectHandler; import enviromine.trackers.properties.StabilityType; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.potion.Potion; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.BiomeDictionary; import net.minecraftforge.common.BiomeDictionary.Type; import net.minecraftforge.common.IExtendedEntityProperties; import net.minecraftforge.common.util.ForgeDirection; import thaumcraft.common.blocks.BlockMagicalLeaves; import static enviromine.trackers.EnviroDataTracker.isTCLoaded;
13,284
package enviromine.utils; public class EnviroUtils { public static final String[] reservedNames = new String[] {"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}; public static final char[] specialCharacters = new char[] {'/', '\n', '\r', '\t', '\u0000', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':'}; private static final String IEEP_PLAYER_WITCHERY = "WitcheryExtendedPlayer"; private static final String IEEP_PLAYER_WITCHERY_CREATURE_TYPE = "CreatureType"; private static final String IEEP_PLAYER_WITCHERY_VAMPIRE_LEVEL = "VampireLevel"; private static final String IEEP_PLAYER_WITCHERY_WEREWOLF_LEVEL = "WerewolfLevel"; private static final String IEEP_PLAYER_WITCHERY_DEMON_LEVEL = "DemonLevel"; private static final String IEEP_PLAYER_MO_ANDROID = "AndroidPlayer"; private static final String IEEP_PLAYER_MO_ISANDROID = "isAndroid"; public static void extendPotionList() { int maxID = 32;
package enviromine.utils; public class EnviroUtils { public static final String[] reservedNames = new String[] {"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}; public static final char[] specialCharacters = new char[] {'/', '\n', '\r', '\t', '\u0000', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':'}; private static final String IEEP_PLAYER_WITCHERY = "WitcheryExtendedPlayer"; private static final String IEEP_PLAYER_WITCHERY_CREATURE_TYPE = "CreatureType"; private static final String IEEP_PLAYER_WITCHERY_VAMPIRE_LEVEL = "VampireLevel"; private static final String IEEP_PLAYER_WITCHERY_WEREWOLF_LEVEL = "WerewolfLevel"; private static final String IEEP_PLAYER_WITCHERY_DEMON_LEVEL = "DemonLevel"; private static final String IEEP_PLAYER_MO_ANDROID = "AndroidPlayer"; private static final String IEEP_PLAYER_MO_ISANDROID = "isAndroid"; public static void extendPotionList() { int maxID = 32;
if(EM_Settings.heatstrokePotionID >= maxID)
1
2023-11-16 18:15:29+00:00
16k
exadel-inc/etoolbox-anydiff
core/src/test/java/com/exadel/etoolbox/anydiff/AllTests.java
[ { "identifier": "DiffBlockXPathTest", "path": "core/src/test/java/com/exadel/etoolbox/anydiff/comparison/DiffBlockXPathTest.java", "snippet": "public class DiffBlockXPathTest {\n\n @Test\n public void shouldReportHtmlPath() throws IOException {\n try (\n InputStream leftInput...
import com.exadel.etoolbox.anydiff.comparison.DiffBlockXPathTest; import com.exadel.etoolbox.anydiff.comparison.DiffCountTest; import com.exadel.etoolbox.anydiff.comparison.DiffTaskTest; import com.exadel.etoolbox.anydiff.comparison.DiffTest; import com.exadel.etoolbox.anydiff.comparison.FragmentTest; import com.exadel.etoolbox.anydiff.comparison.MarkedStringTest; import com.exadel.etoolbox.anydiff.comparison.SpacesHandlingTest; import com.exadel.etoolbox.anydiff.comparison.preprocessor.PreprocessorsTest; import com.exadel.etoolbox.anydiff.runner.DiffRunnerTest; import com.exadel.etoolbox.anydiff.runner.FilterHelperTest; import com.exadel.etoolbox.anydiff.runner.FiltersTest; import org.junit.runner.RunWith; import org.junit.runners.Suite;
14,094
/* * 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.exadel.etoolbox.anydiff; @RunWith(Suite.class) @Suite.SuiteClasses({ DiffTest.class, DiffRunnerTest.class, DiffTaskTest.class, DiffCountTest.class, DiffBlockXPathTest.class,
/* * 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.exadel.etoolbox.anydiff; @RunWith(Suite.class) @Suite.SuiteClasses({ DiffTest.class, DiffRunnerTest.class, DiffTaskTest.class, DiffCountTest.class, DiffBlockXPathTest.class,
FragmentTest.class,
4
2023-11-16 14:29:45+00:00
16k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/capability/CapabilityHandler.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 java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.network.PacketDistributor; import org.apache.commons.lang3.Validate; import sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationHandler; import sheridan.gunscraft.events.RenderEvents; import sheridan.gunscraft.network.LoginPacks; import sheridan.gunscraft.network.PacketHandler; import sheridan.gunscraft.network.packets.SyncPlayerDataPacket;
12,234
key.setId(nextId); this.keyMap.put(key.getKey(), key); this.keyIdMap.put(nextId, key); } } public <T> void set(PlayerEntity player, CapabilityKey<T> key, T value) { if(this.keyMap.containsValue(key)) { PlayerDataManager manager = this.getDataManager(player); if(manager != null && manager.set(player, key, value)) { if(!player.world.isRemote) { this.dataChanged = true; } } } } public <T> T get(PlayerEntity player, CapabilityKey<T> key) { if(this.keyMap.containsValue(key)) { PlayerDataManager manager = this.getDataManager(player); return manager != null ? manager.get(key) : key.getDefaultValueSupplier().get(); } return null; } @OnlyIn(Dist.CLIENT) public <T> void updateClientData(PlayerEntity player, Pair<T> entry) { CapabilityHandler.getInstance().set(player, entry.getKey(), entry.getValue()); } @Nullable public CapabilityKey<?> getKey(int id) { return this.keyIdMap.get(id); } public List<CapabilityKey<?>> getKeys() { return ImmutableList.copyOf(this.keyMap.values()); } @Nullable private PlayerDataManager getDataManager(PlayerEntity player) { return player.getCapability(CAPABILITY, null).orElse(null); } @SubscribeEvent public void attachCapabilities(AttachCapabilitiesEvent<Entity> event) { if(event.getObject() instanceof PlayerEntity) { event.addCapability(new ResourceLocation(Gunscraft.MOD_ID, "sync_player_data"), new CapabilityProvider()); } } public static class CapabilityProvider implements ICapabilitySerializable<ListNBT> { final PlayerDataManager INSTANCE = new PlayerDataManager(); @Override public ListNBT serializeNBT() { return (ListNBT) CAPABILITY.getStorage().writeNBT(CAPABILITY, INSTANCE, null); } @Override public void deserializeNBT(ListNBT compound) { CAPABILITY.getStorage().readNBT(CAPABILITY, INSTANCE, null, compound); } @Nonnull @Override public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { return CAPABILITY.orEmpty(cap, LazyOptional.of(() -> INSTANCE)); } } @SubscribeEvent public void onPlayerJoinWorld(EntityJoinWorldEvent event) { Entity entity = event.getEntity(); if(entity instanceof PlayerEntity && !event.getWorld().isRemote) { PlayerEntity player = (PlayerEntity) entity; PlayerDataManager manager = this.getDataManager(player); if(manager != null) { List<Pair<?>> pairs = manager.gatherAll(); if(!pairs.isEmpty()) { PacketHandler.CommonChannel.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new SyncPlayerDataPacket(player.getEntityId(), pairs)); } } } } @SubscribeEvent public void onStartTracking(PlayerEvent.StartTracking event) { if(event.getTarget() instanceof PlayerEntity && !event.getPlayer().world.isRemote) { PlayerEntity player = (PlayerEntity) event.getTarget(); PlayerDataManager manager = this.getDataManager(player); if(manager != null) { List<Pair<?>> pairs = manager.gatherAll(); pairs.removeIf(entry -> !entry.getKey().shouldSyncToAllPlayers()); if(!pairs.isEmpty()) { PacketHandler.CommonChannel.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new SyncPlayerDataPacket(player.getEntityId(), pairs)); } } } } @SubscribeEvent public void onPlayerClone(PlayerEvent.Clone event) { PlayerEntity original = event.getOriginal(); if(!original.world.isRemote) { PlayerEntity player = event.getPlayer(); PlayerDataManager originalManager = this.getDataManager(original); if(originalManager != null) { PlayerDataManager newManager = this.getDataManager(player); if(newManager != null) { Map<CapabilityKey<?>, Pair<?>> dataMap = new HashMap<>(originalManager.dataMap); if(event.isWasDeath()) { dataMap.entrySet().removeIf(entry -> !entry.getKey().isShouldKeepAfterDeath()); } newManager.dataMap = dataMap; } } }
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package sheridan.gunscraft.capability; public class CapabilityHandler { @CapabilityInject(PlayerDataManager.class) public static final Capability<PlayerDataManager> CAPABILITY = null; public static CapabilityHandler INSTANCE; private static boolean init = false; public boolean dataChanged = false; private final Map<ResourceLocation, CapabilityKey<?>> keyMap = new HashMap<>(); private final Map<Integer, CapabilityKey<?>> keyIdMap = new HashMap<>(); private int nextKeyId = 0; private CapabilityHandler() {} public static CapabilityHandler getInstance() { if(INSTANCE == null) { INSTANCE = new CapabilityHandler(); } return INSTANCE; } public static void init() { if(!init) { CapabilityManager.INSTANCE.register(PlayerDataManager.class, new Storage(), PlayerDataManager::new); MinecraftForge.EVENT_BUS.register(getInstance()); init = true; } } public void registerKey(CapabilityKey<?> key) { if(!this.keyMap.containsKey(key.getKey())) { int nextId = this.nextKeyId++; key.setId(nextId); this.keyMap.put(key.getKey(), key); this.keyIdMap.put(nextId, key); } } public <T> void set(PlayerEntity player, CapabilityKey<T> key, T value) { if(this.keyMap.containsValue(key)) { PlayerDataManager manager = this.getDataManager(player); if(manager != null && manager.set(player, key, value)) { if(!player.world.isRemote) { this.dataChanged = true; } } } } public <T> T get(PlayerEntity player, CapabilityKey<T> key) { if(this.keyMap.containsValue(key)) { PlayerDataManager manager = this.getDataManager(player); return manager != null ? manager.get(key) : key.getDefaultValueSupplier().get(); } return null; } @OnlyIn(Dist.CLIENT) public <T> void updateClientData(PlayerEntity player, Pair<T> entry) { CapabilityHandler.getInstance().set(player, entry.getKey(), entry.getValue()); } @Nullable public CapabilityKey<?> getKey(int id) { return this.keyIdMap.get(id); } public List<CapabilityKey<?>> getKeys() { return ImmutableList.copyOf(this.keyMap.values()); } @Nullable private PlayerDataManager getDataManager(PlayerEntity player) { return player.getCapability(CAPABILITY, null).orElse(null); } @SubscribeEvent public void attachCapabilities(AttachCapabilitiesEvent<Entity> event) { if(event.getObject() instanceof PlayerEntity) { event.addCapability(new ResourceLocation(Gunscraft.MOD_ID, "sync_player_data"), new CapabilityProvider()); } } public static class CapabilityProvider implements ICapabilitySerializable<ListNBT> { final PlayerDataManager INSTANCE = new PlayerDataManager(); @Override public ListNBT serializeNBT() { return (ListNBT) CAPABILITY.getStorage().writeNBT(CAPABILITY, INSTANCE, null); } @Override public void deserializeNBT(ListNBT compound) { CAPABILITY.getStorage().readNBT(CAPABILITY, INSTANCE, null, compound); } @Nonnull @Override public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { return CAPABILITY.orEmpty(cap, LazyOptional.of(() -> INSTANCE)); } } @SubscribeEvent public void onPlayerJoinWorld(EntityJoinWorldEvent event) { Entity entity = event.getEntity(); if(entity instanceof PlayerEntity && !event.getWorld().isRemote) { PlayerEntity player = (PlayerEntity) entity; PlayerDataManager manager = this.getDataManager(player); if(manager != null) { List<Pair<?>> pairs = manager.gatherAll(); if(!pairs.isEmpty()) { PacketHandler.CommonChannel.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new SyncPlayerDataPacket(player.getEntityId(), pairs)); } } } } @SubscribeEvent public void onStartTracking(PlayerEvent.StartTracking event) { if(event.getTarget() instanceof PlayerEntity && !event.getPlayer().world.isRemote) { PlayerEntity player = (PlayerEntity) event.getTarget(); PlayerDataManager manager = this.getDataManager(player); if(manager != null) { List<Pair<?>> pairs = manager.gatherAll(); pairs.removeIf(entry -> !entry.getKey().shouldSyncToAllPlayers()); if(!pairs.isEmpty()) { PacketHandler.CommonChannel.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new SyncPlayerDataPacket(player.getEntityId(), pairs)); } } } } @SubscribeEvent public void onPlayerClone(PlayerEvent.Clone event) { PlayerEntity original = event.getOriginal(); if(!original.world.isRemote) { PlayerEntity player = event.getPlayer(); PlayerDataManager originalManager = this.getDataManager(original); if(originalManager != null) { PlayerDataManager newManager = this.getDataManager(player); if(newManager != null) { Map<CapabilityKey<?>, Pair<?>> dataMap = new HashMap<>(originalManager.dataMap); if(event.isWasDeath()) { dataMap.entrySet().removeIf(entry -> !entry.getKey().isShouldKeepAfterDeath()); } newManager.dataMap = dataMap; } } }
if (original.getEntityId() == ClientProxy.clientPlayerId && original == Minecraft.getInstance().player) {
0
2023-11-14 14:00:55+00:00
16k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/utils/tasks/SignAPK.java
[ { "identifier": "APKTasksActivity", "path": "app/src/main/java/com/threethan/questpatcher/activities/APKTasksActivity.java", "snippet": "public class APKTasksActivity extends AppCompatActivity {\n\n private AppCompatImageView mIcon;\n private ProgressBar mProgress;\n private View mCancel, mDeta...
import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.util.Log; import com.threethan.questpatcher.R; import com.threethan.questpatcher.activities.APKTasksActivity; import com.threethan.questpatcher.utils.APKData; import com.threethan.questpatcher.utils.APKEditorUtils; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.InvalidZipException; import com.threethan.questpatcher.utils.SplitAPKInstaller; import com.threethan.questpatcher.utils.ZipAlign; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils; import in.sunilpaulmathew.sCommon.PackageUtils.sPackageUtils;
12,165
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on January 28, 2023 */ public class SignAPK extends sExecutor { private final Activity mActivity; private File mBackUpPath = null, mBuildDir = null, mExportPath = null, mTMPZip = null; private File mParent; public SignAPK(Activity activity) { mActivity = activity; } @SuppressLint("StringFormatInvalid") @Override public void onPreExecute() { mExportPath = new File(mActivity.getCacheDir(), Common.getAppID()); mTMPZip = new File(mActivity.getCacheDir(), "tmp.apk"); Common.setFinishStatus(false); Common.isCancelled(false); Common.isBuilding(true); Common.setStatus(null); Intent apkTasks = new Intent(mActivity, APKTasksActivity.class); mActivity.startActivity(apkTasks); Common.setStatus(mActivity.getString(R.string.preparing_apk, Common.getAppID())); mBuildDir = new File(mExportPath, ".aeeBuild"); mBackUpPath = new File(mExportPath, ".aeeBackup"); if (mBuildDir.exists()) { sFileUtils.delete(mBuildDir); } sFileUtils.mkdir(mBuildDir); if (mTMPZip.exists()) { sFileUtils.delete(mTMPZip); } } List<String> apks = new ArrayList<>(); @SuppressLint("StringFormatInvalid") @Override public void doInBackground() { Common.setStatus(mActivity.getString(R.string.preparing_source)); APKData.prepareSource(mBuildDir, mExportPath, mBackUpPath, mActivity); if (Common.getError() > 0) { return; }
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on January 28, 2023 */ public class SignAPK extends sExecutor { private final Activity mActivity; private File mBackUpPath = null, mBuildDir = null, mExportPath = null, mTMPZip = null; private File mParent; public SignAPK(Activity activity) { mActivity = activity; } @SuppressLint("StringFormatInvalid") @Override public void onPreExecute() { mExportPath = new File(mActivity.getCacheDir(), Common.getAppID()); mTMPZip = new File(mActivity.getCacheDir(), "tmp.apk"); Common.setFinishStatus(false); Common.isCancelled(false); Common.isBuilding(true); Common.setStatus(null); Intent apkTasks = new Intent(mActivity, APKTasksActivity.class); mActivity.startActivity(apkTasks); Common.setStatus(mActivity.getString(R.string.preparing_apk, Common.getAppID())); mBuildDir = new File(mExportPath, ".aeeBuild"); mBackUpPath = new File(mExportPath, ".aeeBackup"); if (mBuildDir.exists()) { sFileUtils.delete(mBuildDir); } sFileUtils.mkdir(mBuildDir); if (mTMPZip.exists()) { sFileUtils.delete(mTMPZip); } } List<String> apks = new ArrayList<>(); @SuppressLint("StringFormatInvalid") @Override public void doInBackground() { Common.setStatus(mActivity.getString(R.string.preparing_source)); APKData.prepareSource(mBuildDir, mExportPath, mBackUpPath, mActivity); if (Common.getError() > 0) { return; }
APKEditorUtils.zip(mBuildDir, mTMPZip);
2
2023-11-18 15:13:30+00:00
16k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/security/rest/AuthorizationController.java
[ { "identifier": "RsaProperties", "path": "dimple-common/src/main/java/com/dimple/config/RsaProperties.java", "snippet": "@Data\n@Component\npublic class RsaProperties {\n\n public static String privateKey;\n\n @Value(\"${rsa.private_key}\")\n public void setPrivateKey(String privateKey) {\n ...
import cn.hutool.core.util.IdUtil; import com.dimple.annotation.OLog; import com.dimple.annotation.rest.AnonymousDeleteMapping; import com.dimple.annotation.rest.AnonymousGetMapping; import com.dimple.annotation.rest.AnonymousPostMapping; import com.dimple.config.RsaProperties; import com.dimple.exception.BadRequestException; import com.dimple.modules.security.config.bean.LoginProperties; import com.dimple.modules.security.config.bean.SecurityProperties; import com.dimple.modules.security.security.TokenProvider; import com.dimple.modules.security.service.OnlineUserService; import com.dimple.modules.security.service.dto.AuthUserDTO; import com.dimple.modules.security.service.dto.JwtUserDTO; import com.dimple.service.LoginLogService; import com.dimple.utils.RedisUtils; import com.dimple.utils.RsaUtils; import com.dimple.utils.SecurityUtils; import com.dimple.utils.StringUtils; import com.wf.captcha.base.Captcha; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit;
12,334
package com.dimple.modules.security.rest; /** * @className: AuthorizationController * @description: * @author: Dimple * @date: 06/17/20 */ @Slf4j @RestController @RequestMapping("/auth") @RequiredArgsConstructor @Api(tags = "系统:系统授权接口") public class AuthorizationController { private final SecurityProperties properties; private final RedisUtils redisUtils; private final OnlineUserService onlineUserService; private final TokenProvider tokenProvider; private final AuthenticationManagerBuilder authenticationManagerBuilder; private final LoginLogService loginLogService; @Resource private LoginProperties loginProperties; @OLog("用户登录") @ApiOperation("登录授权") @AnonymousPostMapping(value = "/login") public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDTO authUser, HttpServletRequest request) throws Exception { // 密码解密 String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword()); // 查询验证码 String code = (String) redisUtils.get(authUser.getUuid()); // 清除验证码 redisUtils.del(authUser.getUuid()); if (StringUtils.isBlank(code)) { loginLogService.save(false, authUser.getUsername(), authUser.getUuid(), request, "验证码不存在或已过期"); throw new BadRequestException("验证码不存在或已过期"); } if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) { loginLogService.save(false, authUser.getUsername(), authUser.getUuid(), request, "验证码错误"); throw new BadRequestException("验证码错误"); } Map<String, Object> authInfo; String token; try { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authUser.getUsername(), password); Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); // 生成令牌 token = tokenProvider.createToken(authentication); final JwtUserDTO jwtUserDto = (JwtUserDTO) authentication.getPrincipal(); // 保存在线信息 onlineUserService.save(jwtUserDto, token, request); // 返回 token 与 用户信息 authInfo = new HashMap<String, Object>(2) {{ put("token", properties.getTokenStartWith() + token); put("user", jwtUserDto); }}; } catch (Exception e) { loginLogService.save(false, authUser.getUsername(), authUser.getUuid(), request, e.getMessage()); throw e; } if (loginProperties.isSingleLogin()) { //踢掉之前已经登录的token onlineUserService.checkLoginOnUser(authUser.getUsername(), token); } loginLogService.save(true, authUser.getUsername(), authUser.getUuid(), request, "登录成功"); return ResponseEntity.ok(authInfo); } @ApiOperation("获取用户信息") @GetMapping(value = "/info") public ResponseEntity<Object> getUserInfo() {
package com.dimple.modules.security.rest; /** * @className: AuthorizationController * @description: * @author: Dimple * @date: 06/17/20 */ @Slf4j @RestController @RequestMapping("/auth") @RequiredArgsConstructor @Api(tags = "系统:系统授权接口") public class AuthorizationController { private final SecurityProperties properties; private final RedisUtils redisUtils; private final OnlineUserService onlineUserService; private final TokenProvider tokenProvider; private final AuthenticationManagerBuilder authenticationManagerBuilder; private final LoginLogService loginLogService; @Resource private LoginProperties loginProperties; @OLog("用户登录") @ApiOperation("登录授权") @AnonymousPostMapping(value = "/login") public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDTO authUser, HttpServletRequest request) throws Exception { // 密码解密 String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword()); // 查询验证码 String code = (String) redisUtils.get(authUser.getUuid()); // 清除验证码 redisUtils.del(authUser.getUuid()); if (StringUtils.isBlank(code)) { loginLogService.save(false, authUser.getUsername(), authUser.getUuid(), request, "验证码不存在或已过期"); throw new BadRequestException("验证码不存在或已过期"); } if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) { loginLogService.save(false, authUser.getUsername(), authUser.getUuid(), request, "验证码错误"); throw new BadRequestException("验证码错误"); } Map<String, Object> authInfo; String token; try { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authUser.getUsername(), password); Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); // 生成令牌 token = tokenProvider.createToken(authentication); final JwtUserDTO jwtUserDto = (JwtUserDTO) authentication.getPrincipal(); // 保存在线信息 onlineUserService.save(jwtUserDto, token, request); // 返回 token 与 用户信息 authInfo = new HashMap<String, Object>(2) {{ put("token", properties.getTokenStartWith() + token); put("user", jwtUserDto); }}; } catch (Exception e) { loginLogService.save(false, authUser.getUsername(), authUser.getUuid(), request, e.getMessage()); throw e; } if (loginProperties.isSingleLogin()) { //踢掉之前已经登录的token onlineUserService.checkLoginOnUser(authUser.getUsername(), token); } loginLogService.save(true, authUser.getUsername(), authUser.getUuid(), request, "登录成功"); return ResponseEntity.ok(authInfo); } @ApiOperation("获取用户信息") @GetMapping(value = "/info") public ResponseEntity<Object> getUserInfo() {
return ResponseEntity.ok(SecurityUtils.getCurrentUser());
11
2023-11-10 03:30:36+00:00
16k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/moduleedit/toolbar/needmodule/NeedModuleCombobox.java
[ { "identifier": "ModuleInfo", "path": "database/src/main/java/com/lazycoder/database/model/ModuleInfo.java", "snippet": "@NoArgsConstructor\n@Data\npublic class ModuleInfo implements BaseModel {\n\n\tprivate String moduleId;\n\n\t/**\n\t * 分类名\n\t */\n\tprivate String className = \"\";\n\n\t/**\n\t * 模块...
import com.lazycoder.database.model.ModuleInfo; import com.lazycoder.database.model.formodule.ModuleStaticMethod; import com.lazycoder.service.service.SysService; import com.lazycoder.uidatasourceedit.DataSourceEditHolder; import com.lazycoder.uidatasourceedit.ModuleEditPaneHolder; import com.lazycoder.uidatasourceedit.moduleedit.ModuleEditComponentInterface; import com.lazycoder.uiutils.component.MultiSelectComboBox; import java.util.ArrayList; import java.util.List; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener;
10,926
package com.lazycoder.uidatasourceedit.moduleedit.toolbar.needmodule; /** * 使用模块前,需要调用的模块的设置下拉框 该下拉框列出所有模块 * * @param <Module> * @author admin */ public class NeedModuleCombobox<Module> extends MultiSelectComboBox<Module> implements ModuleEditComponentInterface { /** * */ private static final long serialVersionUID = -1584741096952249466L; public NeedModuleCombobox() { // TODO Auto-generated constructor stub super(); setRenderer(new NeedModuleComboboxRenderer()); // setModel((ComboBoxModel<Module>) // NeedModuleComboboxRenderer.getTestModel()); // addPopupMenuListener(listener); } private PopupMenuListener listener = new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { // TODO Auto-generated method stub } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { // TODO Auto-generated method stub } @Override public void popupMenuCanceled(PopupMenuEvent e) { // TODO Auto-generated method stub } }; /** * 添加需要用到的模块列表 */ @SuppressWarnings("unchecked") public void addNeedUseModuleList() { List<com.lazycoder.database.model.Module> moduleList = (List<com.lazycoder.database.model.Module>) getSelectedItems(); if (moduleList != null) {
package com.lazycoder.uidatasourceedit.moduleedit.toolbar.needmodule; /** * 使用模块前,需要调用的模块的设置下拉框 该下拉框列出所有模块 * * @param <Module> * @author admin */ public class NeedModuleCombobox<Module> extends MultiSelectComboBox<Module> implements ModuleEditComponentInterface { /** * */ private static final long serialVersionUID = -1584741096952249466L; public NeedModuleCombobox() { // TODO Auto-generated constructor stub super(); setRenderer(new NeedModuleComboboxRenderer()); // setModel((ComboBoxModel<Module>) // NeedModuleComboboxRenderer.getTestModel()); // addPopupMenuListener(listener); } private PopupMenuListener listener = new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { // TODO Auto-generated method stub } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { // TODO Auto-generated method stub } @Override public void popupMenuCanceled(PopupMenuEvent e) { // TODO Auto-generated method stub } }; /** * 添加需要用到的模块列表 */ @SuppressWarnings("unchecked") public void addNeedUseModuleList() { List<com.lazycoder.database.model.Module> moduleList = (List<com.lazycoder.database.model.Module>) getSelectedItems(); if (moduleList != null) {
ModuleEditPaneHolder.needUseCodeFileEditPane.addNeedUseCodeFormatPaneByModuleList(moduleList);
4
2023-11-16 11:55:06+00:00
16k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506/KSUnknown.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.MainContext; import kr.or.kashi.hde.HomeDevice; import kr.or.kashi.hde.ksx4506.KSDeviceContextBase; import kr.or.kashi.hde.ksx4506.KSPacket; import java.util.Map;
11,239
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /** * [KS X 4506] Fallback implementation for unknown HomeDevice */ public class KSUnknown extends KSDeviceContextBase { private static final String TAG = "KSUnknown"; private static final boolean DBG = true; public KSUnknown(MainContext mainContext, Map defaultProps) {
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /** * [KS X 4506] Fallback implementation for unknown HomeDevice */ public class KSUnknown extends KSDeviceContextBase { private static final String TAG = "KSUnknown"; private static final boolean DBG = true; public KSUnknown(MainContext mainContext, Map defaultProps) {
super(mainContext, defaultProps, HomeDevice.class);
2
2023-11-10 01:19:44+00:00
16k
xLorey/FluxLoader
src/main/java/zombie/network/chat/ChatServer.java
[ { "identifier": "EventManager", "path": "src/main/java/io/xlorey/FluxLoader/shared/EventManager.java", "snippet": "@UtilityClass\npublic class EventManager {\n /**\n * Event Listeners\n */\n private static final ArrayList<Object> listeners = new ArrayList<>();\n\n /**\n * Subscribin...
import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Stack; import java.util.concurrent.ConcurrentHashMap; import io.xlorey.FluxLoader.annotations.Modified; import io.xlorey.FluxLoader.shared.EventManager; import zombie.GameWindow; import zombie.characters.Faction; import zombie.characters.IsoPlayer; import zombie.chat.ChatBase; import zombie.chat.ChatMessage; import zombie.chat.ChatTab; import zombie.chat.ChatUtility; import zombie.chat.ServerChatMessage; import zombie.chat.defaultChats.AdminChat; import zombie.chat.defaultChats.FactionChat; import zombie.chat.defaultChats.GeneralChat; import zombie.chat.defaultChats.RadioChat; import zombie.chat.defaultChats.SafehouseChat; import zombie.chat.defaultChats.SayChat; import zombie.chat.defaultChats.ServerChat; import zombie.chat.defaultChats.ShoutChat; import zombie.chat.defaultChats.WhisperChat; import zombie.core.Core; import zombie.core.logger.LoggerManager; import zombie.core.logger.ZLogger; import zombie.core.network.ByteBufferWriter; import zombie.core.raknet.UdpConnection; import zombie.iso.areas.SafeHouse; import zombie.network.ServerOptions; import zombie.network.PacketTypes.PacketType;
14,173
} return instance; } public static boolean isInited() { return inited; } private ChatServer() { } public void init() { if (!inited) { LoggerManager.createLogger("chat", Core.bDebug); logger = LoggerManager.getLogger("chat"); logger.write("Start chat server initialization...", "info"); ChatTab var1 = new ChatTab((short)0, "UI_chat_main_tab_title_id"); ChatTab var2 = new ChatTab((short)1, "UI_chat_admin_tab_title_id"); boolean var3 = ServerOptions.getInstance().DiscordEnable.getValue(); GeneralChat var4 = new GeneralChat(this.getNextChatID(), var1, var3); SayChat var5 = new SayChat(this.getNextChatID(), var1); ShoutChat var6 = new ShoutChat(this.getNextChatID(), var1); RadioChat var7 = new RadioChat(this.getNextChatID(), var1); AdminChat var8 = new AdminChat(this.getNextChatID(), var2); ServerChat var9 = new ServerChat(this.getNextChatID(), var1); chats.put(var4.getID(), var4); chats.put(var5.getID(), var5); chats.put(var6.getID(), var6); chats.put(var7.getID(), var7); chats.put(var8.getID(), var8); chats.put(var9.getID(), var9); defaultChats.put(var4.getType(), var4); defaultChats.put(var5.getType(), var5); defaultChats.put(var6.getType(), var6); defaultChats.put(var9.getType(), var9); defaultChats.put(var7.getType(), var7); tabs.put("main", var1); tabs.put("admin", var2); generalChat = var4; adminChat = var8; serverChat = var9; radioChat = var7; inited = true; logger.write("General chat has id = " + var4.getID(), "info"); logger.write("Say chat has id = " + var5.getID(), "info"); logger.write("Shout chat has id = " + var6.getID(), "info"); logger.write("Radio chat has id = " + var7.getID(), "info"); logger.write("Admin chat has id = " + var8.getID(), "info"); logger.write("Server chat has id = " + serverChat.getID(), "info"); logger.write("Chat server successfully initialized", "info"); } } public void initPlayer(short var1) { logger.write("Player with id = '" + var1 + "' tries to connect", "info"); synchronized(players) { if (players.contains(var1)) { logger.write("Player already connected!", "warning"); return; } } logger.write("Adding player '" + var1 + "' to chat server", "info"); IsoPlayer var2 = ChatUtility.findPlayer(var1); UdpConnection var3 = ChatUtility.findConnection(var1); if (var3 != null && var2 != null) { this.sendInitPlayerChatPacket(var3); this.addDefaultChats(var1); logger.write("Player joined to default chats", "info"); if (var3.accessLevel == 32) { this.joinAdminChat(var1); } Faction var4 = Faction.getPlayerFaction(var2); if (var4 != null) { this.addMemberToFactionChat(var4.getName(), var1); } SafeHouse var5 = SafeHouse.hasSafehouse(var2); if (var5 != null) { this.addMemberToSafehouseChat(var5.getId(), var1); } ByteBufferWriter var6 = var3.startPacket(); PacketType.PlayerConnectedToChat.doPacket(var6); PacketType.PlayerConnectedToChat.send(var3); synchronized(players) { players.add(var1); } logger.write("Player " + var2.getUsername() + "(" + var1 + ") joined to chat server successfully", "info"); } else { logger.write("Player or connection is not found on server!", "error"); logger.write((var3 == null ? "connection = null " : "") + (var2 == null ? "player = null" : ""), "error"); } } @Modified public void processMessageFromPlayerPacket(ByteBuffer var1) { int var2 = var1.getInt(); synchronized(chats) { ChatBase var4 = (ChatBase)chats.get(var2); ChatMessage var5 = var4.unpackMessage(var1); EventManager.invokeEvent("onChatServerMessage", var4, var5); logger.write("Got message:" + var5, "info"); if (!ChatUtility.chatStreamEnabled(var4.getType())) { logger.write("Message ignored by server because the chat disabled by server settings", "warning"); } else { this.sendMessage(var5); logger.write("Message " + var5 + " sent to chat (id = " + var4.getID() + ") members", "info"); } } } public void processPlayerStartWhisperChatPacket(ByteBuffer var1) { logger.write("Whisper chat starting...", "info"); if (!ChatUtility.chatStreamEnabled(ChatType.whisper)) { logger.write("Message for whisper chat is ignored because whisper chat is disabled by server settings", "info"); } else {
package zombie.network.chat; @SuppressWarnings(value = "unchecked") public class ChatServer { private static ChatServer instance = null; private static final Stack<Integer> availableChatsID = new Stack(); private static int lastChatId = -1; private static final HashMap<ChatType, ChatBase> defaultChats = new HashMap(); private static final ConcurrentHashMap<Integer, ChatBase> chats = new ConcurrentHashMap(); private static final ConcurrentHashMap<String, FactionChat> factionChats = new ConcurrentHashMap(); private static final ConcurrentHashMap<String, SafehouseChat> safehouseChats = new ConcurrentHashMap(); private static AdminChat adminChat = null; private static GeneralChat generalChat = null; private static ServerChat serverChat = null; private static RadioChat radioChat = null; private static boolean inited = false; private static final HashSet<Short> players = new HashSet(); private static final String logName = "chat"; private static ZLogger logger; private static final HashMap<String, ChatTab> tabs = new HashMap(); private static final String mainTabID = "main"; private static final String adminTabID = "admin"; public static ChatServer getInstance() { if (instance == null) { instance = new ChatServer(); } return instance; } public static boolean isInited() { return inited; } private ChatServer() { } public void init() { if (!inited) { LoggerManager.createLogger("chat", Core.bDebug); logger = LoggerManager.getLogger("chat"); logger.write("Start chat server initialization...", "info"); ChatTab var1 = new ChatTab((short)0, "UI_chat_main_tab_title_id"); ChatTab var2 = new ChatTab((short)1, "UI_chat_admin_tab_title_id"); boolean var3 = ServerOptions.getInstance().DiscordEnable.getValue(); GeneralChat var4 = new GeneralChat(this.getNextChatID(), var1, var3); SayChat var5 = new SayChat(this.getNextChatID(), var1); ShoutChat var6 = new ShoutChat(this.getNextChatID(), var1); RadioChat var7 = new RadioChat(this.getNextChatID(), var1); AdminChat var8 = new AdminChat(this.getNextChatID(), var2); ServerChat var9 = new ServerChat(this.getNextChatID(), var1); chats.put(var4.getID(), var4); chats.put(var5.getID(), var5); chats.put(var6.getID(), var6); chats.put(var7.getID(), var7); chats.put(var8.getID(), var8); chats.put(var9.getID(), var9); defaultChats.put(var4.getType(), var4); defaultChats.put(var5.getType(), var5); defaultChats.put(var6.getType(), var6); defaultChats.put(var9.getType(), var9); defaultChats.put(var7.getType(), var7); tabs.put("main", var1); tabs.put("admin", var2); generalChat = var4; adminChat = var8; serverChat = var9; radioChat = var7; inited = true; logger.write("General chat has id = " + var4.getID(), "info"); logger.write("Say chat has id = " + var5.getID(), "info"); logger.write("Shout chat has id = " + var6.getID(), "info"); logger.write("Radio chat has id = " + var7.getID(), "info"); logger.write("Admin chat has id = " + var8.getID(), "info"); logger.write("Server chat has id = " + serverChat.getID(), "info"); logger.write("Chat server successfully initialized", "info"); } } public void initPlayer(short var1) { logger.write("Player with id = '" + var1 + "' tries to connect", "info"); synchronized(players) { if (players.contains(var1)) { logger.write("Player already connected!", "warning"); return; } } logger.write("Adding player '" + var1 + "' to chat server", "info"); IsoPlayer var2 = ChatUtility.findPlayer(var1); UdpConnection var3 = ChatUtility.findConnection(var1); if (var3 != null && var2 != null) { this.sendInitPlayerChatPacket(var3); this.addDefaultChats(var1); logger.write("Player joined to default chats", "info"); if (var3.accessLevel == 32) { this.joinAdminChat(var1); } Faction var4 = Faction.getPlayerFaction(var2); if (var4 != null) { this.addMemberToFactionChat(var4.getName(), var1); } SafeHouse var5 = SafeHouse.hasSafehouse(var2); if (var5 != null) { this.addMemberToSafehouseChat(var5.getId(), var1); } ByteBufferWriter var6 = var3.startPacket(); PacketType.PlayerConnectedToChat.doPacket(var6); PacketType.PlayerConnectedToChat.send(var3); synchronized(players) { players.add(var1); } logger.write("Player " + var2.getUsername() + "(" + var1 + ") joined to chat server successfully", "info"); } else { logger.write("Player or connection is not found on server!", "error"); logger.write((var3 == null ? "connection = null " : "") + (var2 == null ? "player = null" : ""), "error"); } } @Modified public void processMessageFromPlayerPacket(ByteBuffer var1) { int var2 = var1.getInt(); synchronized(chats) { ChatBase var4 = (ChatBase)chats.get(var2); ChatMessage var5 = var4.unpackMessage(var1); EventManager.invokeEvent("onChatServerMessage", var4, var5); logger.write("Got message:" + var5, "info"); if (!ChatUtility.chatStreamEnabled(var4.getType())) { logger.write("Message ignored by server because the chat disabled by server settings", "warning"); } else { this.sendMessage(var5); logger.write("Message " + var5 + " sent to chat (id = " + var4.getID() + ") members", "info"); } } } public void processPlayerStartWhisperChatPacket(ByteBuffer var1) { logger.write("Whisper chat starting...", "info"); if (!ChatUtility.chatStreamEnabled(ChatType.whisper)) { logger.write("Message for whisper chat is ignored because whisper chat is disabled by server settings", "info"); } else {
String var2 = GameWindow.ReadString(var1);
1
2023-11-16 09:05:44+00:00
16k
EmonerRobotics/2023Robot
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "IntakeConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb por...
import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj.smartdashboard.Field2d; import edu.wpi.first.wpilibj.smartdashboard.FieldObject2d; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.RunCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.Constants.IntakeConstants; import frc.robot.commands.AutoElevator; import frc.robot.commands.AutoIntake; import frc.robot.commands.DriveWithJoysticks; import frc.robot.commands.GetInRange; import frc.robot.commands.IntakeCommand; import frc.robot.commands.LiftCommand; import frc.robot.commands.PneumaticCommand; import frc.robot.commands.AutoElevator.ElevatorPosition; import frc.robot.commands.AutoIntake.IntakePosition; import frc.robot.commands.GetInRange.LimelightPositionCheck; import frc.robot.commands.autonomous.AutoBalance; import frc.robot.commands.autonomous.AutoCommand; import frc.robot.commands.autonomous.OnePieceCharge; import frc.robot.poseestimation.PoseEstimation; import frc.robot.subsystems.IntakeSubsystem; import frc.robot.subsystems.LiftSubsystem; import frc.robot.subsystems.LimelightSubsystem; import frc.robot.subsystems.PneumaticSubsystem; import frc.robot.subsystems.drivetrain.Drivetrain; import frc.robot.utils.AllianceUtils; import com.pathplanner.lib.server.PathPlannerServer;
11,957
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5))); if (!DriverStation.isFMSAttached()) { PathPlannerServer.startServer(5811); } drivetrain.setDefaultCommand(driveCommand); if (autoBalanceStartingPosition.getPoses().isEmpty()) { autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d()))); } configureBindings(); autoSelector = new SendableChooser<>(); autoSelector.setDefaultOption("grid1", "grid1"); // 1 kup en yukari kisa taxi //autoSelector.setDefaultOption("grid2", "grid2"); // 1 kup en yukari kisa taxi denge //autoSelector.setDefaultOption("grid3", "grid3"); // 1 kup en yukari ortadan denge //autoSelector.setDefaultOption("grid4", "grid4"); //1 kup en yukari uzun taxi denge //autoSelector.setDefaultOption("grid5", "grid5"); //1 kup en yukari uzun taxi } /** * Use this method to define your trigger->command mappings. Triggers can be created via the * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary * predicate, or via the named factories in {@link * edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link * CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller * PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight * joysticks}. */ private void configureBindings() { //setPoint type is inches //limelight sets 111 cm new JoystickButton(joystick1, 2). whileTrue(new GetInRange(drivetrain, poseEstimation, limelightSubsystem, 44, LimelightPositionCheck.fiftyFive)); //with Y or 4 button goes to the top new JoystickButton(joystick2, IntakeConstants.TopLevelB). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.TOPH, ElevatorPosition.TOP), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenD, IntakePosition.STRAIGHT))); //with B or 2 button goes to the human closes intake and goes to down new JoystickButton(joystick2, IntakeConstants.HumanPB). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.HUMANPH , ElevatorPosition.HUMANP), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenHD, IntakePosition.STRAIGHTHD), new PneumaticCommand(pneumaticSubsystem, true, false), new WaitCommand(1), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED), new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH , ElevatorPosition.GROUND))); //with A or 1 button goes to the down new JoystickButton(joystick2, IntakeConstants.GroundLevelB). toggleOnTrue(new SequentialCommandGroup( new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED), new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH, ElevatorPosition.GROUND) )); new JoystickButton(joystick2, 3). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.MIDH, ElevatorPosition.MIDDLE), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeHalfOpenD, IntakePosition.HALF) )); //Pneumatic new JoystickButton(joystick2, IntakeConstants.SolenoidOnB). onTrue(new PneumaticCommand(pneumaticSubsystem, true, false)); //aciyor new JoystickButton(joystick2, IntakeConstants.SolenoidOffB). onTrue(new PneumaticCommand(pneumaticSubsystem, false, true)); //kapatiyor // Pose Estimation new JoystickButton(joystick1, 6) .onTrue(new InstantCommand(driveCommand::resetFieldOrientation)); new JoystickButton(joystick1, 7) .onTrue(new InstantCommand(() -> poseEstimation.resetPose( new Pose2d( poseEstimation.getEstimatedPose().getTranslation(), new Rotation2d())))); // Driving new JoystickButton(joystick1, 1) .whileTrue(new RunCommand( drivetrain::setX, drivetrain)); new JoystickButton(joystick1, 3) .whileTrue(autoBalanceCommand); } public Command getAutonomousCommand() { Pose2d startingPose = startingPosition.getPose(); return new SequentialCommandGroup( new InstantCommand(() -> poseEstimation.resetPose(startingPose)),
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5))); if (!DriverStation.isFMSAttached()) { PathPlannerServer.startServer(5811); } drivetrain.setDefaultCommand(driveCommand); if (autoBalanceStartingPosition.getPoses().isEmpty()) { autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d()))); } configureBindings(); autoSelector = new SendableChooser<>(); autoSelector.setDefaultOption("grid1", "grid1"); // 1 kup en yukari kisa taxi //autoSelector.setDefaultOption("grid2", "grid2"); // 1 kup en yukari kisa taxi denge //autoSelector.setDefaultOption("grid3", "grid3"); // 1 kup en yukari ortadan denge //autoSelector.setDefaultOption("grid4", "grid4"); //1 kup en yukari uzun taxi denge //autoSelector.setDefaultOption("grid5", "grid5"); //1 kup en yukari uzun taxi } /** * Use this method to define your trigger->command mappings. Triggers can be created via the * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary * predicate, or via the named factories in {@link * edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link * CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller * PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight * joysticks}. */ private void configureBindings() { //setPoint type is inches //limelight sets 111 cm new JoystickButton(joystick1, 2). whileTrue(new GetInRange(drivetrain, poseEstimation, limelightSubsystem, 44, LimelightPositionCheck.fiftyFive)); //with Y or 4 button goes to the top new JoystickButton(joystick2, IntakeConstants.TopLevelB). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.TOPH, ElevatorPosition.TOP), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenD, IntakePosition.STRAIGHT))); //with B or 2 button goes to the human closes intake and goes to down new JoystickButton(joystick2, IntakeConstants.HumanPB). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.HUMANPH , ElevatorPosition.HUMANP), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenHD, IntakePosition.STRAIGHTHD), new PneumaticCommand(pneumaticSubsystem, true, false), new WaitCommand(1), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED), new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH , ElevatorPosition.GROUND))); //with A or 1 button goes to the down new JoystickButton(joystick2, IntakeConstants.GroundLevelB). toggleOnTrue(new SequentialCommandGroup( new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED), new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH, ElevatorPosition.GROUND) )); new JoystickButton(joystick2, 3). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.MIDH, ElevatorPosition.MIDDLE), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeHalfOpenD, IntakePosition.HALF) )); //Pneumatic new JoystickButton(joystick2, IntakeConstants.SolenoidOnB). onTrue(new PneumaticCommand(pneumaticSubsystem, true, false)); //aciyor new JoystickButton(joystick2, IntakeConstants.SolenoidOffB). onTrue(new PneumaticCommand(pneumaticSubsystem, false, true)); //kapatiyor // Pose Estimation new JoystickButton(joystick1, 6) .onTrue(new InstantCommand(driveCommand::resetFieldOrientation)); new JoystickButton(joystick1, 7) .onTrue(new InstantCommand(() -> poseEstimation.resetPose( new Pose2d( poseEstimation.getEstimatedPose().getTranslation(), new Rotation2d())))); // Driving new JoystickButton(joystick1, 1) .whileTrue(new RunCommand( drivetrain::setX, drivetrain)); new JoystickButton(joystick1, 3) .whileTrue(autoBalanceCommand); } public Command getAutonomousCommand() { Pose2d startingPose = startingPosition.getPose(); return new SequentialCommandGroup( new InstantCommand(() -> poseEstimation.resetPose(startingPose)),
new OnePieceCharge(),
13
2023-11-18 14:02:20+00:00
16k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/slayers/zombie/RevenantHorror.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.core.helpers.EntityHelper; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import com.sweattypalms.skyblock.core.items.types.slayer.zombie.items.BeheadedHorror; import com.sweattypalms.skyblock.core.mobs.builder.ISkyblockMob; import com.sweattypalms.skyblock.core.mobs.builder.MobAttributes; import com.sweattypalms.skyblock.core.mobs.builder.NameAttributes; import com.sweattypalms.skyblock.core.mobs.builder.SkyblockMob; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.slayers.ISlayerMob; import com.sweattypalms.skyblock.slayers.Slayer; import com.sweattypalms.skyblock.slayers.SlayerTimer; import com.sweattypalms.skyblock.slayers.events.SlayerFailEvent; import net.minecraft.server.v1_8_R3.EntityLiving; import net.minecraft.server.v1_8_R3.EntityZombie; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; import org.bukkit.inventory.ItemStack;
12,160
package com.sweattypalms.skyblock.slayers.zombie; public abstract class RevenantHorror extends EntityZombie implements ISkyblockMob, ISlayerMob { protected final SkyblockMob skyblockMob;
package com.sweattypalms.skyblock.slayers.zombie; public abstract class RevenantHorror extends EntityZombie implements ISkyblockMob, ISlayerMob { protected final SkyblockMob skyblockMob;
protected final SlayerTimer slayerTimer;
11
2023-11-15 15:05:58+00:00
16k
HanGyeolee/AndroidPdfWriter
android-pdf-writer/src/androidTest/java/com/hangyeolee/androidpdfwriter/PDFTableTest.java
[ { "identifier": "PDFGridLayout", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFGridLayout.java", "snippet": "public class PDFGridLayout extends PDFLayout{\n int rows, columns;\n\n ArrayList<Integer> span;\n\n final int[] gaps;\n final Rect childMargi...
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.hangyeolee.androidpdfwriter.components.PDFGridLayout; import com.hangyeolee.androidpdfwriter.components.PDFH1; import com.hangyeolee.androidpdfwriter.components.PDFH3; import com.hangyeolee.androidpdfwriter.components.PDFImage; import com.hangyeolee.androidpdfwriter.components.PDFLinearLayout; import com.hangyeolee.androidpdfwriter.utils.Anchor; import com.hangyeolee.androidpdfwriter.utils.DPI; import com.hangyeolee.androidpdfwriter.utils.Fit; import com.hangyeolee.androidpdfwriter.utils.Orientation; import com.hangyeolee.androidpdfwriter.utils.Paper; import com.hangyeolee.androidpdfwriter.utils.StandardDirectory; import com.hangyeolee.androidpdfwriter.utils.TextAlign; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.InputStream;
11,117
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFTableTest { Context context; PDFBuilder<PDFLinearLayout> builder; /** * The first page of the pdf file that is output by executing the code below is as follows: * com.hangyeolee.androidpdfwriter.test.R.drawable.pdftabletest_resultimage */ @Before public void setUp() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream stream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(com.hangyeolee.androidpdfwriter.test.R.drawable.test); Bitmap b = BitmapFactory.decodeStream(stream); builder = new PDFBuilder<>(Paper.A4); builder.setPagePadding(30, 30); { builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setBackgroundColor(Color.BLUE) .addChild(PDFImage.build(b) .setSize(null, 200f) .setFit(Fit.CONTAIN)) .addChild(PDFH1.build("제목") .setBackgroundColor(Color.RED)
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFTableTest { Context context; PDFBuilder<PDFLinearLayout> builder; /** * The first page of the pdf file that is output by executing the code below is as follows: * com.hangyeolee.androidpdfwriter.test.R.drawable.pdftabletest_resultimage */ @Before public void setUp() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream stream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(com.hangyeolee.androidpdfwriter.test.R.drawable.test); Bitmap b = BitmapFactory.decodeStream(stream); builder = new PDFBuilder<>(Paper.A4); builder.setPagePadding(30, 30); { builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setBackgroundColor(Color.BLUE) .addChild(PDFImage.build(b) .setSize(null, 200f) .setFit(Fit.CONTAIN)) .addChild(PDFH1.build("제목") .setBackgroundColor(Color.RED)
.setTextAlign(TextAlign.Center))
11
2023-11-15 08:05:28+00:00
16k
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;
12,577
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]
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);
0
2023-11-12 21:12:21+00:00
16k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/utils/data/packetentity/PacketEntity.java
[ { "identifier": "GrimPlayer", "path": "src/main/java/ac/grim/grimac/player/GrimPlayer.java", "snippet": "public class GrimPlayer {\n public final UUID playerUUID;\n public final int entityID;\n public final Player bukkitPlayer;\n // Determining player ping\n // The difference between keep...
import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.utils.collisions.datatypes.SimpleCollisionBox; import ac.grim.grimac.utils.data.ReachInterpolationData; import ac.grim.grimac.utils.enums.EntityType; import ac.grim.grimac.utils.nmsutil.GetBoundingBox; import io.github.retrooper.packetevents.utils.player.ClientVersion; import io.github.retrooper.packetevents.utils.vector.Vector3d; import java.util.Locale;
12,400
// This file was designed and is an original check for GrimAC // Copyright (C) 2021 DefineOutside // // 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 ac.grim.grimac.utils.data.packetentity; // You may not copy this check unless your anticheat is licensed under GPL public class PacketEntity { public Vector3d serverPos; public int lastTransactionHung; public EntityType type; public org.bukkit.entity.EntityType bukkitEntityType; public PacketEntity riding; public int[] passengers = new int[0]; public boolean isDead = false; public boolean isBaby = false; public boolean hasGravity = true; private ReachInterpolationData oldPacketLocation; private ReachInterpolationData newPacketLocation; public PacketEntity(GrimPlayer player, EntityType type, double x, double y, double z) { this.serverPos = new Vector3d(x, y, z); this.type = type; this.bukkitEntityType = org.bukkit.entity.EntityType.valueOf(type.toString().toUpperCase(Locale.ROOT)); this.newPacketLocation = new ReachInterpolationData(GetBoundingBox.getPacketEntityBoundingBox(x, y, z, this), serverPos.getX(), serverPos.getY(), serverPos.getZ(), player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_9)); } // Set the old packet location to the new one // Set the new packet location to the updated packet location public void onFirstTransaction(double x, double y, double z, GrimPlayer player) { this.oldPacketLocation = newPacketLocation; this.newPacketLocation = new ReachInterpolationData(oldPacketLocation.getPossibleLocationCombined(), x, y, z, player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_9)); } // Remove the possibility of the old packet location public void onSecondTransaction() { this.oldPacketLocation = null; } // If the old and new packet location are split, we need to combine bounding boxes public void onMovement() { newPacketLocation.tickMovement(oldPacketLocation == null); // Handle uncertainty of second transaction spanning over multiple ticks if (oldPacketLocation != null) { oldPacketLocation.tickMovement(true); newPacketLocation.updatePossibleStartingLocation(oldPacketLocation.getPossibleLocationCombined()); } } public boolean hasPassenger(int entityID) { for (int passenger : passengers) { if (passenger == entityID) return true; } return false; } // This is for handling riding and entities attached to one another.
// This file was designed and is an original check for GrimAC // Copyright (C) 2021 DefineOutside // // 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 ac.grim.grimac.utils.data.packetentity; // You may not copy this check unless your anticheat is licensed under GPL public class PacketEntity { public Vector3d serverPos; public int lastTransactionHung; public EntityType type; public org.bukkit.entity.EntityType bukkitEntityType; public PacketEntity riding; public int[] passengers = new int[0]; public boolean isDead = false; public boolean isBaby = false; public boolean hasGravity = true; private ReachInterpolationData oldPacketLocation; private ReachInterpolationData newPacketLocation; public PacketEntity(GrimPlayer player, EntityType type, double x, double y, double z) { this.serverPos = new Vector3d(x, y, z); this.type = type; this.bukkitEntityType = org.bukkit.entity.EntityType.valueOf(type.toString().toUpperCase(Locale.ROOT)); this.newPacketLocation = new ReachInterpolationData(GetBoundingBox.getPacketEntityBoundingBox(x, y, z, this), serverPos.getX(), serverPos.getY(), serverPos.getZ(), player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_9)); } // Set the old packet location to the new one // Set the new packet location to the updated packet location public void onFirstTransaction(double x, double y, double z, GrimPlayer player) { this.oldPacketLocation = newPacketLocation; this.newPacketLocation = new ReachInterpolationData(oldPacketLocation.getPossibleLocationCombined(), x, y, z, player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_9)); } // Remove the possibility of the old packet location public void onSecondTransaction() { this.oldPacketLocation = null; } // If the old and new packet location are split, we need to combine bounding boxes public void onMovement() { newPacketLocation.tickMovement(oldPacketLocation == null); // Handle uncertainty of second transaction spanning over multiple ticks if (oldPacketLocation != null) { oldPacketLocation.tickMovement(true); newPacketLocation.updatePossibleStartingLocation(oldPacketLocation.getPossibleLocationCombined()); } } public boolean hasPassenger(int entityID) { for (int passenger : passengers) { if (passenger == entityID) return true; } return false; } // This is for handling riding and entities attached to one another.
public void setPositionRaw(SimpleCollisionBox box) {
1
2023-11-11 05:14:12+00:00
16k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/activity/PersonalDataActivity.java
[ { "identifier": "AppActivity", "path": "app/src/main/java/com/buaa/food/app/AppActivity.java", "snippet": "public abstract class AppActivity extends BaseActivity\n implements ToastAction, TitleBarAction, OnHttpListener<Object> {\n\n /** 标题栏对象 */\n private TitleBar mTitleBar;\n /** 状态栏沉浸 ...
import android.net.Uri; import android.os.Build; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.buaa.food.http.glide.GlideApp; import com.bumptech.glide.load.MultiTransformation; import com.bumptech.glide.load.resource.bitmap.CenterCrop; import com.bumptech.glide.load.resource.bitmap.CircleCrop; import com.buaa.food.R; import com.buaa.food.aop.SingleClick; import com.buaa.food.app.AppActivity; import com.buaa.food.http.api.UpdateImageApi; import com.buaa.food.http.model.HttpData; import com.buaa.food.ui.dialog.AddressDialog; import com.buaa.food.ui.dialog.InputDialog; import com.hjq.http.EasyHttp; import com.hjq.http.listener.HttpCallback; import com.hjq.http.model.FileContentResolver; import com.hjq.widget.layout.SettingBar; import java.io.File; import java.net.URI; import java.net.URISyntaxException;
11,058
package com.buaa.food.ui.activity; public final class PersonalDataActivity extends AppActivity { private ViewGroup mAvatarLayout; private ImageView mAvatarView; private SettingBar mIdView; private SettingBar mNameView; private SettingBar mAddressView; /** 省 */ private String mProvince = "广东省"; /** 市 */ private String mCity = "广州市"; /** 区 */ private String mArea = "天河区"; /** 头像地址 */ private Uri mAvatarUrl; @Override protected int getLayoutId() { return R.layout.personal_data_activity; } @Override protected void initView() { mAvatarLayout = findViewById(R.id.fl_person_data_avatar); mAvatarView = findViewById(R.id.iv_person_data_avatar); mIdView = findViewById(R.id.sb_person_data_id); mNameView = findViewById(R.id.sb_person_data_name); setOnClickListener(mAvatarLayout, mAvatarView, mNameView, mAddressView); } @Override protected void initData() { GlideApp.with(getActivity()) .load(R.drawable.avatar_placeholder_ic) .placeholder(R.drawable.avatar_placeholder_ic) .error(R.drawable.avatar_placeholder_ic) .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop())) .into(mAvatarView); mIdView.setRightText("880634"); mNameView.setRightText("彭莘"); String address = mProvince + mCity + mArea; mAddressView.setRightText(address); } @SingleClick @Override public void onClick(View view) { if (view == mAvatarLayout) { ImageSelectActivity.start(this, data -> { // 裁剪头像 cropImageFile(new File(data.get(0))); }); } else if (view == mAvatarView) { if (mAvatarUrl != null) { // 查看头像 ImagePreviewActivity.start(getActivity(), mAvatarUrl.toString()); } else { // 选择头像 onClick(mAvatarLayout); } } else if (view == mNameView) { new InputDialog.Builder(this) // 标题可以不用填写 .setTitle(getString(R.string.personal_data_name_hint)) .setContent(mNameView.getRightText()) //.setHint(getString(R.string.personal_data_name_hint)) //.setConfirm("确定") // 设置 null 表示不显示取消按钮 //.setCancel("取消") // 设置点击按钮后不关闭对话框 //.setAutoDismiss(false) .setListener((dialog, content) -> { if (!mNameView.getRightText().equals(content)) { mNameView.setRightText(content); } }) .show(); } else if (view == mAddressView) {
package com.buaa.food.ui.activity; public final class PersonalDataActivity extends AppActivity { private ViewGroup mAvatarLayout; private ImageView mAvatarView; private SettingBar mIdView; private SettingBar mNameView; private SettingBar mAddressView; /** 省 */ private String mProvince = "广东省"; /** 市 */ private String mCity = "广州市"; /** 区 */ private String mArea = "天河区"; /** 头像地址 */ private Uri mAvatarUrl; @Override protected int getLayoutId() { return R.layout.personal_data_activity; } @Override protected void initView() { mAvatarLayout = findViewById(R.id.fl_person_data_avatar); mAvatarView = findViewById(R.id.iv_person_data_avatar); mIdView = findViewById(R.id.sb_person_data_id); mNameView = findViewById(R.id.sb_person_data_name); setOnClickListener(mAvatarLayout, mAvatarView, mNameView, mAddressView); } @Override protected void initData() { GlideApp.with(getActivity()) .load(R.drawable.avatar_placeholder_ic) .placeholder(R.drawable.avatar_placeholder_ic) .error(R.drawable.avatar_placeholder_ic) .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop())) .into(mAvatarView); mIdView.setRightText("880634"); mNameView.setRightText("彭莘"); String address = mProvince + mCity + mArea; mAddressView.setRightText(address); } @SingleClick @Override public void onClick(View view) { if (view == mAvatarLayout) { ImageSelectActivity.start(this, data -> { // 裁剪头像 cropImageFile(new File(data.get(0))); }); } else if (view == mAvatarView) { if (mAvatarUrl != null) { // 查看头像 ImagePreviewActivity.start(getActivity(), mAvatarUrl.toString()); } else { // 选择头像 onClick(mAvatarLayout); } } else if (view == mNameView) { new InputDialog.Builder(this) // 标题可以不用填写 .setTitle(getString(R.string.personal_data_name_hint)) .setContent(mNameView.getRightText()) //.setHint(getString(R.string.personal_data_name_hint)) //.setConfirm("确定") // 设置 null 表示不显示取消按钮 //.setCancel("取消") // 设置点击按钮后不关闭对话框 //.setAutoDismiss(false) .setListener((dialog, content) -> { if (!mNameView.getRightText().equals(content)) { mNameView.setRightText(content); } }) .show(); } else if (view == mAddressView) {
new AddressDialog.Builder(this)
3
2023-11-14 10:04:26+00:00
16k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/block/BlockModelRenderer.java
[ { "identifier": "DragonFly", "path": "src/main/java/useless/dragonfly/DragonFly.java", "snippet": "public class DragonFly implements GameStartEntrypoint {\n public static final String MOD_ID = \"dragonfly\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\tpublic static fi...
import net.minecraft.client.Minecraft; import net.minecraft.client.render.RenderBlockCache; import net.minecraft.client.render.RenderBlocks; import net.minecraft.client.render.Tessellator; import net.minecraft.client.render.block.color.BlockColorDispatcher; import net.minecraft.client.render.block.model.BlockModelRenderBlocks; import net.minecraft.core.block.Block; import net.minecraft.core.util.helper.Side; import net.minecraft.core.world.WorldSource; import org.lwjgl.opengl.GL11; import useless.dragonfly.DragonFly; import useless.dragonfly.mixins.mixin.accessor.RenderBlocksAccessor; import useless.dragonfly.model.block.data.PositionData; import useless.dragonfly.model.block.processed.BlockCube; import useless.dragonfly.model.block.processed.BlockFace; import useless.dragonfly.model.block.processed.BlockModel; import useless.dragonfly.utilities.vector.Vector3f; import java.awt.*; import java.lang.reflect.Field; import static useless.dragonfly.utilities.vector.Vector3f.origin;
10,932
float scale = 8f/3; xScale = (float) displayData.scale[2] * scale; yScale = (float) displayData.scale[1] * scale; zScale = (float) displayData.scale[0] * scale; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) -displayData.rotation[2] + 180; yRot = (float) displayData.rotation[1] + 45; zRot = (float) -displayData.rotation[0] - 100; break; case "gui": default: xScale = (float) displayData.scale[2] * 1.6f; yScale = (float) displayData.scale[1] * 1.6f; zScale = (float) displayData.scale[0] * 1.6f; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) displayData.rotation[0] - 30; yRot = (float) displayData.rotation[1] + 45; zRot = (float) displayData.rotation[2]; } Tessellator tessellator = Tessellator.instance; GL11.glEnable(GL11.GL_CULL_FACE); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glRotatef(yRot, 0, 1, 0); GL11.glRotatef(xRot, 1, 0, 0); GL11.glRotatef(zRot, 0, 0, 1); GL11.glTranslatef(-xOffset, -yOffset, -zOffset); GL11.glScalef(xScale, yScale, zScale); if (modelDragonFly.baseModel.blockCubes != null){ tessellator.startDrawingQuads(); GL11.glColor4f(brightness, brightness, brightness, 1); for (BlockCube cube: modelDragonFly.baseModel.blockCubes) { for (BlockFace face: cube.getFaces().values()) { tessellator.setNormal(face.getSide().getOffsetX(), face.getSide().getOffsetY(), face.getSide().getOffsetZ()); float r = 1; float g = 1; float b = 1; if (face.useTint()){ int color = BlockColorDispatcher.getInstance().getDispatch(block).getFallbackColor(meta); r = (float)(color >> 16 & 0xFF) / 255.0f; g = (float)(color >> 8 & 0xFF) / 255.0f; b = (float)(color & 0xFF) / 255.0f; } renderModelFaceWithColor(face, 0, 0, 0, r * brightness, g * brightness, b * brightness); } } tessellator.draw(); } GL11.glFrontFace(GL11.GL_CCW); // Deleting this breaks rendering for the whole world GL11.glDisable(GL11.GL_CULL_FACE); // Deleting this causes render issues on vanilla transparent blocks GL11.glTranslatef(xOffset, yOffset, zOffset); } public static boolean renderModelNormal(BlockModel model, Block block, int x, int y, int z, int rotationX, int rotationY) { BlockModelRenderer.rotationX = rotationX; BlockModelRenderer.rotationY = rotationY; if (rotationX % 90 != 0 || rotationY % 90 != 0) throw new IllegalArgumentException("Rotation must be a multiple of 90!!"); boolean didRender; if (mc.isAmbientOcclusionEnabled() && model.getAO()) { didRender = renderStandardModelWithAmbientOcclusion(model, block, x, y, z); } else { didRender = renderStandardModelWithColorMultiplier(model, block, x, y, z, 1, 1, 1); } BlockModelRenderer.rotationX = 0; BlockModelRenderer.rotationY = 0; return didRender; } public static boolean renderModelNoCulling(BlockModel model, Block block, int x, int y, int z, int rotationX, int rotationY) { renderAllFaces = true; boolean result = renderModelNormal(model, block, x, y, z, rotationX, rotationY); renderAllFaces = false; return result; } public static boolean renderModelBlockUsingTexture(BlockModel model, Block block, int x, int y, int z, int textureIndex, int rotationX, int rotationY) { overrideBlockTexture = textureIndex; boolean result = renderModelNormal(model, block, x, y, z, rotationX, rotationY); overrideBlockTexture = -1; return result; } public static boolean renderStandardModelWithAmbientOcclusion(BlockModel model, Block block, int x, int y, int z) { enableAO = true; rba().getCache().setupCache(block, rba().getBlockAccess(), x, y, z); boolean somethingRendered = false; for (BlockCube cube: model.blockCubes) { for (Side side: DragonFly.sides) { somethingRendered |= renderModelSide(model, cube, block, x, y, z, side); } } enableAO = false; return somethingRendered; } public static boolean renderModelSide(BlockModel model, BlockCube cube, Block block, int x, int y, int z, Side side) { BlockFace blockFace = cube.getFaceFromSide(side, rotationX, rotationY); if (blockFace == null) return false; if (!renderAllFaces){ if (!renderSide(model, cube, side, x, y, z)) return false; } RenderBlockCache cache = rba().getCache(); int sideOffX = side.getOffsetX(); int sideOffY = side.getOffsetY(); int sideOffZ = side.getOffsetZ();
package useless.dragonfly.model.block; public class BlockModelRenderer { public static Minecraft mc = Minecraft.getMinecraft(Minecraft.class); private static boolean enableAO = false; private static boolean renderAllFaces = false; private static float colorRedTopRight; private static float colorRedBottomRight; private static float colorRedBottomLeft; private static float colorGreenTopRight; private static float colorRedTopLeft; private static float colorGreenBottomRight; private static float colorGreenBottomLeft; private static float colorGreenTopLeft; private static float colorBlueTopRight; private static float colorBlueBottomRight; private static float colorBlueBottomLeft; private static float colorBlueTopLeft; private static int overrideBlockTexture = -1; private static int rotationX = 0; private static int rotationY = 0; public static void renderModelInventory(BlockModelDragonFly modelDragonFly, Block block, int meta, float brightness){ int off = (int) ((System.currentTimeMillis()/20) % 360); float xOffset; float yOffset; float zOffset; float xScale; float yScale; float zScale; float xRot; float yRot; float zRot; PositionData displayData = modelDragonFly.baseModel.getDisplayPosition(DragonFly.renderState); switch (DragonFly.renderState) { case "ground": xScale = (float) displayData.scale[2] * 4; yScale = (float) displayData.scale[1] * 4; zScale = (float) displayData.scale[0] * 4; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) displayData.rotation[0]; yRot = (float) displayData.rotation[1]; zRot = (float) displayData.rotation[2]; break; case "head": GL11.glFrontFace(GL11.GL_CW); xScale = (float) displayData.scale[0]; yScale = (float) displayData.scale[1]; zScale = (float) displayData.scale[2]; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[0] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[2] / 16f; xRot = (float) displayData.rotation[0]; yRot = (float) displayData.rotation[1] + 180; zRot = (float) displayData.rotation[2]; break; case "firstperson_righthand": xScale = (float) displayData.scale[2] * 2.5f; yScale = (float) displayData.scale[1] * 2.5f; zScale = (float) displayData.scale[0] * 2.5f; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 8f; yOffset -= (float) displayData.translation[1] / 8f; zOffset -= (float) displayData.translation[0] / 8f; xRot = (float) displayData.rotation[0]; yRot = (float) displayData.rotation[1] + 45; zRot = (float) displayData.rotation[2]; break; case "thirdperson_righthand": GL11.glFrontFace(GL11.GL_CW); float scale = 8f/3; xScale = (float) displayData.scale[2] * scale; yScale = (float) displayData.scale[1] * scale; zScale = (float) displayData.scale[0] * scale; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) -displayData.rotation[2] + 180; yRot = (float) displayData.rotation[1] + 45; zRot = (float) -displayData.rotation[0] - 100; break; case "gui": default: xScale = (float) displayData.scale[2] * 1.6f; yScale = (float) displayData.scale[1] * 1.6f; zScale = (float) displayData.scale[0] * 1.6f; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) displayData.rotation[0] - 30; yRot = (float) displayData.rotation[1] + 45; zRot = (float) displayData.rotation[2]; } Tessellator tessellator = Tessellator.instance; GL11.glEnable(GL11.GL_CULL_FACE); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glRotatef(yRot, 0, 1, 0); GL11.glRotatef(xRot, 1, 0, 0); GL11.glRotatef(zRot, 0, 0, 1); GL11.glTranslatef(-xOffset, -yOffset, -zOffset); GL11.glScalef(xScale, yScale, zScale); if (modelDragonFly.baseModel.blockCubes != null){ tessellator.startDrawingQuads(); GL11.glColor4f(brightness, brightness, brightness, 1); for (BlockCube cube: modelDragonFly.baseModel.blockCubes) { for (BlockFace face: cube.getFaces().values()) { tessellator.setNormal(face.getSide().getOffsetX(), face.getSide().getOffsetY(), face.getSide().getOffsetZ()); float r = 1; float g = 1; float b = 1; if (face.useTint()){ int color = BlockColorDispatcher.getInstance().getDispatch(block).getFallbackColor(meta); r = (float)(color >> 16 & 0xFF) / 255.0f; g = (float)(color >> 8 & 0xFF) / 255.0f; b = (float)(color & 0xFF) / 255.0f; } renderModelFaceWithColor(face, 0, 0, 0, r * brightness, g * brightness, b * brightness); } } tessellator.draw(); } GL11.glFrontFace(GL11.GL_CCW); // Deleting this breaks rendering for the whole world GL11.glDisable(GL11.GL_CULL_FACE); // Deleting this causes render issues on vanilla transparent blocks GL11.glTranslatef(xOffset, yOffset, zOffset); } public static boolean renderModelNormal(BlockModel model, Block block, int x, int y, int z, int rotationX, int rotationY) { BlockModelRenderer.rotationX = rotationX; BlockModelRenderer.rotationY = rotationY; if (rotationX % 90 != 0 || rotationY % 90 != 0) throw new IllegalArgumentException("Rotation must be a multiple of 90!!"); boolean didRender; if (mc.isAmbientOcclusionEnabled() && model.getAO()) { didRender = renderStandardModelWithAmbientOcclusion(model, block, x, y, z); } else { didRender = renderStandardModelWithColorMultiplier(model, block, x, y, z, 1, 1, 1); } BlockModelRenderer.rotationX = 0; BlockModelRenderer.rotationY = 0; return didRender; } public static boolean renderModelNoCulling(BlockModel model, Block block, int x, int y, int z, int rotationX, int rotationY) { renderAllFaces = true; boolean result = renderModelNormal(model, block, x, y, z, rotationX, rotationY); renderAllFaces = false; return result; } public static boolean renderModelBlockUsingTexture(BlockModel model, Block block, int x, int y, int z, int textureIndex, int rotationX, int rotationY) { overrideBlockTexture = textureIndex; boolean result = renderModelNormal(model, block, x, y, z, rotationX, rotationY); overrideBlockTexture = -1; return result; } public static boolean renderStandardModelWithAmbientOcclusion(BlockModel model, Block block, int x, int y, int z) { enableAO = true; rba().getCache().setupCache(block, rba().getBlockAccess(), x, y, z); boolean somethingRendered = false; for (BlockCube cube: model.blockCubes) { for (Side side: DragonFly.sides) { somethingRendered |= renderModelSide(model, cube, block, x, y, z, side); } } enableAO = false; return somethingRendered; } public static boolean renderModelSide(BlockModel model, BlockCube cube, Block block, int x, int y, int z, Side side) { BlockFace blockFace = cube.getFaceFromSide(side, rotationX, rotationY); if (blockFace == null) return false; if (!renderAllFaces){ if (!renderSide(model, cube, side, x, y, z)) return false; } RenderBlockCache cache = rba().getCache(); int sideOffX = side.getOffsetX(); int sideOffY = side.getOffsetY(); int sideOffZ = side.getOffsetZ();
Vector3f vMin = cube.getMin().rotateAroundX(origin, rotationX).rotateAroundY(origin, rotationY);
6
2023-11-16 01:10:52+00:00
16k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/config/captcha/service/impl/CaptchaServiceImpl.java
[ { "identifier": "CaptchaCondition", "path": "src/main/java/top/sharehome/springbootinittemplate/config/captcha/condition/CaptchaCondition.java", "snippet": "public class CaptchaCondition implements Condition {\n\n @Override\n public boolean matches(ConditionContext context, AnnotatedTypeMetadata m...
import cn.hutool.captcha.AbstractCaptcha; import cn.hutool.captcha.generator.CodeGenerator; import cn.hutool.core.util.ReflectUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Conditional; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.stereotype.Service; import top.sharehome.springbootinittemplate.config.captcha.condition.CaptchaCondition; import top.sharehome.springbootinittemplate.config.captcha.model.CaptchaCreate; import top.sharehome.springbootinittemplate.config.captcha.properties.CaptchaProperties; import top.sharehome.springbootinittemplate.config.captcha.properties.enums.CaptchaType; import top.sharehome.springbootinittemplate.config.captcha.service.CaptchaService; import top.sharehome.springbootinittemplate.common.base.ReturnCode; import top.sharehome.springbootinittemplate.config.bean.SpringContextHolder; import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException; import top.sharehome.springbootinittemplate.utils.redisson.cache.CacheUtils; import top.sharehome.springbootinittemplate.utils.redisson.KeyPrefixConstants; import javax.annotation.Resource; import java.util.UUID;
13,938
package top.sharehome.springbootinittemplate.config.captcha.service.impl; /** * 验证码服务实现类 * * @author AntonyCheng */ @EnableConfigurationProperties(CaptchaProperties.class) @Service @Conditional(CaptchaCondition.class) public class CaptchaServiceImpl implements CaptchaService { @Resource private CaptchaProperties captchaProperties; @Override public CaptchaCreate createCaptcha() { CaptchaCreate captchaCreateResponse = new CaptchaCreate(); boolean enable = captchaProperties.getEnable(); captchaCreateResponse.setEnableCode(enable); if (!enable) { return captchaCreateResponse; } String uuid = UUID.randomUUID().toString().replace("-", "");
package top.sharehome.springbootinittemplate.config.captcha.service.impl; /** * 验证码服务实现类 * * @author AntonyCheng */ @EnableConfigurationProperties(CaptchaProperties.class) @Service @Conditional(CaptchaCondition.class) public class CaptchaServiceImpl implements CaptchaService { @Resource private CaptchaProperties captchaProperties; @Override public CaptchaCreate createCaptcha() { CaptchaCreate captchaCreateResponse = new CaptchaCreate(); boolean enable = captchaProperties.getEnable(); captchaCreateResponse.setEnableCode(enable); if (!enable) { return captchaCreateResponse; } String uuid = UUID.randomUUID().toString().replace("-", "");
String codeKeyInRedis = KeyPrefixConstants.CAPTCHA_PREFIX + uuid;
9
2023-11-12 07:49:59+00:00
16k
Shushandr/offroad
src/net/osmand/router/PrecalculatedRouteDirection.java
[ { "identifier": "RouteDataObject", "path": "src/net/osmand/binary/RouteDataObject.java", "snippet": "public class RouteDataObject {\n\t/*private */static final int RESTRICTION_SHIFT = 3;\n\t/*private */static final int RESTRICTION_MASK = 7;\n\t\n\tpublic final RouteRegion region;\n\t// all these arrays ...
import gnu.trove.list.array.TIntArrayList; import java.util.ArrayList; import java.util.List; import net.osmand.binary.RouteDataObject; import net.osmand.data.LatLon; import net.osmand.data.QuadPoint; import net.osmand.data.QuadRect; import net.osmand.data.QuadTree; import net.osmand.util.MapUtils;
12,348
package net.osmand.router; public class PrecalculatedRouteDirection { private int[] pointsX; private int[] pointsY; private float minSpeed; private float maxSpeed; private float[] tms; private boolean followNext; private static final int SHIFT = (1 << (31 - 17)); private static final int[] SHIFTS = new int[]{1 << (31 - 15), 1 << (31 - 13), 1 << (31 - 12), 1 << (31 - 11), 1 << (31 - 7)}; private List<Integer> cachedS = new ArrayList<Integer>(); private long startPoint = 0; private long endPoint = 0; // private DataTileManager<Integer> indexedPoints = new DataTileManager<Integer>(17); QuadTree<Integer> quadTree = new QuadTree<Integer>(new QuadRect(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE), 8, 0.55f); private float startFinishTime; private float endFinishTime; public PrecalculatedRouteDirection(TIntArrayList px, TIntArrayList py, List<Float> speedSegments, float maxSpeed) { this.maxSpeed = maxSpeed; init(px, py, speedSegments); } private PrecalculatedRouteDirection(List<RouteSegmentResult> ls, float maxSpeed) { this.maxSpeed = maxSpeed; init(ls); }
package net.osmand.router; public class PrecalculatedRouteDirection { private int[] pointsX; private int[] pointsY; private float minSpeed; private float maxSpeed; private float[] tms; private boolean followNext; private static final int SHIFT = (1 << (31 - 17)); private static final int[] SHIFTS = new int[]{1 << (31 - 15), 1 << (31 - 13), 1 << (31 - 12), 1 << (31 - 11), 1 << (31 - 7)}; private List<Integer> cachedS = new ArrayList<Integer>(); private long startPoint = 0; private long endPoint = 0; // private DataTileManager<Integer> indexedPoints = new DataTileManager<Integer>(17); QuadTree<Integer> quadTree = new QuadTree<Integer>(new QuadRect(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE), 8, 0.55f); private float startFinishTime; private float endFinishTime; public PrecalculatedRouteDirection(TIntArrayList px, TIntArrayList py, List<Float> speedSegments, float maxSpeed) { this.maxSpeed = maxSpeed; init(px, py, speedSegments); } private PrecalculatedRouteDirection(List<RouteSegmentResult> ls, float maxSpeed) { this.maxSpeed = maxSpeed; init(ls); }
private PrecalculatedRouteDirection(LatLon[] ls, float maxSpeed) {
1
2023-11-15 05:04:55+00:00
16k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/service/impl/HrmEmployeeAchievementFileServiceImpl.java
[ { "identifier": "BasePage", "path": "common/common-web/src/main/java/com/kakarote/core/entity/BasePage.java", "snippet": "public class BasePage<T> implements IPage<T> {\n\n private static final long serialVersionUID = 8545996863226528798L;\n\n /**\n * 查询数据列表\n */\n private List<T> list;...
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.ObjectUtil; import com.kakarote.core.entity.BasePage; import com.kakarote.core.exception.CrmException; import com.kakarote.core.servlet.BaseServiceImpl; import com.kakarote.hrm.common.HrmCodeEnum; import com.kakarote.hrm.constant.MenuIdConstant; import com.kakarote.hrm.entity.BO.QueryCoefficientBO; import com.kakarote.hrm.entity.BO.QueryEmployeeAchievementFileBO; import com.kakarote.hrm.entity.DTO.EmployeeAchievementFileReq; import com.kakarote.hrm.entity.DTO.OperationReq; import com.kakarote.hrm.entity.PO.HrmAppraisalEmployee; import com.kakarote.hrm.entity.PO.HrmAppraisalPlanResultSetting; import com.kakarote.hrm.entity.PO.HrmEmployeeAchievementFile; import com.kakarote.hrm.entity.VO.EmployeeAchievementFileVO; import com.kakarote.hrm.mapper.HrmEmployeeAchievementFileMapper; import com.kakarote.hrm.service.IHrmAppraisalEmployeeService; import com.kakarote.hrm.service.IHrmAppraisalPlanResultSettingService; import com.kakarote.hrm.service.IHrmEmployeeAchievementFileService; import com.kakarote.hrm.utils.EmployeeUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.stream.Collectors;
13,945
package com.kakarote.hrm.service.impl; /** * <p> * 员工绩效档案 服务实现类 * </p> * * @author zyl * @since 2022-06-14 */ @Service public class HrmEmployeeAchievementFileServiceImpl extends BaseServiceImpl<HrmEmployeeAchievementFileMapper, HrmEmployeeAchievementFile> implements IHrmEmployeeAchievementFileService { @Autowired private EmployeeUtil employeeUtil; @Autowired private IHrmAppraisalPlanResultSettingService appraisalPlanResultSettingService; @Autowired private IHrmAppraisalEmployeeService appraisalEmployeeService; @Override public BasePage<EmployeeAchievementFileVO> queryEmployeeAchievementFileList(QueryEmployeeAchievementFileBO employeeAchievementFileBO) { Collection<Long> employeeIds = employeeUtil.queryDataAuthEmpIdByMenuId(MenuIdConstant.ACHIEVEMENT_FILE_MENU_ID); return baseMapper.queryEmployeeAchievementFileList(employeeAchievementFileBO.parse(), employeeAchievementFileBO, employeeIds); } @Override public void addOrUpdate(Long appraisalEmployeeId, Long employeeId) { HrmEmployeeAchievementFile employeeAchievementFile = lambdaQuery().eq(HrmEmployeeAchievementFile::getEmployeeId, employeeId).one(); if (ObjectUtil.isNotNull(employeeAchievementFile)) { lambdaUpdate().set(HrmEmployeeAchievementFile::getUpdateTime, new Date()).set(HrmEmployeeAchievementFile::getAppraisalCount, employeeAchievementFile.getAppraisalCount() + 1).set(HrmEmployeeAchievementFile::getRecentlyAppraisalEmployeeId, appraisalEmployeeId).eq(HrmEmployeeAchievementFile::getEmployeeId, employeeId).update(); } else { HrmEmployeeAchievementFile achievementFile = new HrmEmployeeAchievementFile(); achievementFile.setCreateTime(new Date()); achievementFile.setEmployeeId(employeeId); achievementFile.setAppraisalCount(1); achievementFile.setRecentlyAppraisalEmployeeId(appraisalEmployeeId); save(achievementFile); } } @Override public Map<Long, Double> queryCoefficient(QueryCoefficientBO queryCoefficientBO) { Map<Long, Double> employeeCoefficient = new HashMap<>(); StringBuffer paidForMonth = new StringBuffer(); paidForMonth.append(queryCoefficientBO.getYear()); paidForMonth.append("-"); if (queryCoefficientBO.getMonth() < 10) { paidForMonth.append("0"); } paidForMonth.append(queryCoefficientBO.getMonth()); if (CollectionUtil.isNotEmpty(queryCoefficientBO.getEmployeeIdList())) { queryCoefficientBO.getEmployeeIdList().stream().forEach( employeeId -> { HrmAppraisalEmployee appraisalEmployee = baseMapper.queryRecentlyAppraisal(employeeId, paidForMonth.toString()); if (ObjectUtil.isNotNull(appraisalEmployee)) { HrmAppraisalPlanResultSetting resultSetting = appraisalPlanResultSettingService.lambdaQuery().eq(HrmAppraisalPlanResultSetting::getAppraisalPlanId, appraisalEmployee.getAppraisalPlanId()).eq(HrmAppraisalPlanResultSetting::getLevelName, appraisalEmployee.getLevel()).one(); employeeCoefficient.put(employeeId, resultSetting.getCoefficient()); } } ); } return employeeCoefficient; } @Transactional @Override public void delAppraisalFileRecordList(EmployeeAchievementFileReq operationReq) { Optional<HrmEmployeeAchievementFile> achievementFile = lambdaQuery().eq(HrmEmployeeAchievementFile::getEmployeeId, operationReq.getEmployeeId()).oneOpt(); if (achievementFile.isPresent()) { Integer delCount = appraisalEmployeeService.deleteAppraisalEmployeeById(operationReq.getIds()); Integer curCount = achievementFile.get().getAppraisalCount(); Integer count = curCount - delCount; Optional<HrmAppraisalEmployee> recentlyAppraisalEmployee = appraisalEmployeeService.lambdaQuery().eq(HrmAppraisalEmployee::getEmployeeId, operationReq.getEmployeeId()).orderByDesc(HrmAppraisalEmployee::getCreateTime).last("limit 1").oneOpt(); if (recentlyAppraisalEmployee.isPresent()) { lambdaUpdate().set(HrmEmployeeAchievementFile::getRecentlyAppraisalEmployeeId, recentlyAppraisalEmployee.get().getAppraisalEmployeeId()).set(HrmEmployeeAchievementFile::getAppraisalCount, count).set(HrmEmployeeAchievementFile::getUpdateTime, new Date()).eq(HrmEmployeeAchievementFile::getEmployeeId, operationReq.getEmployeeId()).update(); } else { lambdaUpdate().eq(HrmEmployeeAchievementFile::getEmployeeId, operationReq.getEmployeeId()).remove(); } } } @Transactional @Override public void delAppraisalFileRecordListOfAll(OperationReq operationReq) { List<HrmEmployeeAchievementFile> employeeAchievementFileList = lambdaQuery().in(HrmEmployeeAchievementFile::getAchievementFileId, operationReq.getIds()).list(); if (CollectionUtil.isEmpty(employeeAchievementFileList)) {
package com.kakarote.hrm.service.impl; /** * <p> * 员工绩效档案 服务实现类 * </p> * * @author zyl * @since 2022-06-14 */ @Service public class HrmEmployeeAchievementFileServiceImpl extends BaseServiceImpl<HrmEmployeeAchievementFileMapper, HrmEmployeeAchievementFile> implements IHrmEmployeeAchievementFileService { @Autowired private EmployeeUtil employeeUtil; @Autowired private IHrmAppraisalPlanResultSettingService appraisalPlanResultSettingService; @Autowired private IHrmAppraisalEmployeeService appraisalEmployeeService; @Override public BasePage<EmployeeAchievementFileVO> queryEmployeeAchievementFileList(QueryEmployeeAchievementFileBO employeeAchievementFileBO) { Collection<Long> employeeIds = employeeUtil.queryDataAuthEmpIdByMenuId(MenuIdConstant.ACHIEVEMENT_FILE_MENU_ID); return baseMapper.queryEmployeeAchievementFileList(employeeAchievementFileBO.parse(), employeeAchievementFileBO, employeeIds); } @Override public void addOrUpdate(Long appraisalEmployeeId, Long employeeId) { HrmEmployeeAchievementFile employeeAchievementFile = lambdaQuery().eq(HrmEmployeeAchievementFile::getEmployeeId, employeeId).one(); if (ObjectUtil.isNotNull(employeeAchievementFile)) { lambdaUpdate().set(HrmEmployeeAchievementFile::getUpdateTime, new Date()).set(HrmEmployeeAchievementFile::getAppraisalCount, employeeAchievementFile.getAppraisalCount() + 1).set(HrmEmployeeAchievementFile::getRecentlyAppraisalEmployeeId, appraisalEmployeeId).eq(HrmEmployeeAchievementFile::getEmployeeId, employeeId).update(); } else { HrmEmployeeAchievementFile achievementFile = new HrmEmployeeAchievementFile(); achievementFile.setCreateTime(new Date()); achievementFile.setEmployeeId(employeeId); achievementFile.setAppraisalCount(1); achievementFile.setRecentlyAppraisalEmployeeId(appraisalEmployeeId); save(achievementFile); } } @Override public Map<Long, Double> queryCoefficient(QueryCoefficientBO queryCoefficientBO) { Map<Long, Double> employeeCoefficient = new HashMap<>(); StringBuffer paidForMonth = new StringBuffer(); paidForMonth.append(queryCoefficientBO.getYear()); paidForMonth.append("-"); if (queryCoefficientBO.getMonth() < 10) { paidForMonth.append("0"); } paidForMonth.append(queryCoefficientBO.getMonth()); if (CollectionUtil.isNotEmpty(queryCoefficientBO.getEmployeeIdList())) { queryCoefficientBO.getEmployeeIdList().stream().forEach( employeeId -> { HrmAppraisalEmployee appraisalEmployee = baseMapper.queryRecentlyAppraisal(employeeId, paidForMonth.toString()); if (ObjectUtil.isNotNull(appraisalEmployee)) { HrmAppraisalPlanResultSetting resultSetting = appraisalPlanResultSettingService.lambdaQuery().eq(HrmAppraisalPlanResultSetting::getAppraisalPlanId, appraisalEmployee.getAppraisalPlanId()).eq(HrmAppraisalPlanResultSetting::getLevelName, appraisalEmployee.getLevel()).one(); employeeCoefficient.put(employeeId, resultSetting.getCoefficient()); } } ); } return employeeCoefficient; } @Transactional @Override public void delAppraisalFileRecordList(EmployeeAchievementFileReq operationReq) { Optional<HrmEmployeeAchievementFile> achievementFile = lambdaQuery().eq(HrmEmployeeAchievementFile::getEmployeeId, operationReq.getEmployeeId()).oneOpt(); if (achievementFile.isPresent()) { Integer delCount = appraisalEmployeeService.deleteAppraisalEmployeeById(operationReq.getIds()); Integer curCount = achievementFile.get().getAppraisalCount(); Integer count = curCount - delCount; Optional<HrmAppraisalEmployee> recentlyAppraisalEmployee = appraisalEmployeeService.lambdaQuery().eq(HrmAppraisalEmployee::getEmployeeId, operationReq.getEmployeeId()).orderByDesc(HrmAppraisalEmployee::getCreateTime).last("limit 1").oneOpt(); if (recentlyAppraisalEmployee.isPresent()) { lambdaUpdate().set(HrmEmployeeAchievementFile::getRecentlyAppraisalEmployeeId, recentlyAppraisalEmployee.get().getAppraisalEmployeeId()).set(HrmEmployeeAchievementFile::getAppraisalCount, count).set(HrmEmployeeAchievementFile::getUpdateTime, new Date()).eq(HrmEmployeeAchievementFile::getEmployeeId, operationReq.getEmployeeId()).update(); } else { lambdaUpdate().eq(HrmEmployeeAchievementFile::getEmployeeId, operationReq.getEmployeeId()).remove(); } } } @Transactional @Override public void delAppraisalFileRecordListOfAll(OperationReq operationReq) { List<HrmEmployeeAchievementFile> employeeAchievementFileList = lambdaQuery().in(HrmEmployeeAchievementFile::getAchievementFileId, operationReq.getIds()).list(); if (CollectionUtil.isEmpty(employeeAchievementFileList)) {
throw new CrmException(HrmCodeEnum.RESULT_NULL_ERROR);
3
2023-10-17 05:49:52+00:00
16k
djkcyl/Shamrock
qqinterface/src/main/java/com/tencent/mobileqq/profilecard/processor/AbsProfileBusinessProcessor.java
[ { "identifier": "Card", "path": "qqinterface/src/main/java/com/tencent/mobileqq/data/Card.java", "snippet": "public class Card {\n public static final long BIRTHDAY_INVALID = 0;\n public static final int CONSTELLATION_INVALID = 0;\n public static final short FEMALE = 1;\n public static final...
import android.os.Bundle; import android.util.SparseArray; import com.tencent.mobileqq.data.Card; import com.tencent.mobileqq.profilecard.entity.BusinessReqBuffer; import com.tencent.mobileqq.profilecard.entity.BusinessRespBuffer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import SummaryCard.RespHead; import SummaryCard.RespSummaryCard; import mqq.app.AppRuntime; import tencent.im.oidb.cmd0x5eb.oidb_0x5eb;
12,251
package com.tencent.mobileqq.profilecard.processor; public abstract class AbsProfileBusinessProcessor implements IRequestProfileCardCallback, IGetProfileDetailCallback { public AbsProfileBusinessProcessor(AppRuntime appRuntime) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailRequestForLogin(List<Short> list) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseBegin(Bundle bundle) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseEnd(Bundle bundle, boolean z, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLV(Bundle bundle, long j2, Card card, short s, short s2, ByteBuffer byteBuffer) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVBegin(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVEnd(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback
package com.tencent.mobileqq.profilecard.processor; public abstract class AbsProfileBusinessProcessor implements IRequestProfileCardCallback, IGetProfileDetailCallback { public AbsProfileBusinessProcessor(AppRuntime appRuntime) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailRequestForLogin(List<Short> list) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseBegin(Bundle bundle) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseEnd(Bundle bundle, boolean z, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLV(Bundle bundle, long j2, Card card, short s, short s2, ByteBuffer byteBuffer) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVBegin(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVEnd(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback
public void onProcessProfile0x5eb(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, oidb_0x5eb.UdcUinData oidb_0x5eb_udcuindata) {
6
2023-10-20 10:43:47+00:00
16k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/system/OreProcess/logic/OP_NormalProcessing.java
[ { "identifier": "OreProcessRecipeDuration", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/system/OreProcess/logic/OP_Values.java", "snippet": "public static final int OreProcessRecipeDuration = 128;" }, { "identifier": "OreProcessRecipeEUt", "path": "src/main/java/com/Nxer/TwistSpaceT...
import static com.Nxer.TwistSpaceTechnology.system.OreProcess.logic.OP_Values.OreProcessRecipeDuration; import static com.Nxer.TwistSpaceTechnology.system.OreProcess.logic.OP_Values.OreProcessRecipeEUt; import static com.Nxer.TwistSpaceTechnology.system.OreProcess.logic.OP_Values.SpecialProcessingLineMaterialInstead; import static com.Nxer.TwistSpaceTechnology.util.Utils.copyAmount; import static com.Nxer.TwistSpaceTechnology.util.Utils.setStackSize; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import net.minecraft.item.ItemStack; import com.Nxer.TwistSpaceTechnology.TwistSpaceTechnology; import com.Nxer.TwistSpaceTechnology.common.recipeMap.GTCMRecipe; import com.Nxer.TwistSpaceTechnology.util.Utils; import com.elisis.gtnhlanth.common.register.WerkstoffMaterialPool; import com.github.bartimaeusnek.bartworks.system.material.WerkstoffLoader; import com.google.common.collect.Sets; import goodgenerator.items.MyMaterial; import gregtech.api.GregTech_API; import gregtech.api.enums.GT_Values; import gregtech.api.enums.Materials; import gregtech.api.enums.OrePrefixes; import gregtech.api.util.GT_ModHandler; import gregtech.api.util.GT_OreDictUnificator; import ic2.core.Ic2Items;
12,436
true ); // Ardite ore processOreRecipe( GT_ModHandler.getModItem("TConstruct","SearedBrick", 1, 2), Materials.Ardite, true ); // IC2 Uranium ore processOreRecipe( copyAmount(1,Ic2Items.uraniumOre), Materials.Uranium, false ); // HEE end powder registryOreProcessRecipe( GT_ModHandler.getModItem("HardcoreEnderExpansion","end_powder_ore",1), new ItemStack[]{GT_ModHandler.getModItem("HardcoreEnderExpansion", "end_powder", 24)} ); // spotless:on } /** * Generate normal ore recipes * * @param material The ore's Material. * @param ID The material ID. */ public void processOreRecipe(Materials material, int ID) { if (GT_OreDictUnificator.get(OrePrefixes.ore, material, 1) == null) return; ItemStack[] outputs = getOutputs(material, false); ItemStack[] outputsRich = getOutputs(material, true); // registry normal stone ore registryOreProcessRecipe(GT_ModHandler.getModItem("gregtech", "gt.blockores", 1, ID), outputs); // registry gt stone ore for (OrePrefixes prefixes : basicStoneTypesExceptNormalStone) { if (GT_OreDictUnificator.get(prefixes, material, 1) == null) { TwistSpaceTechnology.LOG.info("Failed to get ore: material=" + material + " , prefixes=" + prefixes); continue; } registryOreProcessRecipe( GT_OreDictUnificator.get(prefixes, material, 1), isRich(prefixes) ? outputsRich : outputs); } } /** * Process other mods' ore but normal style. * * @param inputOreItems Input ore item stack. * @param material Input ore's material in GT design. * @param isRich Is this ore a rich type. */ public void processOreRecipe(ItemStack inputOreItems, Materials material, boolean isRich) { registryOreProcessRecipe(inputOreItems, getOutputs(material, isRich)); } public ItemStack[] getOutputs(Materials material, boolean isRich) { List<ItemStack> outputs = new ArrayList<>(); // check byproduct if (!material.mOreByProducts.isEmpty()) { // the basic output the material outputs.add(getDustStack(material, 4)); if (material.mOreByProducts.size() == 1) { for (Materials byproduct : material.mOreByProducts) { if (byproduct == null) continue; outputs.add(getDustStack(byproduct, 3)); } } else { for (Materials byproduct : material.mOreByProducts) { if (byproduct == null || byproduct == Materials.Netherrack || byproduct == Materials.Endstone || byproduct == Materials.Stone) continue; outputs.add(getDustStack(byproduct, 2)); } } } else { outputs.add(getDustStack(material, 8)); } // check gem style if (GT_OreDictUnificator.get(OrePrefixes.gem, material, 1) != null) { if (GT_OreDictUnificator.get(OrePrefixes.gemExquisite, material, 1) != null) { // has gem style outputs.add(GT_OreDictUnificator.get(OrePrefixes.gemExquisite, material, 1)); outputs.add(GT_OreDictUnificator.get(OrePrefixes.gemFlawless, material, 2)); outputs.add(GT_OreDictUnificator.get(OrePrefixes.gem, material, 2)); } else { // just normal gem outputs.add(GT_OreDictUnificator.get(OrePrefixes.gem, material, 4)); } } if (isRich) { for (ItemStack out : outputs) { out.stackSize *= 2; } } return outputs.toArray(new ItemStack[0]); } public void registryOreProcessRecipe(ItemStack input, ItemStack[] output) { GT_Values.RA.stdBuilder() .itemInputs(input) .itemOutputs(output) .fluidInputs(Materials.Lubricant.getFluid(1)) .noOptimize() .eut(OreProcessRecipeEUt) .duration(OreProcessRecipeDuration)
package com.Nxer.TwistSpaceTechnology.system.OreProcess.logic; public class OP_NormalProcessing { /** * Ore stone types enum */ public final Set<OrePrefixes> basicStoneTypes = Sets.newHashSet( OrePrefixes.ore, OrePrefixes.oreBasalt, OrePrefixes.oreBlackgranite, OrePrefixes.oreRedgranite, OrePrefixes.oreMarble, OrePrefixes.oreNetherrack, OrePrefixes.oreEndstone); public final Set<OrePrefixes> basicStoneTypesExceptNormalStone = Sets.newHashSet( OrePrefixes.oreBasalt, OrePrefixes.oreBlackgranite, OrePrefixes.oreRedgranite, OrePrefixes.oreMarble, OrePrefixes.oreNetherrack, OrePrefixes.oreEndstone); public final Map<Materials, ItemStack> processingLineMaterials = new HashMap<>(); public void initProcessingLineMaterials() { processingLineMaterials.put(Materials.Platinum, WerkstoffLoader.PTMetallicPowder.get(OrePrefixes.dust, 1)); processingLineMaterials.put(Materials.Palladium, WerkstoffLoader.PDMetallicPowder.get(OrePrefixes.dust, 1)); processingLineMaterials.put(Materials.Iridium, WerkstoffLoader.IrLeachResidue.get(OrePrefixes.dust, 1)); processingLineMaterials.put(Materials.Osmium, WerkstoffLoader.IrOsLeachResidue.get(OrePrefixes.dust, 1)); processingLineMaterials .put(Materials.Samarium, WerkstoffMaterialPool.SamariumOreConcentrate.get(OrePrefixes.dust, 1)); processingLineMaterials .put(Materials.Cerium, WerkstoffMaterialPool.CeriumOreConcentrate.get(OrePrefixes.dust, 1)); } // public final List<Integer> insteadMaterialOresMetas = Arrays.asList( // 19, 20, 28, 32, 33, 35, 57, 86, 89, 98, 347, 382, 500, 501, 514, 522, 526, 530, // 535, 540, 541, 542, 543, 544, 545, 770, 810, 817, 826, 884, 894, 918, 920 // ); public ItemStack getDustStack(Materials material, int amount) { if (SpecialProcessingLineMaterialInstead) { ItemStack t = processingLineMaterials.get(material); if (t != null) { return Utils.copyAmount(amount * 3, t); } } return setStackSize(GT_OreDictUnificator.get(OrePrefixes.dust, material, 1), amount); } /** * Generate recipes. */ public void enumOreProcessingRecipes() { initProcessingLineMaterials(); Set<Materials> specialProcesses = Sets.newHashSet( Materials.Samarium, Materials.Cerium, Materials.Naquadah, Materials.NaquadahEnriched, Materials.Naquadria); // generate normal materials' ore processing recipes for (int i = 0; i < GregTech_API.sGeneratedMaterials.length; i++) { if (GregTech_API.sGeneratedMaterials[i] == null) continue; Materials material = GregTech_API.sGeneratedMaterials[i]; // rule out special materials if (!specialProcesses.isEmpty() && specialProcesses.contains(material)) { specialProcesses.remove(material); continue; } // generate recipes processOreRecipe(material, i); } processSpecialOreRecipe(); new OP_GTPP_OreHandler().processGTPPOreRecipes(); new OP_Bartworks_OreHandler().processBWOreRecipes(); } /** * Generate special ores recipes */ public void processSpecialOreRecipe() { // spotless:off // Cerium ore { ItemStack[] outputs = new ItemStack[] { WerkstoffMaterialPool.CeriumOreConcentrate.get(OrePrefixes.dust, 11) }; ItemStack[] outputsRich = new ItemStack[] { WerkstoffMaterialPool.CeriumOreConcentrate.get(OrePrefixes.dust, 22) }; for (OrePrefixes prefixes : basicStoneTypes) { if (GT_OreDictUnificator.get(prefixes, Materials.Cerium, 1) == null) continue; registryOreProcessRecipe( GT_OreDictUnificator.get(prefixes, Materials.Cerium, 1), isRich(prefixes) ? outputsRich : outputs ); } } // Samarium Ore { ItemStack[] outputs = new ItemStack[] { WerkstoffMaterialPool.SamariumOreConcentrate.get(OrePrefixes.dust, 11) }; ItemStack[] outputsRich = new ItemStack[] { WerkstoffMaterialPool.SamariumOreConcentrate.get(OrePrefixes.dust, 22) }; for (OrePrefixes prefixes : basicStoneTypes) { if (GT_OreDictUnificator.get(prefixes, Materials.Samarium, 1) == null) continue; registryOreProcessRecipe( GT_OreDictUnificator.get(prefixes, Materials.Samarium, 1), isRich(prefixes) ? outputsRich : outputs ); } } // Naquadah Ore { ItemStack[] outputs = new ItemStack[] { MyMaterial.naquadahEarth.get(OrePrefixes.dust, 8), MyMaterial.enrichedNaquadahEarth.get(OrePrefixes.dust, 3), }; ItemStack[] outputsRich = new ItemStack[] { MyMaterial.naquadahEarth.get(OrePrefixes.dust, 16), MyMaterial.enrichedNaquadahEarth.get(OrePrefixes.dust, 8), }; for (OrePrefixes prefixes : basicStoneTypes) { if (GT_OreDictUnificator.get(prefixes, Materials.Naquadah, 1) == null) continue; registryOreProcessRecipe( GT_OreDictUnificator.get(prefixes, Materials.Naquadah, 1), isRich(prefixes) ? outputsRich : outputs ); } } // Enriched Naquadah Ore { ItemStack[] outputs = new ItemStack[] { MyMaterial.enrichedNaquadahEarth.get(OrePrefixes.dust, 8), MyMaterial.naquadriaEarth.get(OrePrefixes.dust, 3) }; ItemStack[] outputsRich = new ItemStack[] { MyMaterial.enrichedNaquadahEarth.get(OrePrefixes.dust, 16), MyMaterial.naquadriaEarth.get(OrePrefixes.dust, 6) }; for (OrePrefixes prefixes : basicStoneTypes) { if (GT_OreDictUnificator.get(prefixes, Materials.NaquadahEnriched, 1) == null) continue; registryOreProcessRecipe( GT_OreDictUnificator.get(prefixes, Materials.NaquadahEnriched, 1), isRich(prefixes) ? outputsRich : outputs ); } } // Naquadria Ore { ItemStack[] outputs = new ItemStack[] { MyMaterial.naquadriaEarth.get(OrePrefixes.dust, 8), MyMaterial.naquadriaEarth.get(OrePrefixes.dust, 3), }; ItemStack[] outputsRich = new ItemStack[] { MyMaterial.naquadriaEarth.get(OrePrefixes.dust, 16), MyMaterial.naquadriaEarth.get(OrePrefixes.dust, 6), }; for (OrePrefixes prefixes : basicStoneTypes) { if (GT_OreDictUnificator.get(prefixes, Materials.Naquadria, 1) == null) continue; registryOreProcessRecipe( GT_OreDictUnificator.get(prefixes, Materials.Naquadria, 1), isRich(prefixes) ? outputsRich : outputs ); } } // Tinker Construct // Cobalt ore processOreRecipe( GT_ModHandler.getModItem("TConstruct","SearedBrick", 1, 1), Materials.Cobalt, true ); // Ardite ore processOreRecipe( GT_ModHandler.getModItem("TConstruct","SearedBrick", 1, 2), Materials.Ardite, true ); // IC2 Uranium ore processOreRecipe( copyAmount(1,Ic2Items.uraniumOre), Materials.Uranium, false ); // HEE end powder registryOreProcessRecipe( GT_ModHandler.getModItem("HardcoreEnderExpansion","end_powder_ore",1), new ItemStack[]{GT_ModHandler.getModItem("HardcoreEnderExpansion", "end_powder", 24)} ); // spotless:on } /** * Generate normal ore recipes * * @param material The ore's Material. * @param ID The material ID. */ public void processOreRecipe(Materials material, int ID) { if (GT_OreDictUnificator.get(OrePrefixes.ore, material, 1) == null) return; ItemStack[] outputs = getOutputs(material, false); ItemStack[] outputsRich = getOutputs(material, true); // registry normal stone ore registryOreProcessRecipe(GT_ModHandler.getModItem("gregtech", "gt.blockores", 1, ID), outputs); // registry gt stone ore for (OrePrefixes prefixes : basicStoneTypesExceptNormalStone) { if (GT_OreDictUnificator.get(prefixes, material, 1) == null) { TwistSpaceTechnology.LOG.info("Failed to get ore: material=" + material + " , prefixes=" + prefixes); continue; } registryOreProcessRecipe( GT_OreDictUnificator.get(prefixes, material, 1), isRich(prefixes) ? outputsRich : outputs); } } /** * Process other mods' ore but normal style. * * @param inputOreItems Input ore item stack. * @param material Input ore's material in GT design. * @param isRich Is this ore a rich type. */ public void processOreRecipe(ItemStack inputOreItems, Materials material, boolean isRich) { registryOreProcessRecipe(inputOreItems, getOutputs(material, isRich)); } public ItemStack[] getOutputs(Materials material, boolean isRich) { List<ItemStack> outputs = new ArrayList<>(); // check byproduct if (!material.mOreByProducts.isEmpty()) { // the basic output the material outputs.add(getDustStack(material, 4)); if (material.mOreByProducts.size() == 1) { for (Materials byproduct : material.mOreByProducts) { if (byproduct == null) continue; outputs.add(getDustStack(byproduct, 3)); } } else { for (Materials byproduct : material.mOreByProducts) { if (byproduct == null || byproduct == Materials.Netherrack || byproduct == Materials.Endstone || byproduct == Materials.Stone) continue; outputs.add(getDustStack(byproduct, 2)); } } } else { outputs.add(getDustStack(material, 8)); } // check gem style if (GT_OreDictUnificator.get(OrePrefixes.gem, material, 1) != null) { if (GT_OreDictUnificator.get(OrePrefixes.gemExquisite, material, 1) != null) { // has gem style outputs.add(GT_OreDictUnificator.get(OrePrefixes.gemExquisite, material, 1)); outputs.add(GT_OreDictUnificator.get(OrePrefixes.gemFlawless, material, 2)); outputs.add(GT_OreDictUnificator.get(OrePrefixes.gem, material, 2)); } else { // just normal gem outputs.add(GT_OreDictUnificator.get(OrePrefixes.gem, material, 4)); } } if (isRich) { for (ItemStack out : outputs) { out.stackSize *= 2; } } return outputs.toArray(new ItemStack[0]); } public void registryOreProcessRecipe(ItemStack input, ItemStack[] output) { GT_Values.RA.stdBuilder() .itemInputs(input) .itemOutputs(output) .fluidInputs(Materials.Lubricant.getFluid(1)) .noOptimize() .eut(OreProcessRecipeEUt) .duration(OreProcessRecipeDuration)
.addTo(GTCMRecipe.OreProcessingRecipes);
6
2023-10-16 09:57:15+00:00
16k
wyjsonGo/GoRouter
GoRouter-Api/src/main/java/com/wyjson/router/core/RouteCenter.java
[ { "identifier": "ROUTER_CURRENT_PATH", "path": "GoRouter-Api/src/main/java/com/wyjson/router/core/Constants.java", "snippet": "static final String ROUTER_CURRENT_PATH = \"go_router_current_path\";" }, { "identifier": "ROUTER_RAW_URI", "path": "GoRouter-Api/src/main/java/com/wyjson/router/cor...
import static com.wyjson.router.core.Constants.ROUTER_CURRENT_PATH; import static com.wyjson.router.core.Constants.ROUTER_RAW_URI; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.wyjson.router.GoRouter; import com.wyjson.router.enums.ParamType; import com.wyjson.router.exception.NoFoundRouteException; import com.wyjson.router.exception.ParamException; import com.wyjson.router.exception.RouterException; import com.wyjson.router.interfaces.IJsonService; import com.wyjson.router.model.Card; import com.wyjson.router.model.CardMeta; import com.wyjson.router.model.ParamMeta; import com.wyjson.router.module.interfaces.IRouteModuleGroup; import com.wyjson.router.utils.MapUtils; import com.wyjson.router.utils.TextUtils; import java.lang.reflect.Field; import java.util.Map;
10,836
package com.wyjson.router.core; public class RouteCenter { private static IJsonService jsonService; public static Map<String, IRouteModuleGroup> getRouteGroups() { return Warehouse.routeGroups; } /** * 动态添加路由分组,按需加载路由 * * @param group * @param routeModuleGroup */ public static void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { Warehouse.routeGroups.put(group, routeModuleGroup); GoRouter.logger.info(null, "[addRouterGroup] Add a route group[" + group + "] dynamically"); } /** * 获取路由元数据 * * @param card * @return * @throws NoFoundRouteException */
package com.wyjson.router.core; public class RouteCenter { private static IJsonService jsonService; public static Map<String, IRouteModuleGroup> getRouteGroups() { return Warehouse.routeGroups; } /** * 动态添加路由分组,按需加载路由 * * @param group * @param routeModuleGroup */ public static void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { Warehouse.routeGroups.put(group, routeModuleGroup); GoRouter.logger.info(null, "[addRouterGroup] Add a route group[" + group + "] dynamically"); } /** * 获取路由元数据 * * @param card * @return * @throws NoFoundRouteException */
public static CardMeta getCardMeta(Card card) throws NoFoundRouteException {
4
2023-10-18 13:52:07+00:00
16k
trpc-group/trpc-java
trpc-registry/trpc-registry-open-polaris/src/test/java/com/tencent/trpc/registry/polaris/PolarisRegistryTest.java
[ { "identifier": "ConfigManager", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/ConfigManager.java", "snippet": "public class ConfigManager {\n\n private static final Logger logger = LoggerFactory.getLogger(ServerConfig.class);\n private static ConfigManager instance = new ConfigMan...
import static com.tencent.trpc.polaris.common.PolarisRegistryConstant.PRIORITY_PARAM_KEY; import static com.tencent.trpc.polaris.common.PolarisRegistryConstant.WEIGHT_PARAM_KEY; import static org.mockito.Matchers.anyObject; import com.tencent.polaris.api.core.ProviderAPI; import com.tencent.polaris.api.exception.PolarisException; import com.tencent.polaris.api.rpc.InstanceDeregisterRequest; import com.tencent.polaris.api.rpc.InstanceHeartbeatRequest; import com.tencent.polaris.api.rpc.InstanceRegisterRequest; import com.tencent.polaris.api.rpc.InstanceRegisterResponse; import com.tencent.polaris.factory.api.APIFactory; import com.tencent.trpc.core.common.ConfigManager; import com.tencent.trpc.core.common.config.PluginConfig; import com.tencent.trpc.core.extension.ExtensionLoader; import com.tencent.trpc.core.registry.RegisterInfo; import com.tencent.trpc.core.registry.spi.Registry; import com.tencent.trpc.polaris.common.PolarisRegistryConstant; import com.tencent.trpc.support.HeartBeatManager; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner;
13,338
/* * 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.registry.polaris; @RunWith(PowerMockRunner.class) @PrepareForTest({APIFactory.class, HeartBeatManager.class}) @PowerMockIgnore({"javax.management.*"}) public class PolarisRegistryTest extends TestCase { @Captor private ArgumentCaptor<Integer> intervalCaptor; protected void setUp() { MockitoAnnotations.initMocks(this); PowerMockito.mockStatic(APIFactory.class); PowerMockito.mockStatic(HeartBeatManager.class); } @Test public void testRegistry() throws PolarisException { PowerMockito.when(APIFactory.createProviderAPIByConfig(anyObject())) .thenReturn(new ProviderAPI() { @Override public InstanceRegisterResponse registerInstance(InstanceRegisterRequest instanceRegisterRequest) throws PolarisException { return null; } @Override public InstanceRegisterResponse register( InstanceRegisterRequest instanceRegisterRequest) { Assert.assertEquals(2000, instanceRegisterRequest.getTtl().intValue()); InstanceRegisterResponse instanceRegisterResponse = new InstanceRegisterResponse("101", true); return instanceRegisterResponse; } @Override public void deRegister(InstanceDeregisterRequest instanceDeRegisterRequest) throws PolarisException { Assert.assertEquals("101", instanceDeRegisterRequest.getInstanceID()); } @Override public void heartbeat(InstanceHeartbeatRequest instanceHeartbeatRequest) throws PolarisException { Assert.assertEquals("101", instanceHeartbeatRequest.getInstanceID()); } @Override public void destroy() { } @Override public void close() { ProviderAPI.super.close(); } }); Map<String, Object> extMap = new HashMap<>(); extMap.put(PolarisRegistryConstant.POLARIS_ADDRESSES_KEY, "10.0.0.1"); extMap.put(PolarisRegistryConstant.TOKEN_PARAM_KEY, "test"); extMap.put(PolarisRegistryConstant.HEARTBEAT_THREAD_CORE_SIZE, 10); extMap.put(PolarisRegistryConstant.HEARTBEAT_THREAD_MAXSIZE, 20); extMap.put(PolarisRegistryConstant.HEARTBEAT_THREAD_QUEUE_SIZE, 1000); extMap.put(PolarisRegistryConstant.HEARTBEAT_THREAD_KEEP_ALIVE_SECONDS, 120L); extMap.put(PolarisRegistryConstant.TTL_KEY, 2000); extMap.put(PRIORITY_PARAM_KEY, 1); extMap.put(WEIGHT_PARAM_KEY, 100); extMap.put(PolarisRegistryConstant.REGISTER_SELF, true); ConfigManager.getInstance().getGlobalConfig().setEnableSet(true); ConfigManager.getInstance().getGlobalConfig().setFullSetName("test.sz.1"); ConfigManager.getInstance().registerPlugin(new PluginConfig("polaris", PolarisRegistry.class, extMap)); Map<String, Object> params = new HashMap<>(); params.put(PolarisRegistryConstant.TOKEN_PARAM_KEY, "test"); params.put(PolarisRegistryConstant.NAMESPACE_KEY, "test"); params.put(PolarisRegistryConstant.TIMEOUT_PARAM_KEY, 60000); params.put(PRIORITY_PARAM_KEY, 1); params.put(WEIGHT_PARAM_KEY, 100);
/* * 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.registry.polaris; @RunWith(PowerMockRunner.class) @PrepareForTest({APIFactory.class, HeartBeatManager.class}) @PowerMockIgnore({"javax.management.*"}) public class PolarisRegistryTest extends TestCase { @Captor private ArgumentCaptor<Integer> intervalCaptor; protected void setUp() { MockitoAnnotations.initMocks(this); PowerMockito.mockStatic(APIFactory.class); PowerMockito.mockStatic(HeartBeatManager.class); } @Test public void testRegistry() throws PolarisException { PowerMockito.when(APIFactory.createProviderAPIByConfig(anyObject())) .thenReturn(new ProviderAPI() { @Override public InstanceRegisterResponse registerInstance(InstanceRegisterRequest instanceRegisterRequest) throws PolarisException { return null; } @Override public InstanceRegisterResponse register( InstanceRegisterRequest instanceRegisterRequest) { Assert.assertEquals(2000, instanceRegisterRequest.getTtl().intValue()); InstanceRegisterResponse instanceRegisterResponse = new InstanceRegisterResponse("101", true); return instanceRegisterResponse; } @Override public void deRegister(InstanceDeregisterRequest instanceDeRegisterRequest) throws PolarisException { Assert.assertEquals("101", instanceDeRegisterRequest.getInstanceID()); } @Override public void heartbeat(InstanceHeartbeatRequest instanceHeartbeatRequest) throws PolarisException { Assert.assertEquals("101", instanceHeartbeatRequest.getInstanceID()); } @Override public void destroy() { } @Override public void close() { ProviderAPI.super.close(); } }); Map<String, Object> extMap = new HashMap<>(); extMap.put(PolarisRegistryConstant.POLARIS_ADDRESSES_KEY, "10.0.0.1"); extMap.put(PolarisRegistryConstant.TOKEN_PARAM_KEY, "test"); extMap.put(PolarisRegistryConstant.HEARTBEAT_THREAD_CORE_SIZE, 10); extMap.put(PolarisRegistryConstant.HEARTBEAT_THREAD_MAXSIZE, 20); extMap.put(PolarisRegistryConstant.HEARTBEAT_THREAD_QUEUE_SIZE, 1000); extMap.put(PolarisRegistryConstant.HEARTBEAT_THREAD_KEEP_ALIVE_SECONDS, 120L); extMap.put(PolarisRegistryConstant.TTL_KEY, 2000); extMap.put(PRIORITY_PARAM_KEY, 1); extMap.put(WEIGHT_PARAM_KEY, 100); extMap.put(PolarisRegistryConstant.REGISTER_SELF, true); ConfigManager.getInstance().getGlobalConfig().setEnableSet(true); ConfigManager.getInstance().getGlobalConfig().setFullSetName("test.sz.1"); ConfigManager.getInstance().registerPlugin(new PluginConfig("polaris", PolarisRegistry.class, extMap)); Map<String, Object> params = new HashMap<>(); params.put(PolarisRegistryConstant.TOKEN_PARAM_KEY, "test"); params.put(PolarisRegistryConstant.NAMESPACE_KEY, "test"); params.put(PolarisRegistryConstant.TIMEOUT_PARAM_KEY, 60000); params.put(PRIORITY_PARAM_KEY, 1); params.put(WEIGHT_PARAM_KEY, 100);
RegisterInfo registerInfo =
3
2023-10-19 10:54:11+00:00
16k
eclipse-jgit/jgit
org.eclipse.jgit/src/org/eclipse/jgit/transport/PushCertificate.java
[ { "identifier": "NONCE", "path": "org.eclipse.jgit/src/org/eclipse/jgit/transport/PushCertificateParser.java", "snippet": "static final String NONCE = \"nonce\"; //$NON-NLS-1$" }, { "identifier": "PUSHEE", "path": "org.eclipse.jgit/src/org/eclipse/jgit/transport/PushCertificateParser.java", ...
import static org.eclipse.jgit.transport.PushCertificateParser.NONCE; import static org.eclipse.jgit.transport.PushCertificateParser.PUSHEE; import static org.eclipse.jgit.transport.PushCertificateParser.PUSHER; import static org.eclipse.jgit.transport.PushCertificateParser.VERSION; import java.text.MessageFormat; import java.util.List; import java.util.Objects; import org.eclipse.jgit.internal.JGitText;
11,072
/* * Copyright (C) 2015, 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.transport; /** * The required information to verify the push. * <p> * A valid certificate will not return null from any getter methods; callers may * assume that any null value indicates a missing or invalid certificate. * * @since 4.0 */ public class PushCertificate { /** Verification result of the nonce returned during push. */ public enum NonceStatus { /** Nonce was not expected, yet client sent one anyway. */ UNSOLICITED, /** Nonce is invalid and did not match server's expectations. */ BAD, /** Nonce is required, but was not sent by client. */ MISSING, /** * Received nonce matches sent nonce, or is valid within the accepted slop * window. */ OK, /** Received nonce is valid, but outside the accepted slop window. */ SLOP } private final String version; private final PushCertificateIdent pusher; private final String pushee; private final String nonce; private final NonceStatus nonceStatus; private final List<ReceiveCommand> commands; private final String signature; PushCertificate(String version, PushCertificateIdent pusher, String pushee, String nonce, NonceStatus nonceStatus, List<ReceiveCommand> commands, String signature) { if (version == null || version.isEmpty()) { throw new IllegalArgumentException(MessageFormat.format( JGitText.get().pushCertificateInvalidField, VERSION)); } if (pusher == null) { throw new IllegalArgumentException(MessageFormat.format( JGitText.get().pushCertificateInvalidField, PUSHER)); } if (nonce == null || nonce.isEmpty()) { throw new IllegalArgumentException(MessageFormat.format(
/* * Copyright (C) 2015, 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.transport; /** * The required information to verify the push. * <p> * A valid certificate will not return null from any getter methods; callers may * assume that any null value indicates a missing or invalid certificate. * * @since 4.0 */ public class PushCertificate { /** Verification result of the nonce returned during push. */ public enum NonceStatus { /** Nonce was not expected, yet client sent one anyway. */ UNSOLICITED, /** Nonce is invalid and did not match server's expectations. */ BAD, /** Nonce is required, but was not sent by client. */ MISSING, /** * Received nonce matches sent nonce, or is valid within the accepted slop * window. */ OK, /** Received nonce is valid, but outside the accepted slop window. */ SLOP } private final String version; private final PushCertificateIdent pusher; private final String pushee; private final String nonce; private final NonceStatus nonceStatus; private final List<ReceiveCommand> commands; private final String signature; PushCertificate(String version, PushCertificateIdent pusher, String pushee, String nonce, NonceStatus nonceStatus, List<ReceiveCommand> commands, String signature) { if (version == null || version.isEmpty()) { throw new IllegalArgumentException(MessageFormat.format( JGitText.get().pushCertificateInvalidField, VERSION)); } if (pusher == null) { throw new IllegalArgumentException(MessageFormat.format( JGitText.get().pushCertificateInvalidField, PUSHER)); } if (nonce == null || nonce.isEmpty()) { throw new IllegalArgumentException(MessageFormat.format(
JGitText.get().pushCertificateInvalidField, NONCE));
0
2023-10-20 15:09:17+00:00
16k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/common/block/TortoiseEggBlock.java
[ { "identifier": "Alligator", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/Alligator.java", "snippet": "public class Alligator extends NaturalistAnimal implements IAnimatable, EggLayingAnimal {\n private static final Ingredient FOOD_ITEMS = Ingredient.of(NaturalistTags.I...
import com.starfish_studios.naturalist.common.entity.Alligator; import com.starfish_studios.naturalist.common.entity.Tortoise; import com.starfish_studios.naturalist.core.registry.NaturalistEntityTypes; import com.starfish_studios.naturalist.core.registry.NaturalistSoundEvents; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.monster.Zombie; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.TurtleEggBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.gameevent.GameEvent;
12,817
package com.starfish_studios.naturalist.common.block; public class TortoiseEggBlock extends TurtleEggBlock { public TortoiseEggBlock(Properties properties) { super(properties); } @Override public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { if (this.shouldUpdateHatchLevel(level)) { int i = state.getValue(HATCH); if (i < 2) { level.playSound(null, pos, NaturalistSoundEvents.TORTOISE_EGG_CRACK.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.setBlock(pos, (BlockState)state.setValue(HATCH, i + 1), 2); } else { level.playSound(null, pos, NaturalistSoundEvents.TORTOISE_EGG_HATCH.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.removeBlock(pos, false); for (int j = 0; j < state.getValue(EGGS); ++j) { level.levelEvent(2001, pos, Block.getId(state)); Tortoise tortoise = NaturalistEntityTypes.TORTOISE.get().create(level); tortoise.setAge(-24000); tortoise.moveTo((double)pos.getX() + 0.3 + (double)j * 0.2, pos.getY(), (double)pos.getZ() + 0.3, 0.0f, 0.0f); level.addFreshEntity(tortoise); } } } } @Override public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) { if (!level.isClientSide) { level.levelEvent(2005, pos, 0); } } private boolean shouldUpdateHatchLevel(Level level) { return level.random.nextInt(500) == 0; } @Override public void stepOn(Level level, BlockPos pos, BlockState state, Entity entity) { if (!entity.isSteppingCarefully()) { this.destroyEgg(level, state, pos, entity, 100); } super.stepOn(level, pos, state, entity); } @Override public void fallOn(Level level, BlockState state, BlockPos pos, Entity entity, float fallDistance) { if (!(entity instanceof Zombie)) { this.destroyEgg(level, state, pos, entity, 3); } super.fallOn(level, state, pos, entity, fallDistance); } private void destroyEgg(Level level, BlockState state, BlockPos pos, Entity entity, int chance) { if (!this.canDestroyEgg(level, entity)) { return; } if (!level.isClientSide && level.random.nextInt(chance) == 0 && state.is(Blocks.TURTLE_EGG)) { this.decreaseEggs(level, pos, state); } } private boolean canDestroyEgg(Level level, Entity entity) {
package com.starfish_studios.naturalist.common.block; public class TortoiseEggBlock extends TurtleEggBlock { public TortoiseEggBlock(Properties properties) { super(properties); } @Override public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { if (this.shouldUpdateHatchLevel(level)) { int i = state.getValue(HATCH); if (i < 2) { level.playSound(null, pos, NaturalistSoundEvents.TORTOISE_EGG_CRACK.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.setBlock(pos, (BlockState)state.setValue(HATCH, i + 1), 2); } else { level.playSound(null, pos, NaturalistSoundEvents.TORTOISE_EGG_HATCH.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.removeBlock(pos, false); for (int j = 0; j < state.getValue(EGGS); ++j) { level.levelEvent(2001, pos, Block.getId(state)); Tortoise tortoise = NaturalistEntityTypes.TORTOISE.get().create(level); tortoise.setAge(-24000); tortoise.moveTo((double)pos.getX() + 0.3 + (double)j * 0.2, pos.getY(), (double)pos.getZ() + 0.3, 0.0f, 0.0f); level.addFreshEntity(tortoise); } } } } @Override public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) { if (!level.isClientSide) { level.levelEvent(2005, pos, 0); } } private boolean shouldUpdateHatchLevel(Level level) { return level.random.nextInt(500) == 0; } @Override public void stepOn(Level level, BlockPos pos, BlockState state, Entity entity) { if (!entity.isSteppingCarefully()) { this.destroyEgg(level, state, pos, entity, 100); } super.stepOn(level, pos, state, entity); } @Override public void fallOn(Level level, BlockState state, BlockPos pos, Entity entity, float fallDistance) { if (!(entity instanceof Zombie)) { this.destroyEgg(level, state, pos, entity, 3); } super.fallOn(level, state, pos, entity, fallDistance); } private void destroyEgg(Level level, BlockState state, BlockPos pos, Entity entity, int chance) { if (!this.canDestroyEgg(level, entity)) { return; } if (!level.isClientSide && level.random.nextInt(chance) == 0 && state.is(Blocks.TURTLE_EGG)) { this.decreaseEggs(level, pos, state); } } private boolean canDestroyEgg(Level level, Entity entity) {
if (entity instanceof Alligator) {
0
2023-10-16 21:54:32+00:00
16k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/current/CurrentFragment.java
[ { "identifier": "Utils", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/Utils.java", "snippet": "public class Utils {\n private static final String TAG = \"Utils\";\n //\tpublic final static String ACTION_RECEIVER_CHANGED=\"cn.wq.myandroidtoolspro.receiver_changed\";\n//\tprivate final ...
import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.widget.AppCompatSeekBar; import android.support.v7.widget.SwitchCompat; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.List; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.Utils; import cn.wq.myandroidtoolspro.recyclerview.fragment.CustomProgressDialogFragment; import cn.wq.myandroidtoolspro.recyclerview.toolbar.BaseFragment;
13,064
package cn.wq.myandroidtoolspro.recyclerview.fragment.current; /** * Created by wangqi on 2017/7/6. */ public class CurrentFragment extends BaseFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { private SwitchCompat mActivitySwitch, mFragmentSwitch,mMoveSwitch; // private ComponentName mActivityServiceComponentName; private View mFragmentTimeParent, mActivityTextsizeParent,mFragmentParent,mMoveParent; private TextView mFragmentTimeTv; private SharedPreferences sharedPreferences; private final static int REQUEST_CODE_NUM_PICKER = 100; private TextView mActSizeTv; private AppCompatSeekBar mActSeekBar; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //参考:https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/layout/preference.xml return inflater.inflate(R.layout.fragment_current, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.current_activity_parent).setOnClickListener(this); mActivitySwitch = (SwitchCompat) view.findViewById(R.id.current_activity_switch); mActivitySwitch.setOnCheckedChangeListener(this); mFragmentParent = view.findViewById(R.id.current_fragment_parent); mFragmentParent.setOnClickListener(this); mFragmentSwitch = (SwitchCompat) view.findViewById(R.id.current_fragment_switch); mFragmentSwitch.setOnCheckedChangeListener(this); mActivityTextsizeParent = view.findViewById(R.id.current_activity_textsize_parent); mFragmentTimeParent = view.findViewById(R.id.current_fragment_time_parent); mFragmentTimeParent.setOnClickListener(this); mActSizeTv = (TextView) view.findViewById(R.id.current_activity_textsize); // 真实值从 5~30,progress从 0~5 mActSeekBar = (AppCompatSeekBar) view.findViewById(R.id.current_activity_seekbar); mActSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { final int newValue = progress + 5; mActSizeTv.setText(getString(R.string.textsize) + ": " + newValue); sharedPreferences.edit() .putInt("current_activity_textsize", newValue).apply();
package cn.wq.myandroidtoolspro.recyclerview.fragment.current; /** * Created by wangqi on 2017/7/6. */ public class CurrentFragment extends BaseFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { private SwitchCompat mActivitySwitch, mFragmentSwitch,mMoveSwitch; // private ComponentName mActivityServiceComponentName; private View mFragmentTimeParent, mActivityTextsizeParent,mFragmentParent,mMoveParent; private TextView mFragmentTimeTv; private SharedPreferences sharedPreferences; private final static int REQUEST_CODE_NUM_PICKER = 100; private TextView mActSizeTv; private AppCompatSeekBar mActSeekBar; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //参考:https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/layout/preference.xml return inflater.inflate(R.layout.fragment_current, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.current_activity_parent).setOnClickListener(this); mActivitySwitch = (SwitchCompat) view.findViewById(R.id.current_activity_switch); mActivitySwitch.setOnCheckedChangeListener(this); mFragmentParent = view.findViewById(R.id.current_fragment_parent); mFragmentParent.setOnClickListener(this); mFragmentSwitch = (SwitchCompat) view.findViewById(R.id.current_fragment_switch); mFragmentSwitch.setOnCheckedChangeListener(this); mActivityTextsizeParent = view.findViewById(R.id.current_activity_textsize_parent); mFragmentTimeParent = view.findViewById(R.id.current_fragment_time_parent); mFragmentTimeParent.setOnClickListener(this); mActSizeTv = (TextView) view.findViewById(R.id.current_activity_textsize); // 真实值从 5~30,progress从 0~5 mActSeekBar = (AppCompatSeekBar) view.findViewById(R.id.current_activity_seekbar); mActSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { final int newValue = progress + 5; mActSizeTv.setText(getString(R.string.textsize) + ": " + newValue); sharedPreferences.edit() .putInt("current_activity_textsize", newValue).apply();
Intent intent = new Intent(Utils.ACTION_ACTIVITY_TEXTSIZE);
0
2023-10-18 14:32:49+00:00
16k
instana/otel-dc
rdb/src/main/java/com/instana/dc/rdb/impl/DamengDc.java
[ { "identifier": "CalculationMode", "path": "internal/otel-dc/src/main/java/com/instana/dc/CalculationMode.java", "snippet": "public enum CalculationMode {\n DIRECT,\n RATE\n}" }, { "identifier": "DcUtil", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcUtil.java", "snippet...
import com.instana.dc.CalculationMode; import com.instana.dc.DcUtil; import com.instana.dc.rdb.AbstractDbDc; import com.instana.dc.rdb.DbDcUtil; import io.opentelemetry.api.OpenTelemetry; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static com.instana.agent.sensorsdk.semconv.SemanticAttributes.*; import static com.instana.dc.rdb.DbDcUtil.*; import static com.instana.dc.rdb.impl.DamengUtil.*;
11,617
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb.impl; public class DamengDc extends AbstractDbDc { private static final Logger logger = Logger.getLogger(DamengDc.class.getName()); public DamengDc(Map<String, String> properties, String dbSystem, String dbDriver) throws SQLException { super(properties, dbSystem, dbDriver); setDbPassword(DcUtil.base64Decode(getDbPassword())); findDbNameAndVersion(); if (getServiceInstanceId() == null) { setServiceInstanceId(getDbAddress() + ":" + getDbPort() + "@" + getDbName()); } } private void findDbNameAndVersion() throws SQLException { try (Connection connection = getConnection()) { ResultSet rs = DbDcUtil.executeQuery(connection, DB_NAME_VERSION_SQL); rs.next(); if (getDbName() == null) setDbName(rs.getString(1)); setDbVersion(rs.getString(2)); } } @Override public void registerMetrics() { super.registerMetrics();
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb.impl; public class DamengDc extends AbstractDbDc { private static final Logger logger = Logger.getLogger(DamengDc.class.getName()); public DamengDc(Map<String, String> properties, String dbSystem, String dbDriver) throws SQLException { super(properties, dbSystem, dbDriver); setDbPassword(DcUtil.base64Decode(getDbPassword())); findDbNameAndVersion(); if (getServiceInstanceId() == null) { setServiceInstanceId(getDbAddress() + ":" + getDbPort() + "@" + getDbName()); } } private void findDbNameAndVersion() throws SQLException { try (Connection connection = getConnection()) { ResultSet rs = DbDcUtil.executeQuery(connection, DB_NAME_VERSION_SQL); rs.next(); if (getDbName() == null) setDbName(rs.getString(1)); setDbVersion(rs.getString(2)); } } @Override public void registerMetrics() { super.registerMetrics();
getRawMetric(DB_TRANSACTION_RATE_NAME).setCalculationMode(CalculationMode.RATE);
0
2023-10-23 01:16:38+00:00
16k
histevehu/12306
business/src/main/java/com/steve/train/business/service/TrainService.java
[ { "identifier": "Train", "path": "business/src/main/java/com/steve/train/business/domain/Train.java", "snippet": "public class Train {\n private Long id;\n\n private String code;\n\n private String type;\n\n private String start;\n\n private String startPinyin;\n\n private Date startTi...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.util.ObjectUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.steve.train.business.domain.Train; import com.steve.train.business.domain.TrainExample; import com.steve.train.business.mapper.TrainMapper; import com.steve.train.business.req.TrainQueryReq; import com.steve.train.business.req.TrainSaveReq; import com.steve.train.business.resp.TrainQueryResp; import com.steve.train.common.exception.BusinessException; import com.steve.train.common.exception.BusinessExceptionEnum; import com.steve.train.common.resp.PageResp; import com.steve.train.common.util.SnowFlakeUtil; import jakarta.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List;
11,520
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-10-29 09:38:38 * @description: 车次服务(FreeMarker生成) */ @Service public class TrainService { private static final Logger LOG = LoggerFactory.getLogger(TrainService.class); @Resource private TrainMapper trainMapper; public void save(TrainSaveReq req) { DateTime now = DateTime.now(); Train train = BeanUtil.copyProperties(req, Train.class); if (ObjectUtil.isNull(train.getId())) { Train trainDB = selectByUnique(req.getCode()); if (ObjectUtil.isNotEmpty(trainDB)) {
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-10-29 09:38:38 * @description: 车次服务(FreeMarker生成) */ @Service public class TrainService { private static final Logger LOG = LoggerFactory.getLogger(TrainService.class); @Resource private TrainMapper trainMapper; public void save(TrainSaveReq req) { DateTime now = DateTime.now(); Train train = BeanUtil.copyProperties(req, Train.class); if (ObjectUtil.isNull(train.getId())) { Train trainDB = selectByUnique(req.getCode()); if (ObjectUtil.isNotEmpty(trainDB)) {
throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_CODE_UNIQUE_ERROR);
6
2023-10-23 01:20:56+00:00
16k
team-moabam/moabam-BE
src/main/java/com/moabam/api/application/room/RoomService.java
[ { "identifier": "RoomType", "path": "src/main/java/com/moabam/api/domain/room/RoomType.java", "snippet": "public enum RoomType {\n\n\tMORNING,\n\tNIGHT\n}" }, { "identifier": "ErrorMessage", "path": "src/main/java/com/moabam/global/error/model/ErrorMessage.java", "snippet": "@Getter\n@Re...
import static com.moabam.api.domain.room.RoomType.*; import static com.moabam.global.error.model.ErrorMessage.*; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.moabam.api.application.member.MemberService; 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.member.Member; 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.DailyMemberCertificationRepository; import com.moabam.api.domain.room.repository.ParticipantRepository; import com.moabam.api.domain.room.repository.ParticipantSearchRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.domain.room.repository.RoutineRepository; import com.moabam.api.dto.room.CreateRoomRequest; import com.moabam.api.dto.room.EnterRoomRequest; import com.moabam.api.dto.room.ModifyRoomRequest; import com.moabam.global.common.util.ClockHolder; import com.moabam.global.error.exception.BadRequestException; import com.moabam.global.error.exception.ForbiddenException; import com.moabam.global.error.exception.NotFoundException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j;
10,984
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Slf4j @Transactional(readOnly = true) public class RoomService { private final RoomRepository roomRepository;
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Slf4j @Transactional(readOnly = true) public class RoomService { private final RoomRepository roomRepository;
private final RoutineRepository routineRepository;
15
2023-10-20 06:15:43+00:00
16k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/label/XmTag.java
[ { "identifier": "CallBack", "path": "BaseUI/src/main/java/com/xm2013/jfx/common/CallBack.java", "snippet": "public interface CallBack<T> {\n \n /**\n * Call.\n *\n * @param t the t\n */\n public void call(T t);\n}" }, { "identifier": "FxKit", "path": "BaseUI/src/main...
import com.xm2013.jfx.common.CallBack; import com.xm2013.jfx.common.FxKit; import com.xm2013.jfx.control.base.CssKeys; import com.xm2013.jfx.control.base.HueType; import com.xm2013.jfx.control.base.XmControl; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.value.WritableValue; import javafx.css.CssMetaData; import javafx.css.Styleable; import javafx.css.StyleableProperty; import javafx.css.converter.BooleanConverter; import javafx.css.converter.EnumConverter; import javafx.scene.AccessibleRole; import javafx.scene.Node; import javafx.scene.control.Control; import javafx.scene.control.Skin; import java.util.ArrayList; import java.util.Collections; import java.util.List;
10,932
/* * 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.label; public class XmTag extends XmLabel { private static final String USER_AGENT_STYLESHEET = FxKit.getResourceURL("/css/control.css"); public XmTag(){ this(null); } public XmTag(String text){ this(text, null); } public XmTag(String text, Node graphic){ super(text, graphic); init(); } private void init(){ getStyleClass().setAll("xm-tag"); setAccessibleRole(AccessibleRole.TEXT); getStylesheets().add(USER_AGENT_STYLESHEET); } protected Skin<?> createDefaultSkin() { return new XmTagSkin(this); } /** * 点击关闭的时候的回调函数 */ private CallBack closeCallback; public void setCloseCallback(CallBack callback){ this.closeCallback = callback; } public CallBack getCloseCallback(){ return this.closeCallback; } private CallBack<String> editEnterCallback; public CallBack<String> getEditEnterCallback() { return editEnterCallback; } public void setEditEnterCallback(CallBack<String> editEnterCallback) { this.editEnterCallback = editEnterCallback; } /** * 是否可以关闭标签 */ private BooleanProperty closeable; public boolean isCloseable() { return closeableProperty().get(); } public BooleanProperty closeableProperty() { if(closeable == null){ closeable = FxKit.newBooleanProperty(false, StyleableProperties.CLOSEABLE, this, "closeable"); } return closeable; } public void setCloseable(boolean closeable) { this.closeableProperty().set(closeable); } /** * 是否可以编辑 */ private BooleanProperty editable; public boolean isEditable() { return editableProperty().get(); } public BooleanProperty editableProperty() { if(editable == null) editable = FxKit.newBooleanProperty(false, StyleableProperties.EDITABLE, this, "editable"); return editable; } public void setEditable(boolean editable) { this.editableProperty().set(editable); }
/* * 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.label; public class XmTag extends XmLabel { private static final String USER_AGENT_STYLESHEET = FxKit.getResourceURL("/css/control.css"); public XmTag(){ this(null); } public XmTag(String text){ this(text, null); } public XmTag(String text, Node graphic){ super(text, graphic); init(); } private void init(){ getStyleClass().setAll("xm-tag"); setAccessibleRole(AccessibleRole.TEXT); getStylesheets().add(USER_AGENT_STYLESHEET); } protected Skin<?> createDefaultSkin() { return new XmTagSkin(this); } /** * 点击关闭的时候的回调函数 */ private CallBack closeCallback; public void setCloseCallback(CallBack callback){ this.closeCallback = callback; } public CallBack getCloseCallback(){ return this.closeCallback; } private CallBack<String> editEnterCallback; public CallBack<String> getEditEnterCallback() { return editEnterCallback; } public void setEditEnterCallback(CallBack<String> editEnterCallback) { this.editEnterCallback = editEnterCallback; } /** * 是否可以关闭标签 */ private BooleanProperty closeable; public boolean isCloseable() { return closeableProperty().get(); } public BooleanProperty closeableProperty() { if(closeable == null){ closeable = FxKit.newBooleanProperty(false, StyleableProperties.CLOSEABLE, this, "closeable"); } return closeable; } public void setCloseable(boolean closeable) { this.closeableProperty().set(closeable); } /** * 是否可以编辑 */ private BooleanProperty editable; public boolean isEditable() { return editableProperty().get(); } public BooleanProperty editableProperty() { if(editable == null) editable = FxKit.newBooleanProperty(false, StyleableProperties.EDITABLE, this, "editable"); return editable; } public void setEditable(boolean editable) { this.editableProperty().set(editable); }
private ObjectProperty<HueType> hueType;
3
2023-10-17 08:57:08+00:00
16k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/PCFGLA/SentenceSegmenter.java
[ { "identifier": "PTBLineLexer", "path": "src/berkeley_parser/edu/berkeley/nlp/io/PTBLineLexer.java", "snippet": "public class PTBLineLexer extends PTBLexer {\n\n\tpublic PTBLineLexer() {\n\t\tsuper((java.io.Reader) null);\n\t}\n\n\tpublic List<String> tokenizeLine(String line) throws IOException {\n\t\t...
import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.imageio.ImageIO; import javax.swing.JFrame; import edu.berkeley.nlp.io.PTBLineLexer; import edu.berkeley.nlp.syntax.Tree; import edu.berkeley.nlp.ui.TreeJPanel; import edu.berkeley.nlp.util.Numberer; import edu.berkeley.nlp.util.Pair;
12,282
package edu.berkeley.nlp.PCFGLA; /** * * @author Slav Petrov */ public class SentenceSegmenter { static TreeJPanel tjp; static JFrame frame; public static class Options { @Option(name = "-gr", required = true, usage = "Grammarfile (Required)\n") public String grFileName; @Option(name = "-tokenize", usage = "Tokenize input first. (Default: false=text is already tokenized)") public boolean tokenize; @Option(name = "-accurate", usage = "Set thresholds for accuracy. (Default: set thresholds for efficiency)") public boolean accurate; @Option(name = "-constituent", usage = "Instead of sentence probabilities return constituent probabilities") public boolean constituent = false; @Option(name = "-inputFile", usage = "Read input from this file instead of reading it from STDIN.") public String inputFile; @Option(name = "-outputFile", usage = "Store output in this file instead of printing it to STDOUT.") public String outputFile; } @SuppressWarnings("unchecked") public static void main(String[] args) { OptionParser optParser = new OptionParser(Options.class); Options opts = (Options) optParser.parse(args, true); double threshold = 1.0; String inFileName = opts.grFileName; ParserData pData = ParserData.Load(inFileName); if (pData == null) { System.out.println("Failed to load grammar from file" + inFileName + "."); System.exit(1); } Grammar grammar = pData.getGrammar(); Lexicon lexicon = pData.getLexicon(); Numberer.setNumberers(pData.getNumbs()); CoarseToFineMaxRuleParser parser = null; parser = new CoarseToFineMaxRuleParser(grammar, lexicon, threshold, -1, false, false, false, opts.accurate, false, true, true); parser.binarization = pData.getBinarization(); try { BufferedReader inputData = (opts.inputFile == null) ? new BufferedReader( new InputStreamReader(System.in)) : new BufferedReader( new InputStreamReader(new FileInputStream(opts.inputFile), "UTF-8")); PrintWriter outputData = (opts.outputFile == null) ? new PrintWriter( new OutputStreamWriter(System.out)) : new PrintWriter( new OutputStreamWriter( new FileOutputStream(opts.outputFile), "UTF-8"), true);
package edu.berkeley.nlp.PCFGLA; /** * * @author Slav Petrov */ public class SentenceSegmenter { static TreeJPanel tjp; static JFrame frame; public static class Options { @Option(name = "-gr", required = true, usage = "Grammarfile (Required)\n") public String grFileName; @Option(name = "-tokenize", usage = "Tokenize input first. (Default: false=text is already tokenized)") public boolean tokenize; @Option(name = "-accurate", usage = "Set thresholds for accuracy. (Default: set thresholds for efficiency)") public boolean accurate; @Option(name = "-constituent", usage = "Instead of sentence probabilities return constituent probabilities") public boolean constituent = false; @Option(name = "-inputFile", usage = "Read input from this file instead of reading it from STDIN.") public String inputFile; @Option(name = "-outputFile", usage = "Store output in this file instead of printing it to STDOUT.") public String outputFile; } @SuppressWarnings("unchecked") public static void main(String[] args) { OptionParser optParser = new OptionParser(Options.class); Options opts = (Options) optParser.parse(args, true); double threshold = 1.0; String inFileName = opts.grFileName; ParserData pData = ParserData.Load(inFileName); if (pData == null) { System.out.println("Failed to load grammar from file" + inFileName + "."); System.exit(1); } Grammar grammar = pData.getGrammar(); Lexicon lexicon = pData.getLexicon(); Numberer.setNumberers(pData.getNumbs()); CoarseToFineMaxRuleParser parser = null; parser = new CoarseToFineMaxRuleParser(grammar, lexicon, threshold, -1, false, false, false, opts.accurate, false, true, true); parser.binarization = pData.getBinarization(); try { BufferedReader inputData = (opts.inputFile == null) ? new BufferedReader( new InputStreamReader(System.in)) : new BufferedReader( new InputStreamReader(new FileInputStream(opts.inputFile), "UTF-8")); PrintWriter outputData = (opts.outputFile == null) ? new PrintWriter( new OutputStreamWriter(System.out)) : new PrintWriter( new OutputStreamWriter( new FileOutputStream(opts.outputFile), "UTF-8"), true);
PTBLineLexer tokenizer = null;
0
2023-10-22 13:13:22+00:00
16k
neftalito/R-Info-Plus
arbol/Programa.java
[ { "identifier": "CodePanel", "path": "form/CodePanel.java", "snippet": "public class CodePanel extends JPanel{\n private JToolBar toolBar;\n public MyTextPane text;\n Ciudad city;\n MonitorActualizarVentana esperarRefresco;\n private JButton saveButton;\n private JButton newButton;\n ...
import form.CodePanel; import form.Ciudad; import form.Robot;
14,011
package arbol; public class Programa extends AST { Identificador I; DeclaracionRobots DR; DeclaracionProcesos DP; DeclaracionVariable DV; DeclaracionAreas DA; Cuerpo C; Robot R; Ciudad city;
package arbol; public class Programa extends AST { Identificador I; DeclaracionRobots DR; DeclaracionProcesos DP; DeclaracionVariable DV; DeclaracionAreas DA; Cuerpo C; Robot R; Ciudad city;
CodePanel codigo;
0
2023-10-20 15:45:37+00:00
16k
UnityFoundation-io/Libre311
app/src/main/java/app/service/servicerequest/ServiceRequestService.java
[ { "identifier": "DownloadRequestsArgumentsDTO", "path": "app/src/main/java/app/dto/download/DownloadRequestsArgumentsDTO.java", "snippet": "@Introspected\npublic class DownloadRequestsArgumentsDTO {\n\n @Nullable\n @QueryValue(value = \"jurisdiction_id\")\n private String jurisdictionId;\n\n ...
import app.dto.download.DownloadRequestsArgumentsDTO; import app.dto.download.DownloadServiceRequestDTO; import app.dto.servicerequest.*; import app.model.service.Service; import app.model.service.ServiceRepository; import app.model.service.servicedefinition.AttributeDataType; import app.model.service.servicedefinition.AttributeValue; import app.model.service.servicedefinition.ServiceDefinition; import app.model.service.servicedefinition.ServiceDefinitionAttribute; import app.model.servicerequest.ServiceRequest; import app.model.servicerequest.ServiceRequestRepository; import app.model.servicerequest.ServiceRequestStatus; import app.recaptcha.ReCaptchaService; import app.service.storage.StorageUrlUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.bean.StatefulBeanToCsv; import com.opencsv.bean.StatefulBeanToCsvBuilder; import com.opencsv.exceptions.CsvDataTypeMismatchException; import com.opencsv.exceptions.CsvRequiredFieldEmptyException; import io.micronaut.core.util.StringUtils; import io.micronaut.data.model.Page; import io.micronaut.data.model.Pageable; import io.micronaut.data.model.Sort; import io.micronaut.http.HttpRequest; import io.micronaut.http.server.types.files.StreamedFile; import jakarta.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.MalformedURLException; import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream;
10,807
if (StringUtils.hasText(serviceRequestIds)) { List<Long> requestIds = Arrays.stream(serviceRequestIds.split(",")).map(String::trim).map(Long::valueOf).collect(Collectors.toList()); return serviceRequestRepository.findByIdIn(requestIds, pageable); } if (jurisdictionId == null) { return getServiceRequests(pageable, serviceCode, status, startDate, endDate); } return getJurisdictionServiceRequests(jurisdictionId, pageable, serviceCode, status, startDate, endDate); } private Page<ServiceRequest> getServiceRequests(Pageable pageable, String serviceCode, ServiceRequestStatus status, Instant startDate, Instant endDate) { if (StringUtils.hasText(serviceCode) && status != null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedBetween(serviceCode, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedAfter(serviceCode, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedBefore(serviceCode, status, endDate, pageable); } return serviceRequestRepository.findByServiceServiceCodeAndStatus(serviceCode, status, pageable); } else if (StringUtils.hasText(serviceCode) && status == null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedBetween(serviceCode, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedAfter(serviceCode, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedBefore(serviceCode, endDate, pageable); } return serviceRequestRepository.findByServiceServiceCode(serviceCode, pageable); } else if (status != null && StringUtils.isEmpty(serviceCode)) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByStatusAndDateCreatedBetween(status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByStatusAndDateCreatedAfter(status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByStatusAndDateCreatedBefore(status, endDate, pageable); } return serviceRequestRepository.findByStatus(status, pageable); } if (startDate != null && endDate != null) { return serviceRequestRepository.findByDateCreatedBetween(startDate, endDate, pageable); } else if (startDate != null && endDate == null) { // just start return serviceRequestRepository.findByDateCreatedAfter(startDate, pageable); } else if (startDate == null && endDate != null) { // just end return serviceRequestRepository.findByDateCreatedBefore(endDate, pageable); } return serviceRequestRepository.findAll(pageable); } private Page<ServiceRequest> getJurisdictionServiceRequests(String jurisdictionId, Pageable pageable, String serviceCode, ServiceRequestStatus status, Instant startDate, Instant endDate) { if (StringUtils.hasText(serviceCode) && status != null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBetween(jurisdictionId, serviceCode, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedAfter(jurisdictionId, serviceCode, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBefore(jurisdictionId, serviceCode, status, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatus(jurisdictionId, serviceCode, status, pageable); } else if (StringUtils.hasText(serviceCode) && status == null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBetween(jurisdictionId, serviceCode, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedAfter(jurisdictionId, serviceCode, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBefore(jurisdictionId, serviceCode, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCode(jurisdictionId, serviceCode, pageable); } else if (status != null && StringUtils.isEmpty(serviceCode)) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedBetween(jurisdictionId, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedAfter(jurisdictionId, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedBefore(jurisdictionId, status, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndStatus(jurisdictionId, status, pageable); } if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndDateCreatedBetween(jurisdictionId, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { // just start return serviceRequestRepository.findByJurisdictionIdAndDateCreatedAfter(jurisdictionId, startDate, pageable); } else if (startDate == null && endDate != null) { // just end return serviceRequestRepository.findByJurisdictionIdAndDateCreatedBefore(jurisdictionId, endDate, pageable); } return serviceRequestRepository.findAllByJurisdictionId(jurisdictionId, pageable); } public ServiceRequestDTO getServiceRequest(Long serviceRequestId, String jurisdictionId) { Optional<ServiceRequest> serviceRequestOptional; if (jurisdictionId == null) { serviceRequestOptional = serviceRequestRepository.findById(serviceRequestId); } else { serviceRequestOptional = serviceRequestRepository.findByIdAndJurisdictionId(serviceRequestId, jurisdictionId); } return serviceRequestOptional.map(ServiceRequestService::convertToDTO).orElse(null); } public StreamedFile getAllServiceRequests(DownloadRequestsArgumentsDTO downloadRequestsArgumentsDTO) throws MalformedURLException {
// Copyright 2023 Libre311 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package app.service.servicerequest; @Singleton public class ServiceRequestService { private static final Logger LOG = LoggerFactory.getLogger(ServiceRequestService.class); private final ServiceRequestRepository serviceRequestRepository; private final ServiceRepository serviceRepository; private final ReCaptchaService reCaptchaService; private final StorageUrlUtil storageUrlUtil; public ServiceRequestService(ServiceRequestRepository serviceRequestRepository, ServiceRepository serviceRepository, ReCaptchaService reCaptchaService, StorageUrlUtil storageUrlUtil) { this.serviceRequestRepository = serviceRequestRepository; this.serviceRepository = serviceRepository; this.reCaptchaService = reCaptchaService; this.storageUrlUtil = storageUrlUtil; } private static ServiceRequestDTO convertToDTO(ServiceRequest serviceRequest) { ServiceRequestDTO serviceRequestDTO = new ServiceRequestDTO(serviceRequest); ObjectMapper objectMapper = new ObjectMapper(); String attributesJson = serviceRequest.getAttributesJson(); if (attributesJson != null) { try { ServiceDefinitionAttribute[] serviceDefinitionAttributes = objectMapper.readValue(attributesJson, ServiceDefinitionAttribute[].class); serviceRequestDTO.setSelectedValues(List.of(serviceDefinitionAttributes)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } return serviceRequestDTO; } public PostResponseServiceRequestDTO createServiceRequest(HttpRequest<?> request, PostRequestServiceRequestDTO serviceRequestDTO) { if (!reCaptchaService.verifyReCaptcha(serviceRequestDTO.getgRecaptchaResponse())) { LOG.error("ReCaptcha verification failed."); return null; } if (!validMediaUrl(serviceRequestDTO.getMediaUrl())) { LOG.error("Media URL is invalid."); return null; } Optional<Service> serviceByServiceCodeOptional = serviceRepository.findByServiceCode(serviceRequestDTO.getServiceCode()); if (serviceByServiceCodeOptional.isEmpty()) { LOG.error("Corresponding service not found."); return null; // todo return 'corresponding service not found } if (serviceRequestDTO.getJurisdictionId() != null && !serviceRequestDTO.getJurisdictionId().equals(serviceByServiceCodeOptional.get().getJurisdiction().getId())) { LOG.error("Mismatch between jurisdiction_id provided and Service's associated jurisdiction."); return null; } // validate if a location is provided boolean latLongProvided = StringUtils.hasText(serviceRequestDTO.getLatitude()) && StringUtils.hasText(serviceRequestDTO.getLongitude()); if (!latLongProvided && StringUtils.isEmpty(serviceRequestDTO.getAddressString()) && StringUtils.isEmpty(serviceRequestDTO.getAddressId())) { LOG.error("Address or lat/long not provided."); return null; // todo throw exception } // validate if additional attributes are required List<ServiceDefinitionAttribute> requestAttributes = null; Service service = serviceByServiceCodeOptional.get(); if (service.isMetadata()) { // get service definition String serviceDefinitionJson = service.getServiceDefinitionJson(); if (serviceDefinitionJson == null || serviceDefinitionJson.isBlank()) { LOG.error("Service definition does not exists despite service requiring it."); return null; // should not be in this state and admin needs to be aware. } requestAttributes = buildUserResponseAttributesFromRequest(request, serviceDefinitionJson); if (requestAttributes.isEmpty()) { LOG.error("Submitted Service Request does not contain any attribute values."); return null; // todo throw exception - must provide attributes } if (!requestAttributesHasAllRequiredServiceDefinitionAttributes(serviceDefinitionJson, requestAttributes)) { LOG.error("Submitted Service Request does not contain required attribute values."); return null; // todo throw exception (validation) } } ServiceRequest serviceRequest = transformDtoToServiceRequest(serviceRequestDTO, service); if (requestAttributes != null) { ObjectMapper objectMapper = new ObjectMapper(); try { serviceRequest.setAttributesJson(objectMapper.writeValueAsString(requestAttributes)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } return new PostResponseServiceRequestDTO(serviceRequestRepository.save(serviceRequest)); } private boolean validMediaUrl(String mediaUrl) { if (mediaUrl == null) return true; return mediaUrl.startsWith(storageUrlUtil.getBucketUrlString()); } private boolean requestAttributesHasAllRequiredServiceDefinitionAttributes(String serviceDefinitionJson, List<ServiceDefinitionAttribute> requestAttributes) { // deserialize ObjectMapper objectMapper = new ObjectMapper(); boolean containsAllRequiredAttrs = false; try { // collect all required attributes ServiceDefinition serviceDefinition = objectMapper.readValue(serviceDefinitionJson, ServiceDefinition.class); List<String> requiredCodes = serviceDefinition.getAttributes().stream() .filter(ServiceDefinitionAttribute::isRequired) .map(ServiceDefinitionAttribute::getCode) .collect(Collectors.toList()); // for each attr, check if it exists in requestAttributes List<String> requestCodes = requestAttributes.stream() .map(ServiceDefinitionAttribute::getCode) .collect(Collectors.toList()); containsAllRequiredAttrs = requestCodes.containsAll(requiredCodes); } catch (JsonProcessingException e) { throw new RuntimeException(e); } return containsAllRequiredAttrs; } private List<ServiceDefinitionAttribute> buildUserResponseAttributesFromRequest(HttpRequest<?> request, String serviceDefinitionJson) { ObjectMapper objectMapper = new ObjectMapper(); ServiceDefinition serviceDefinition; try { serviceDefinition = objectMapper.readValue(serviceDefinitionJson, ServiceDefinition.class); } catch (JsonProcessingException e) { throw new RuntimeException(e); } Optional<Map> body = request.getBody(Map.class); List<ServiceDefinitionAttribute> attributes = new ArrayList<>(); if (body.isPresent()) { Map<String, Object> map = body.get(); map.forEach((k, v) -> { if (k.startsWith("attribute[")) { String attributeCode = k.substring(k.indexOf("[") + 1, k.indexOf("]")); // search for attribute by code in serviceDefinition Optional<ServiceDefinitionAttribute> serviceDefinitionAttributeOptional = serviceDefinition.getAttributes().stream() .filter(serviceDefinitionAttribute -> serviceDefinitionAttribute.getCode().equals(attributeCode)) .findFirst(); // if attribute in request does not exist in db, then ignore if (serviceDefinitionAttributeOptional.isEmpty()) { return; } ServiceDefinitionAttribute serviceDefinitionAttribute = serviceDefinitionAttributeOptional.get(); // validate the value if necessary (number and dates) if (v != null && !validValueType(v, serviceDefinitionAttribute.getDatatype())) { String errorMsg = String.format("Provided value for attribute with code %s is invalid", attributeCode); LOG.error(errorMsg); throw new RuntimeException(errorMsg); } ServiceDefinitionAttribute sda = new ServiceDefinitionAttribute(); sda.setCode(attributeCode); sda.setAttributeOrder(serviceDefinitionAttribute.getAttributeOrder()); sda.setRequired(serviceDefinitionAttribute.isRequired()); sda.setVariable(serviceDefinitionAttribute.isVariable()); List<AttributeValue> values = new ArrayList<>(); if (serviceDefinitionAttribute.getDatatype() == AttributeDataType.SINGLEVALUELIST || serviceDefinitionAttribute.getDatatype() == AttributeDataType.MULTIVALUELIST) { List<AttributeValue> attributeValues = serviceDefinitionAttribute.getValues(); if (attributeValues != null) { if (v instanceof ArrayList) { ((ArrayList<?>) v).forEach(s -> { values.add(new AttributeValue((String) s, getAttributeValueName((String) s, attributeValues))); }); } else { values.add(new AttributeValue((String) v, getAttributeValueName((String) v, attributeValues))); } } } else { // we need a way to capture the user's response. We will do so by adding an attribute value where // the key is the code and the value is the user's response. values.add(new AttributeValue(attributeCode, (String) v)); } attributes.add(sda); } }); } return attributes; } private boolean validValueType(Object v, AttributeDataType datatype) { if (datatype == AttributeDataType.NUMBER || datatype == AttributeDataType.DATETIME){ String value = (String) v; if (datatype == AttributeDataType.NUMBER) { try { Integer.parseInt(value); } catch (NumberFormatException nfe) { return false; } } else { try { Instant.parse(value); } catch (DateTimeParseException dtpe) { return false; } } return true; } return true; } private String getAttributeValueName(String valueKey, List<AttributeValue> attributeValues) { String valueName = null; Optional<AttributeValue> attributeValueOptional = attributeValues.stream() .filter(attributeValue -> attributeValue.getKey().equals(valueKey)).findFirst(); if (attributeValueOptional.isPresent()) { valueName = attributeValueOptional.get().getName(); } return valueName; } private ServiceRequest transformDtoToServiceRequest(PostRequestServiceRequestDTO serviceRequestDTO, Service service) { ServiceRequest serviceRequest = new ServiceRequest(); serviceRequest.setService(service); serviceRequest.setJurisdiction(service.getJurisdiction()); serviceRequest.setLatitude(serviceRequestDTO.getLatitude()); serviceRequest.setLongitude(serviceRequestDTO.getLongitude()); serviceRequest.setAddressString(serviceRequestDTO.getAddressString()); serviceRequest.setAddressId(serviceRequestDTO.getAddressId()); serviceRequest.setEmail(serviceRequestDTO.getEmail()); serviceRequest.setDeviceId(serviceRequestDTO.getDeviceId()); serviceRequest.setAccountId(serviceRequestDTO.getAccountId()); serviceRequest.setFirstName(serviceRequestDTO.getFirstName()); serviceRequest.setLastName(serviceRequestDTO.getLastName()); serviceRequest.setPhone(serviceRequestDTO.getPhone()); serviceRequest.setDescription(serviceRequestDTO.getDescription()); serviceRequest.setMediaUrl(serviceRequestDTO.getMediaUrl()); return serviceRequest; } public Page<ServiceRequestDTO> findAll(GetServiceRequestsDTO requestDTO) { return getServiceRequestPage(requestDTO).map(ServiceRequestService::convertToDTO); } private Page<ServiceRequest> getServiceRequestPage(GetServiceRequestsDTO requestDTO) { String serviceRequestIds = requestDTO.getId(); String serviceCode = requestDTO.getServiceCode(); String jurisdictionId = requestDTO.getJurisdictionId(); ServiceRequestStatus status = requestDTO.getStatus(); Instant startDate = requestDTO.getStartDate(); Instant endDate = requestDTO.getEndDate(); Pageable pageable = requestDTO.getPageable(); if(!pageable.isSorted()) { pageable = pageable.order("dateCreated", Sort.Order.Direction.DESC); } if (StringUtils.hasText(serviceRequestIds)) { List<Long> requestIds = Arrays.stream(serviceRequestIds.split(",")).map(String::trim).map(Long::valueOf).collect(Collectors.toList()); return serviceRequestRepository.findByIdIn(requestIds, pageable); } if (jurisdictionId == null) { return getServiceRequests(pageable, serviceCode, status, startDate, endDate); } return getJurisdictionServiceRequests(jurisdictionId, pageable, serviceCode, status, startDate, endDate); } private Page<ServiceRequest> getServiceRequests(Pageable pageable, String serviceCode, ServiceRequestStatus status, Instant startDate, Instant endDate) { if (StringUtils.hasText(serviceCode) && status != null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedBetween(serviceCode, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedAfter(serviceCode, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedBefore(serviceCode, status, endDate, pageable); } return serviceRequestRepository.findByServiceServiceCodeAndStatus(serviceCode, status, pageable); } else if (StringUtils.hasText(serviceCode) && status == null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedBetween(serviceCode, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedAfter(serviceCode, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedBefore(serviceCode, endDate, pageable); } return serviceRequestRepository.findByServiceServiceCode(serviceCode, pageable); } else if (status != null && StringUtils.isEmpty(serviceCode)) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByStatusAndDateCreatedBetween(status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByStatusAndDateCreatedAfter(status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByStatusAndDateCreatedBefore(status, endDate, pageable); } return serviceRequestRepository.findByStatus(status, pageable); } if (startDate != null && endDate != null) { return serviceRequestRepository.findByDateCreatedBetween(startDate, endDate, pageable); } else if (startDate != null && endDate == null) { // just start return serviceRequestRepository.findByDateCreatedAfter(startDate, pageable); } else if (startDate == null && endDate != null) { // just end return serviceRequestRepository.findByDateCreatedBefore(endDate, pageable); } return serviceRequestRepository.findAll(pageable); } private Page<ServiceRequest> getJurisdictionServiceRequests(String jurisdictionId, Pageable pageable, String serviceCode, ServiceRequestStatus status, Instant startDate, Instant endDate) { if (StringUtils.hasText(serviceCode) && status != null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBetween(jurisdictionId, serviceCode, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedAfter(jurisdictionId, serviceCode, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBefore(jurisdictionId, serviceCode, status, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatus(jurisdictionId, serviceCode, status, pageable); } else if (StringUtils.hasText(serviceCode) && status == null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBetween(jurisdictionId, serviceCode, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedAfter(jurisdictionId, serviceCode, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBefore(jurisdictionId, serviceCode, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCode(jurisdictionId, serviceCode, pageable); } else if (status != null && StringUtils.isEmpty(serviceCode)) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedBetween(jurisdictionId, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedAfter(jurisdictionId, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedBefore(jurisdictionId, status, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndStatus(jurisdictionId, status, pageable); } if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndDateCreatedBetween(jurisdictionId, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { // just start return serviceRequestRepository.findByJurisdictionIdAndDateCreatedAfter(jurisdictionId, startDate, pageable); } else if (startDate == null && endDate != null) { // just end return serviceRequestRepository.findByJurisdictionIdAndDateCreatedBefore(jurisdictionId, endDate, pageable); } return serviceRequestRepository.findAllByJurisdictionId(jurisdictionId, pageable); } public ServiceRequestDTO getServiceRequest(Long serviceRequestId, String jurisdictionId) { Optional<ServiceRequest> serviceRequestOptional; if (jurisdictionId == null) { serviceRequestOptional = serviceRequestRepository.findById(serviceRequestId); } else { serviceRequestOptional = serviceRequestRepository.findByIdAndJurisdictionId(serviceRequestId, jurisdictionId); } return serviceRequestOptional.map(ServiceRequestService::convertToDTO).orElse(null); } public StreamedFile getAllServiceRequests(DownloadRequestsArgumentsDTO downloadRequestsArgumentsDTO) throws MalformedURLException {
List<DownloadServiceRequestDTO> downloadServiceRequestDTOS = getServiceRequests(downloadRequestsArgumentsDTO).stream()
1
2023-10-18 15:37:36+00:00
16k
JonnyOnlineYT/xenza
src/minecraft/net/minecraft/network/play/server/S28PacketEffect.java
[ { "identifier": "Packet", "path": "src/minecraft/net/minecraft/network/Packet.java", "snippet": "public interface Packet<T extends INetHandler> {\n void readPacketData(PacketBuffer var1) throws IOException;\n\n void writePacketData(PacketBuffer var1) throws IOException;\n\n void processPacket(T va...
import java.io.IOException; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos;
11,280
package net.minecraft.network.play.server; public class S28PacketEffect implements Packet<INetHandlerPlayClient> { private int soundType; private BlockPos soundPos; private int soundData; private boolean serverWide; public S28PacketEffect() { } public S28PacketEffect(int soundTypeIn, BlockPos soundPosIn, int soundDataIn, boolean serverWideIn) { this.soundType = soundTypeIn; this.soundPos = soundPosIn; this.soundData = soundDataIn; this.serverWide = serverWideIn; } @Override
package net.minecraft.network.play.server; public class S28PacketEffect implements Packet<INetHandlerPlayClient> { private int soundType; private BlockPos soundPos; private int soundData; private boolean serverWide; public S28PacketEffect() { } public S28PacketEffect(int soundTypeIn, BlockPos soundPosIn, int soundDataIn, boolean serverWideIn) { this.soundType = soundTypeIn; this.soundPos = soundPosIn; this.soundData = soundDataIn; this.serverWide = serverWideIn; } @Override
public void readPacketData(PacketBuffer buf) throws IOException {
1
2023-10-15 00:21:15+00:00
16k
LeGhast/Miniaturise
src/main/java/de/leghast/miniaturise/command/SelectCommand.java
[ { "identifier": "Miniaturise", "path": "src/main/java/de/leghast/miniaturise/Miniaturise.java", "snippet": "public final class Miniaturise extends JavaPlugin {\n\n private MiniatureManager miniatureManager;\n private RegionManager regionManager;\n private SettingsManager settingsManager;\n\n ...
import de.leghast.miniaturise.Miniaturise; import de.leghast.miniaturise.instance.miniature.Miniature; import de.leghast.miniaturise.instance.miniature.PlacedMiniature; import de.leghast.miniaturise.instance.region.Region; import de.leghast.miniaturise.manager.ConfigManager; import de.leghast.miniaturise.util.Util; import org.bukkit.Chunk; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.BlockDisplay; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List;
11,016
package de.leghast.miniaturise.command; public class SelectCommand implements CommandExecutor { private Miniaturise main; public SelectCommand(Miniaturise main){ this.main = main; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { if(sender instanceof Player player){ if(player.hasPermission("miniaturise.use")){ if(main.getRegionManager().hasSelectedLocations(player.getUniqueId())){ if(main.getRegionManager().getSelectedLocations(player.getUniqueId()).isValid()){ try{ Region region = new Region(main.getRegionManager().getSelectedLocations(player.getUniqueId())); if(main.getRegionManager().hasRegion(player.getUniqueId())) { main.getRegionManager().getRegions().replace(player.getUniqueId(), region); }else{ main.getRegionManager().addRegion(player.getUniqueId(), region); } Miniature miniature = new Miniature(region, player.getLocation(), ConfigManager.getDefaultSize()); if(miniature.getBlocks().size() >= ConfigManager.getMaxEntityLimit()){ player.sendMessage(Util.PREFIX + "§cThe current selection §e(" + miniature.getBlocks().size() + " blocks) §cexceeds the limit of §e" + ConfigManager.getMaxEntityLimit() + " §cblocks"); main.getRegionManager().removeRegion(player.getUniqueId()); return false; } if(main.getMiniatureManager().hasMiniature(player.getUniqueId())){ main.getMiniatureManager().getMiniatures().replace(player.getUniqueId(), miniature); }else{ main.getMiniatureManager().addMiniature(player.getUniqueId(), miniature); } List<BlockDisplay> blockDisplays = Util.getBlockDisplaysFromRegion(player, region); if(!blockDisplays.isEmpty()){ if(main.getMiniatureManager().hasPlacedMiniature(player.getUniqueId())){ if(main.getMiniatureManager().getPlacedMiniature(player.getUniqueId()) != null){ }
package de.leghast.miniaturise.command; public class SelectCommand implements CommandExecutor { private Miniaturise main; public SelectCommand(Miniaturise main){ this.main = main; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { if(sender instanceof Player player){ if(player.hasPermission("miniaturise.use")){ if(main.getRegionManager().hasSelectedLocations(player.getUniqueId())){ if(main.getRegionManager().getSelectedLocations(player.getUniqueId()).isValid()){ try{ Region region = new Region(main.getRegionManager().getSelectedLocations(player.getUniqueId())); if(main.getRegionManager().hasRegion(player.getUniqueId())) { main.getRegionManager().getRegions().replace(player.getUniqueId(), region); }else{ main.getRegionManager().addRegion(player.getUniqueId(), region); } Miniature miniature = new Miniature(region, player.getLocation(), ConfigManager.getDefaultSize()); if(miniature.getBlocks().size() >= ConfigManager.getMaxEntityLimit()){ player.sendMessage(Util.PREFIX + "§cThe current selection §e(" + miniature.getBlocks().size() + " blocks) §cexceeds the limit of §e" + ConfigManager.getMaxEntityLimit() + " §cblocks"); main.getRegionManager().removeRegion(player.getUniqueId()); return false; } if(main.getMiniatureManager().hasMiniature(player.getUniqueId())){ main.getMiniatureManager().getMiniatures().replace(player.getUniqueId(), miniature); }else{ main.getMiniatureManager().addMiniature(player.getUniqueId(), miniature); } List<BlockDisplay> blockDisplays = Util.getBlockDisplaysFromRegion(player, region); if(!blockDisplays.isEmpty()){ if(main.getMiniatureManager().hasPlacedMiniature(player.getUniqueId())){ if(main.getMiniatureManager().getPlacedMiniature(player.getUniqueId()) != null){ }
main.getMiniatureManager().getPlacedMiniatures().replace(player.getUniqueId(), new PlacedMiniature(blockDisplays));
2
2023-10-15 09:08:33+00:00
16k
instrumental-id/iiq-common-public
src/com/identityworksllc/iiq/common/table/QueryTable.java
[ { "identifier": "ColumnConfig", "path": "src/com/identityworksllc/iiq/common/iterators/ColumnConfig.java", "snippet": "public final class ColumnConfig {\n\n /**\n * The error returned if the input to the constructor is wrong\n */\n private static final String BAD_INPUT_ERROR = \"Input must...
import com.identityworksllc.iiq.common.iterators.ColumnConfig; import com.identityworksllc.iiq.common.iterators.ResultSetIterator; import com.identityworksllc.iiq.common.query.NamedParameterStatement; import sailpoint.api.SailPointContext; import sailpoint.tools.GeneralException; import sailpoint.tools.JdbcUtil; import sailpoint.tools.Util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean;
12,729
package com.identityworksllc.iiq.common.table; /** * An extension of Table to run a SQL query and export it. You must provide a * Connection (or way of getting one) and a list of column specs. * * The meat of the querying takes place in {@link ResultSetIterator}. */ public class QueryTable implements AutoCloseable, StyleTarget { /** * The column specs, recognized by {@link ColumnConfig}. At this * time that is Strings, other ColumnConfig objects (which will be cloned), or * ReportColumnConfig objects. */ private final List<Object> columns; /** * The connection, which is assumed open until close() is invoked */ private final Connection connection; /** * The context */ private final SailPointContext context; /** * Set to true on render() */ private final AtomicBoolean frozen; /** * The Table to be populated by the query output */ private final Table table; /** * Constructs a n ew QueryTable with the given context, connection, and column * specifications. The column specs should be some object recognized by * the reporting class {@link ColumnConfig}. * * @param context The context * @param connection The SQL connection, which must be open and ready to query * @param columns A non-empty list of column specs */ public QueryTable(SailPointContext context, Connection connection, List<Object> columns) { this.connection = Objects.requireNonNull(connection); this.context = Objects.requireNonNull(context); if (columns == null || columns.isEmpty()) { throw new IllegalArgumentException("For QueryTable, 'columns' must contain at least one column specification"); } this.table = new Table(); this.columns = new ArrayList<>(columns); this.frozen = new AtomicBoolean(); } /** * Constructs a new QueryTable with the given context and connection, as well * as a string list of column tokens. * * @param context The context * @param connection The SQL connection, which must be open and ready to query * @param columns A non-empty list of column tokens */ public QueryTable(SailPointContext context, Connection connection, String... columns) { this(context, connection, Arrays.asList(columns)); } /** * Constructs a new QueryTable with the given context and connection info, as well * as a string list of column tokens. * * @param context The context * @param connectionInfo A map of connection info, with the same keys specified by connectors * @param columns A non-empty list of column tokens */ public QueryTable(SailPointContext context, Map<String, Object> connectionInfo, String... columns) throws GeneralException { this(context, JdbcUtil.getConnection(connectionInfo), columns); } /** * Constructs a new QueryTable with the given context and connection info, as well * as a string list of column tokens. * * @param context The context * @param connectionInfo A map of connection info, with the same keys specified by connectors * @param columns A non-empty list of column specs */ public QueryTable(SailPointContext context, Map<String, Object> connectionInfo, List<Object> columns) throws GeneralException { this(context, JdbcUtil.getConnection(connectionInfo), columns); } /** * Adds an output column to this QueryTable * * @param columnConfig The column config * @return This object, for call chaining */ public QueryTable addColumn(Object columnConfig) { if (columnConfig != null) { this.columns.add(columnConfig); } return this; } /** * Closes the connection * * @throws SQLException on failure to close the connection */ @Override public void close() throws SQLException { if (this.connection != null) { this.connection.close(); } } /** * Executes the given query with the given options. The query will be run * via {@link NamedParameterStatement}, so the arguments must be of a type * recognized by that class. * * @param queryString The query string, which must not be null or empty * @param arguments The list of arguments, if any * @return This object, for call chaining * @throws SQLException if any SQL failures occur * @throws GeneralException if any IIQ failures occur */ public QueryTable executeQuery(String queryString, Map<String, Object> arguments) throws SQLException, GeneralException { if (this.frozen.get()) { throw new IllegalArgumentException("QueryTable.executeQuery() cannot be invoked twice for the same table"); } if (Util.isNullOrEmpty(queryString)) { throw new IllegalArgumentException("The query passed to executeQuery() must not be null"); } try (NamedParameterStatement statement = new NamedParameterStatement(connection, queryString)) { statement.setParameters(arguments); try (ResultSet results = statement.executeQuery()) {
package com.identityworksllc.iiq.common.table; /** * An extension of Table to run a SQL query and export it. You must provide a * Connection (or way of getting one) and a list of column specs. * * The meat of the querying takes place in {@link ResultSetIterator}. */ public class QueryTable implements AutoCloseable, StyleTarget { /** * The column specs, recognized by {@link ColumnConfig}. At this * time that is Strings, other ColumnConfig objects (which will be cloned), or * ReportColumnConfig objects. */ private final List<Object> columns; /** * The connection, which is assumed open until close() is invoked */ private final Connection connection; /** * The context */ private final SailPointContext context; /** * Set to true on render() */ private final AtomicBoolean frozen; /** * The Table to be populated by the query output */ private final Table table; /** * Constructs a n ew QueryTable with the given context, connection, and column * specifications. The column specs should be some object recognized by * the reporting class {@link ColumnConfig}. * * @param context The context * @param connection The SQL connection, which must be open and ready to query * @param columns A non-empty list of column specs */ public QueryTable(SailPointContext context, Connection connection, List<Object> columns) { this.connection = Objects.requireNonNull(connection); this.context = Objects.requireNonNull(context); if (columns == null || columns.isEmpty()) { throw new IllegalArgumentException("For QueryTable, 'columns' must contain at least one column specification"); } this.table = new Table(); this.columns = new ArrayList<>(columns); this.frozen = new AtomicBoolean(); } /** * Constructs a new QueryTable with the given context and connection, as well * as a string list of column tokens. * * @param context The context * @param connection The SQL connection, which must be open and ready to query * @param columns A non-empty list of column tokens */ public QueryTable(SailPointContext context, Connection connection, String... columns) { this(context, connection, Arrays.asList(columns)); } /** * Constructs a new QueryTable with the given context and connection info, as well * as a string list of column tokens. * * @param context The context * @param connectionInfo A map of connection info, with the same keys specified by connectors * @param columns A non-empty list of column tokens */ public QueryTable(SailPointContext context, Map<String, Object> connectionInfo, String... columns) throws GeneralException { this(context, JdbcUtil.getConnection(connectionInfo), columns); } /** * Constructs a new QueryTable with the given context and connection info, as well * as a string list of column tokens. * * @param context The context * @param connectionInfo A map of connection info, with the same keys specified by connectors * @param columns A non-empty list of column specs */ public QueryTable(SailPointContext context, Map<String, Object> connectionInfo, List<Object> columns) throws GeneralException { this(context, JdbcUtil.getConnection(connectionInfo), columns); } /** * Adds an output column to this QueryTable * * @param columnConfig The column config * @return This object, for call chaining */ public QueryTable addColumn(Object columnConfig) { if (columnConfig != null) { this.columns.add(columnConfig); } return this; } /** * Closes the connection * * @throws SQLException on failure to close the connection */ @Override public void close() throws SQLException { if (this.connection != null) { this.connection.close(); } } /** * Executes the given query with the given options. The query will be run * via {@link NamedParameterStatement}, so the arguments must be of a type * recognized by that class. * * @param queryString The query string, which must not be null or empty * @param arguments The list of arguments, if any * @return This object, for call chaining * @throws SQLException if any SQL failures occur * @throws GeneralException if any IIQ failures occur */ public QueryTable executeQuery(String queryString, Map<String, Object> arguments) throws SQLException, GeneralException { if (this.frozen.get()) { throw new IllegalArgumentException("QueryTable.executeQuery() cannot be invoked twice for the same table"); } if (Util.isNullOrEmpty(queryString)) { throw new IllegalArgumentException("The query passed to executeQuery() must not be null"); } try (NamedParameterStatement statement = new NamedParameterStatement(connection, queryString)) { statement.setParameters(arguments); try (ResultSet results = statement.executeQuery()) {
ResultSetIterator rsi = new ResultSetIterator(results, this.columns, context);
1
2023-10-20 15:20:16+00:00
16k
mosaic-addons/traffic-state-estimation
src/main/java/com/dcaiti/mosaic/app/tse/processors/SpatioTemporalProcessor.java
[ { "identifier": "FcdRecord", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FcdRecord.java", "snippet": "public class FcdRecord extends FxdRecord {\n\n /**\n * List of vehicles perceived during the collection of FCD in the form of {@link VehicleObject VehicleObjects}.\n */\n private...
import com.dcaiti.mosaic.app.fxd.data.FcdRecord; import com.dcaiti.mosaic.app.fxd.data.FcdTraversal; import com.dcaiti.mosaic.app.tse.TseServerApp; import com.dcaiti.mosaic.app.tse.data.DatabaseAccess; 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 org.eclipse.mosaic.fed.application.ambassador.util.UnitLogger; import org.eclipse.mosaic.lib.database.Database; import org.eclipse.mosaic.lib.util.gson.UnitFieldAdapter; import org.eclipse.mosaic.rti.TIME; import com.google.common.collect.Iterables; import com.google.gson.annotations.JsonAdapter; import org.apache.commons.math3.analysis.interpolation.LinearInterpolator; import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction; import org.apache.commons.math3.exception.OutOfRangeException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List;
11,662
/* * Copyright (c) 2021 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse.processors; /** * Processes new FCD data. Holds methods to compute base-metrics and handles the record-buffer-queue for each veh. * It mainly handles computing the spatial and temporal mean speeds, once a veh leaves a connection. * This Data needs to be preprocessed, as it is the base from which the thresholds are derived. * * @see FcdDatabaseHelper * @see TseServerApp */ public class SpatioTemporalProcessor implements TraversalBasedProcessor<FcdRecord, FcdTraversal>, DatabaseAccess { private final static int CONNECTION_LENGTH_THRESHOLD = 5; /** * Each connection will be dissected into parts of this length and * the spatial mean speed will be averaged over measurements on these points. [m] */ @JsonAdapter(UnitFieldAdapter.DistanceMeters.class) public double spatialMeanSpeedChunkSize = 15; private UnitLogger logger; private Database networkDatabase; /** * needed to store and retrieve any data from the FcdDatabase. */ private FcdDataStorage fcdDataStorage; /** * Polls the last connection from the buffer, performs preprocessing and stores resulting metrics in db. * * @param vehicleId to compute sub-metrics for * @param traversal {@link FcdTraversal} containing all records of a connection traversal plus previous and following record */ private void computeSubMetrics(String vehicleId, FcdTraversal traversal) { final LinkedList<FcdRecord> records = buildTraversalList(traversal); String connectionId = traversal.getConnectionId(); if (records.size() < 3) { // we expect at least one record on the previous, one on the current, and one on the following connection logger.error("Invalid traversal during computation of sub metrics for vehicle {} on connection {}", vehicleId, connectionId); return; } // quit if incomplete traversal FcdRecord previousRecord = records.peekFirst(); FcdRecord firstRecordOnConnection = records.get(1); FcdRecord followingRecord = records.peekLast(); if (previousRecord == null || followingRecord == null || firstRecordOnConnection == null || previousRecord.getConnectionId().equals(firstRecordOnConnection.getConnectionId()) || firstRecordOnConnection.getConnectionId().equals(followingRecord.getConnectionId()) ) { // execution will always land here for the first edge-traversal as there is no previous connection traversed logger.debug("Incomplete traversal during computation of sub metrics for vehicle {} on connection {}", vehicleId, connectionId); return; } // Calculate Splines for the relation between distance driven and time/speed for the current traversal double[] distanceOffsets = new double[records.size()]; double[] speeds = new double[records.size()]; double[] timeStamps = new double[records.size()]; // set initial values timeStamps[0] = (double) records.get(0).getTimeStamp(); speeds[0] = records.get(0).getSpeed(); distanceOffsets[0] = records.get(0).getOffset(); // add offsets and timestamps for (int i = 1; i < records.size(); i++) { timeStamps[i] = (double) records.get(i).getTimeStamp(); speeds[i] = records.get(i).getSpeed(); distanceOffsets[i] = Math.max(records.get(i).getOffset(), distanceOffsets[i - 1] + 0.001); } // get the time-distance function to compute temporal mean speed PolynomialSplineFunction distanceTimeSpline = interpolateTimeDistanceFunction(distanceOffsets, timeStamps); PolynomialSplineFunction distanceSpeedSpline = interpolateSpeedDistanceFunction(distanceOffsets, speeds); double length = calculateTraversalLength(connectionId, distanceTimeSpline); try { double traversalTime = distanceTimeSpline.value(length) - distanceTimeSpline.value(0); double temporalMeanSpeed = (length / traversalTime) * TIME.SECOND; double spatialMeanSpeed = computeSpatialMeanSpeed(records, distanceSpeedSpline); float relativeMetric = -1; // insert RTSM as well, if thresholds are already available for the connection if (fcdDataStorage.gotThresholdFor(connectionId)) { relativeMetric = SpatioTemporalTrafficMetric.computeRelativeTrafficStatusMetric( temporalMeanSpeed, spatialMeanSpeed, connectionId, fcdDataStorage ); } FcdRecord lastRecordOfTraversal = Iterables.getLast(traversal.getTraversal()); fcdDataStorage.insertTraversalMetrics( vehicleId, lastRecordOfTraversal.getTimeStamp(), connectionId, traversal.getFollowingRecord() == null ? connectionId : traversal.getFollowingRecord().getConnectionId(), spatialMeanSpeed, temporalMeanSpeed, computeNaiveTemporalMeanSpeed(records), relativeMetric, (long) traversalTime); } catch (OutOfRangeException e) { // catches errors using polynomial spline function, due to errors in the connections // length and the actual length a vehicle travels on it logger.error("Error during computeSubMetrics() for {} on Connection {}: {}", vehicleId, connectionId, e.getMessage()); } } /** * This method build a list of records that is used to generate splines for a traversal. Additionally, the previous and following * records are considered with newly calculated offsets. * <br> * Note: Not exactly sure if we need the previous and following record * * @param traversal the traversal object * @return a {@link LinkedList} of {@link FcdRecord} representing a traversal */ private LinkedList<FcdRecord> buildTraversalList(FcdTraversal traversal) { final LinkedList<FcdRecord> records = new LinkedList<>(); if (traversal.getPreviousRecord() != null) { double offsetPreviousRecord = -traversal.getPreviousRecord().getPosition() .distanceTo(networkDatabase.getConnection(traversal.getConnectionId()).getNodes().get(0).getPosition()); records.add(new FcdRecord.Builder(traversal.getPreviousRecord()).withOffset(offsetPreviousRecord).build()); } records.addAll(traversal.getTraversal()); if (traversal.getFollowingRecord() != null && !records.isEmpty()) { FcdRecord lastTraversalRecord = records.peekLast(); double offsetFollowingRecord = lastTraversalRecord.getOffset() + lastTraversalRecord.getPosition() .distanceTo(traversal.getFollowingRecord().getPosition()); records.add(new FcdRecord.Builder(traversal.getFollowingRecord()).withOffset(offsetFollowingRecord).build()); } return records; } private double calculateTraversalLength(String connectionId, PolynomialSplineFunction distanceTimeSpline) {
/* * Copyright (c) 2021 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse.processors; /** * Processes new FCD data. Holds methods to compute base-metrics and handles the record-buffer-queue for each veh. * It mainly handles computing the spatial and temporal mean speeds, once a veh leaves a connection. * This Data needs to be preprocessed, as it is the base from which the thresholds are derived. * * @see FcdDatabaseHelper * @see TseServerApp */ public class SpatioTemporalProcessor implements TraversalBasedProcessor<FcdRecord, FcdTraversal>, DatabaseAccess { private final static int CONNECTION_LENGTH_THRESHOLD = 5; /** * Each connection will be dissected into parts of this length and * the spatial mean speed will be averaged over measurements on these points. [m] */ @JsonAdapter(UnitFieldAdapter.DistanceMeters.class) public double spatialMeanSpeedChunkSize = 15; private UnitLogger logger; private Database networkDatabase; /** * needed to store and retrieve any data from the FcdDatabase. */ private FcdDataStorage fcdDataStorage; /** * Polls the last connection from the buffer, performs preprocessing and stores resulting metrics in db. * * @param vehicleId to compute sub-metrics for * @param traversal {@link FcdTraversal} containing all records of a connection traversal plus previous and following record */ private void computeSubMetrics(String vehicleId, FcdTraversal traversal) { final LinkedList<FcdRecord> records = buildTraversalList(traversal); String connectionId = traversal.getConnectionId(); if (records.size() < 3) { // we expect at least one record on the previous, one on the current, and one on the following connection logger.error("Invalid traversal during computation of sub metrics for vehicle {} on connection {}", vehicleId, connectionId); return; } // quit if incomplete traversal FcdRecord previousRecord = records.peekFirst(); FcdRecord firstRecordOnConnection = records.get(1); FcdRecord followingRecord = records.peekLast(); if (previousRecord == null || followingRecord == null || firstRecordOnConnection == null || previousRecord.getConnectionId().equals(firstRecordOnConnection.getConnectionId()) || firstRecordOnConnection.getConnectionId().equals(followingRecord.getConnectionId()) ) { // execution will always land here for the first edge-traversal as there is no previous connection traversed logger.debug("Incomplete traversal during computation of sub metrics for vehicle {} on connection {}", vehicleId, connectionId); return; } // Calculate Splines for the relation between distance driven and time/speed for the current traversal double[] distanceOffsets = new double[records.size()]; double[] speeds = new double[records.size()]; double[] timeStamps = new double[records.size()]; // set initial values timeStamps[0] = (double) records.get(0).getTimeStamp(); speeds[0] = records.get(0).getSpeed(); distanceOffsets[0] = records.get(0).getOffset(); // add offsets and timestamps for (int i = 1; i < records.size(); i++) { timeStamps[i] = (double) records.get(i).getTimeStamp(); speeds[i] = records.get(i).getSpeed(); distanceOffsets[i] = Math.max(records.get(i).getOffset(), distanceOffsets[i - 1] + 0.001); } // get the time-distance function to compute temporal mean speed PolynomialSplineFunction distanceTimeSpline = interpolateTimeDistanceFunction(distanceOffsets, timeStamps); PolynomialSplineFunction distanceSpeedSpline = interpolateSpeedDistanceFunction(distanceOffsets, speeds); double length = calculateTraversalLength(connectionId, distanceTimeSpline); try { double traversalTime = distanceTimeSpline.value(length) - distanceTimeSpline.value(0); double temporalMeanSpeed = (length / traversalTime) * TIME.SECOND; double spatialMeanSpeed = computeSpatialMeanSpeed(records, distanceSpeedSpline); float relativeMetric = -1; // insert RTSM as well, if thresholds are already available for the connection if (fcdDataStorage.gotThresholdFor(connectionId)) { relativeMetric = SpatioTemporalTrafficMetric.computeRelativeTrafficStatusMetric( temporalMeanSpeed, spatialMeanSpeed, connectionId, fcdDataStorage ); } FcdRecord lastRecordOfTraversal = Iterables.getLast(traversal.getTraversal()); fcdDataStorage.insertTraversalMetrics( vehicleId, lastRecordOfTraversal.getTimeStamp(), connectionId, traversal.getFollowingRecord() == null ? connectionId : traversal.getFollowingRecord().getConnectionId(), spatialMeanSpeed, temporalMeanSpeed, computeNaiveTemporalMeanSpeed(records), relativeMetric, (long) traversalTime); } catch (OutOfRangeException e) { // catches errors using polynomial spline function, due to errors in the connections // length and the actual length a vehicle travels on it logger.error("Error during computeSubMetrics() for {} on Connection {}: {}", vehicleId, connectionId, e.getMessage()); } } /** * This method build a list of records that is used to generate splines for a traversal. Additionally, the previous and following * records are considered with newly calculated offsets. * <br> * Note: Not exactly sure if we need the previous and following record * * @param traversal the traversal object * @return a {@link LinkedList} of {@link FcdRecord} representing a traversal */ private LinkedList<FcdRecord> buildTraversalList(FcdTraversal traversal) { final LinkedList<FcdRecord> records = new LinkedList<>(); if (traversal.getPreviousRecord() != null) { double offsetPreviousRecord = -traversal.getPreviousRecord().getPosition() .distanceTo(networkDatabase.getConnection(traversal.getConnectionId()).getNodes().get(0).getPosition()); records.add(new FcdRecord.Builder(traversal.getPreviousRecord()).withOffset(offsetPreviousRecord).build()); } records.addAll(traversal.getTraversal()); if (traversal.getFollowingRecord() != null && !records.isEmpty()) { FcdRecord lastTraversalRecord = records.peekLast(); double offsetFollowingRecord = lastTraversalRecord.getOffset() + lastTraversalRecord.getPosition() .distanceTo(traversal.getFollowingRecord().getPosition()); records.add(new FcdRecord.Builder(traversal.getFollowingRecord()).withOffset(offsetFollowingRecord).build()); } return records; } private double calculateTraversalLength(String connectionId, PolynomialSplineFunction distanceTimeSpline) {
double length = ScenarioDatabaseHelper.calcLengthByNodes(networkDatabase.getConnection(connectionId));
6
2023-10-23 16:39:40+00:00
16k
Primogem-Craft-Development/Primogem-Craft-Fabric
src/main/java/com/primogemstudio/primogemcraft/items/instances/materials/nagadus/NagadusEmeraldShovelItem.java
[ { "identifier": "PrimogemCraftBlocks", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/PrimogemCraftBlocks.java", "snippet": "public class PrimogemCraftBlocks {\n public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem(\"dendro_core_block\", new DendroCoreBlock());\n ...
import com.primogemstudio.primogemcraft.blocks.PrimogemCraftBlocks; import com.primogemstudio.primogemcraft.items.PrimogemCraftItems; import com.primogemstudio.primogemcraft.sounds.PrimogemCraftSounds; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.*; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import java.util.List;
11,445
package com.primogemstudio.primogemcraft.items.instances.materials.nagadus; public class NagadusEmeraldShovelItem extends ShovelItem { public NagadusEmeraldShovelItem() { super(new Tier() { public int getUses() { return 1561; } public float getSpeed() { return 1f; } public float getAttackDamageBonus() { return 0f; } public int getLevel() { return 4; } public int getEnchantmentValue() { return 5; } public @NotNull Ingredient getRepairIngredient() { return Ingredient.of(new ItemStack(PrimogemCraftItems.PRIMOGEM_ITEM), new ItemStack(PrimogemCraftItems.NAGADUS_EMERALD_SLIVER_ITEM)); } }, 1, -1f, new Item.Properties().fireResistant()); } @Override public boolean mineBlock(ItemStack itemstack, Level world, BlockState blockstate, BlockPos pos, LivingEntity entity) { boolean retval = super.mineBlock(itemstack, world, blockstate, pos, entity); var x = pos.getX(); var y = pos.getY(); var z = pos.getZ(); if (itemstack.getOrCreateTag().getBoolean("value")) { if (Math.random() < 0.01) { if (Math.random() < 0.5) { if (world instanceof ServerLevel _level) { ItemEntity entityToSpawn = new ItemEntity(_level, x, y, z, new ItemStack(PrimogemCraftBlocks.BLESSING_OF_DENDRO_BLOCK)); entityToSpawn.setPickUpDelay(10); _level.addFreshEntity(entityToSpawn); } } else { world.setBlock(BlockPos.containing(x, y, z), PrimogemCraftBlocks.BLESSING_OF_DENDRO_BLOCK.defaultBlockState(), 3); } } } else { world.setBlock(BlockPos.containing(x, y, z), PrimogemCraftBlocks.BLESSING_OF_DENDRO_BLOCK.defaultBlockState(), 3); itemstack.getOrCreateTag().putBoolean("value", true); } return retval; } @Override public void appendHoverText(ItemStack itemstack, Level world, List<Component> list, TooltipFlag flag) { list.add(Component.translatable("tooltip.primogemcraft.nagadus_emerald_shovel.line1")); list.add(Component.translatable("tooltip.primogemcraft.nagadus_emerald_shovel.line2")); list.add(Component.translatable("tooltip.primogemcraft.nagadus_emerald_shovel.line3")); } @Override public InteractionResult useOn(UseOnContext context) { super.useOn(context); var x = context.getClickedPos().getX(); var y = context.getClickedPos().getY(); var z = context.getClickedPos().getZ(); var world = context.getLevel(); var entity = context.getPlayer(); var itemstack = context.getItemInHand(); if (entity.isShiftKeyDown()) { if (itemstack.getItem() == entity.getMainHandItem().getItem()) { entity.swing(InteractionHand.MAIN_HAND, true); } else { entity.swing(InteractionHand.OFF_HAND, true); } entity.getCooldowns().addCooldown(itemstack.getItem(), 10); ItemStack _ist = itemstack; if (_ist.hurt(1, RandomSource.create(), null)) { _ist.shrink(1); _ist.setDamageValue(0); } if (!world.isClientSide()) {
package com.primogemstudio.primogemcraft.items.instances.materials.nagadus; public class NagadusEmeraldShovelItem extends ShovelItem { public NagadusEmeraldShovelItem() { super(new Tier() { public int getUses() { return 1561; } public float getSpeed() { return 1f; } public float getAttackDamageBonus() { return 0f; } public int getLevel() { return 4; } public int getEnchantmentValue() { return 5; } public @NotNull Ingredient getRepairIngredient() { return Ingredient.of(new ItemStack(PrimogemCraftItems.PRIMOGEM_ITEM), new ItemStack(PrimogemCraftItems.NAGADUS_EMERALD_SLIVER_ITEM)); } }, 1, -1f, new Item.Properties().fireResistant()); } @Override public boolean mineBlock(ItemStack itemstack, Level world, BlockState blockstate, BlockPos pos, LivingEntity entity) { boolean retval = super.mineBlock(itemstack, world, blockstate, pos, entity); var x = pos.getX(); var y = pos.getY(); var z = pos.getZ(); if (itemstack.getOrCreateTag().getBoolean("value")) { if (Math.random() < 0.01) { if (Math.random() < 0.5) { if (world instanceof ServerLevel _level) { ItemEntity entityToSpawn = new ItemEntity(_level, x, y, z, new ItemStack(PrimogemCraftBlocks.BLESSING_OF_DENDRO_BLOCK)); entityToSpawn.setPickUpDelay(10); _level.addFreshEntity(entityToSpawn); } } else { world.setBlock(BlockPos.containing(x, y, z), PrimogemCraftBlocks.BLESSING_OF_DENDRO_BLOCK.defaultBlockState(), 3); } } } else { world.setBlock(BlockPos.containing(x, y, z), PrimogemCraftBlocks.BLESSING_OF_DENDRO_BLOCK.defaultBlockState(), 3); itemstack.getOrCreateTag().putBoolean("value", true); } return retval; } @Override public void appendHoverText(ItemStack itemstack, Level world, List<Component> list, TooltipFlag flag) { list.add(Component.translatable("tooltip.primogemcraft.nagadus_emerald_shovel.line1")); list.add(Component.translatable("tooltip.primogemcraft.nagadus_emerald_shovel.line2")); list.add(Component.translatable("tooltip.primogemcraft.nagadus_emerald_shovel.line3")); } @Override public InteractionResult useOn(UseOnContext context) { super.useOn(context); var x = context.getClickedPos().getX(); var y = context.getClickedPos().getY(); var z = context.getClickedPos().getZ(); var world = context.getLevel(); var entity = context.getPlayer(); var itemstack = context.getItemInHand(); if (entity.isShiftKeyDown()) { if (itemstack.getItem() == entity.getMainHandItem().getItem()) { entity.swing(InteractionHand.MAIN_HAND, true); } else { entity.swing(InteractionHand.OFF_HAND, true); } entity.getCooldowns().addCooldown(itemstack.getItem(), 10); ItemStack _ist = itemstack; if (_ist.hurt(1, RandomSource.create(), null)) { _ist.shrink(1); _ist.setDamageValue(0); } if (!world.isClientSide()) {
world.playSound(null, BlockPos.containing(x, y, z), PrimogemCraftSounds.NAGADUS_EMERALD_SHOVEL_ONUSE, SoundSource.NEUTRAL, (float) 0.3, 5);
2
2023-10-15 08:07:06+00:00
16k
turtleisaac/PokEditor
src/main/java/io/github/turtleisaac/pokeditor/gui/editors/data/formats/scripts/field/FieldScriptEditor.java
[ { "identifier": "PokeditorManager", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/PokeditorManager.java", "snippet": "public class PokeditorManager extends PanelManager\n{\n private static final Dimension dimension = new Dimension(1200, 714);\n\n public static final FlatSVGIcon sheetE...
import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.text.*; import io.github.turtleisaac.nds4j.ui.ThemeUtils; import io.github.turtleisaac.pokeditor.formats.GenericFileData; import io.github.turtleisaac.pokeditor.formats.scripts.GenericScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.ScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.LevelScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.antlr4.ScriptDataProducer; import io.github.turtleisaac.pokeditor.formats.text.TextBankData; import io.github.turtleisaac.pokeditor.gui.*; import io.github.turtleisaac.pokeditor.gui.PokeditorManager; import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditor; import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditorPanel; import io.github.turtleisaac.pokeditor.gui.editors.data.EditorDataModel; import io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.*; import io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.ScriptDocument; import io.github.turtleisaac.pokeditor.gui.sheets.tables.FormatModel; import net.miginfocom.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.List;
12,288
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.field; /** * @author turtleisaac */ public class FieldScriptEditor extends DefaultDataEditor<GenericScriptData, FieldScriptEditor.FieldScriptContents> { private DefaultListModel<GenericScriptData.ScriptComponent> levelScriptDataListModel = new DefaultListModel<>(); private DefaultListModel<String> labelDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> actionDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> scriptDisplayListModel = new DefaultListModel<>(); private boolean editMode; private GenericScriptData.ScriptComponent selected; public FieldScriptEditor(List<GenericScriptData> data, List<TextBankData> textBankData) { super(new FieldScriptModel(data, textBankData)); editMode = false; initComponents(); // FieldScriptEditorKit editorKit = new FieldScriptEditorKit(); StyledDocument document = new ScriptDocument(textPane1); textPane1.setDocument(document); textPane1.setBackground(new Color(58, 56, 77)); textPane1.setScrollPane(scrollPane1); textPane1.setForeground(Color.WHITE); levelScriptTypeComboBox.setSelectedIndex(0); paddingCheckbox.setSelected(true); levelScriptList.setModel(levelScriptDataListModel); levelScriptList.setSelectedIndex(-1); levelScriptListValueChanged(null); clearInputFields(); // valueField.addChangeListener(e -> paramFieldTextChange()); // scriptNoField.addChangeListener(e -> paramFieldTextChange()); // variableField.addChangeListener(e -> paramFieldTextChange()); removeButton.setEnabled(false); try { JTextPane numberPane = new JTextPane(); // numberPane.setBackground(textPane1.getBackground()); // numberPane.setForeground(textPane1.getForeground()); textPane1.setLineNumberPane(numberPane); scrollPane1.setRowHeaderView(numberPane); } catch(BadLocationException e) { throw new RuntimeException(e); } setIcons(); } private void setIcons() { addButton.setIcon(PokeditorManager.rowInsertIcon); removeButton.setIcon(PokeditorManager.rowRemoveIcon); confirmButton.setIcon(ThemeUtils.validIcon); discardButton.setIcon(ThemeUtils.reloadIcon); } @Override public void selectedIndexedChanged(int idx, ActionEvent e) { super.selectedIndexedChanged(idx, e);
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.field; /** * @author turtleisaac */ public class FieldScriptEditor extends DefaultDataEditor<GenericScriptData, FieldScriptEditor.FieldScriptContents> { private DefaultListModel<GenericScriptData.ScriptComponent> levelScriptDataListModel = new DefaultListModel<>(); private DefaultListModel<String> labelDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> actionDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> scriptDisplayListModel = new DefaultListModel<>(); private boolean editMode; private GenericScriptData.ScriptComponent selected; public FieldScriptEditor(List<GenericScriptData> data, List<TextBankData> textBankData) { super(new FieldScriptModel(data, textBankData)); editMode = false; initComponents(); // FieldScriptEditorKit editorKit = new FieldScriptEditorKit(); StyledDocument document = new ScriptDocument(textPane1); textPane1.setDocument(document); textPane1.setBackground(new Color(58, 56, 77)); textPane1.setScrollPane(scrollPane1); textPane1.setForeground(Color.WHITE); levelScriptTypeComboBox.setSelectedIndex(0); paddingCheckbox.setSelected(true); levelScriptList.setModel(levelScriptDataListModel); levelScriptList.setSelectedIndex(-1); levelScriptListValueChanged(null); clearInputFields(); // valueField.addChangeListener(e -> paramFieldTextChange()); // scriptNoField.addChangeListener(e -> paramFieldTextChange()); // variableField.addChangeListener(e -> paramFieldTextChange()); removeButton.setEnabled(false); try { JTextPane numberPane = new JTextPane(); // numberPane.setBackground(textPane1.getBackground()); // numberPane.setForeground(textPane1.getForeground()); textPane1.setLineNumberPane(numberPane); scrollPane1.setRowHeaderView(numberPane); } catch(BadLocationException e) { throw new RuntimeException(e); } setIcons(); } private void setIcons() { addButton.setIcon(PokeditorManager.rowInsertIcon); removeButton.setIcon(PokeditorManager.rowRemoveIcon); confirmButton.setIcon(ThemeUtils.validIcon); discardButton.setIcon(ThemeUtils.reloadIcon); } @Override public void selectedIndexedChanged(int idx, ActionEvent e) { super.selectedIndexedChanged(idx, e);
EditorDataModel<FieldScriptContents> model = getModel();
3
2023-10-15 05:00:57+00:00
16k
eclipse-egit/egit
org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/op/CreatePatchOperationTest.java
[ { "identifier": "CreatePatchOperation", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/op/CreatePatchOperation.java", "snippet": "public class CreatePatchOperation implements IEGitOperation {\n\n\t/**\n\t * Diff header format\n\t *\n\t */\n\tpublic enum DiffHeaderFormat {\n\t\t/**\n\t\t * No h...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.File; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.egit.core.op.CreatePatchOperation; import org.eclipse.egit.core.op.CreatePatchOperation.DiffHeaderFormat; import org.eclipse.egit.core.test.GitTestCase; import org.eclipse.egit.core.test.TestProject; import org.eclipse.egit.core.test.TestRepository; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.util.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test;
12,479
/******************************************************************************* * Copyright (c) 2011, 2014 Tasktop Technologies 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 *******************************************************************************/ package org.eclipse.egit.core.test.op; public class CreatePatchOperationTest extends GitTestCase { private static final String SIMPLE_GIT_PATCH_CONTENT = "From ca644a113ac60405e54731330be7879f6a36199c Sat, 23 Jul 2011 20:33:24 -0330\n" + "From: J. Git <j.git@egit.org>\n" + "Date: Sat, 15 Aug 2009 20:12:58 -0330\n" + "Subject: [PATCH] 2nd commit\n" + "\n" + "diff --git a/test-file b/test-file\n" + "index e69de29..af28d38 100644\n" + "--- a/test-file\n" + "+++ b/test-file\n" + "@@ -0,0 +1 @@\n" + "+another line\n"; private static final String SIMPLE_ONELINE_PATCH_CONTENT = "ca644a113ac60405e54731330be7879f6a36199c 2nd commit\n" + "diff --git a/test-file b/test-file\n" + "index e69de29..af28d38 100644\n" + "--- a/test-file\n" + "+++ b/test-file\n" + "@@ -0,0 +1 @@\n" + "+another line\n"; private static final String SIMPLE_PATCH_CONTENT = "diff --git a/test-file b/test-file\n" + "index e69de29..af28d38 100644\n" + "--- a/test-file\n" + "+++ b/test-file\n" + "@@ -0,0 +1 @@\n" + "+another line\n"; private static final String SIMPLE_WORKSPACE_PATCH_CONTENT = "### Eclipse Workspace Patch 1.0\n" + "#P Project-1\n" + "diff --git deleted-file deleted-file\n" + "deleted file mode 100644\n" + "index e69de29..0000000\n" + "--- deleted-file\n" + "+++ /dev/null\n" + "diff --git new-file new-file\n" + "new file mode 100644\n" + "index 0000000..b66ba06\n" + "--- /dev/null\n" + "+++ new-file\n" + "@@ -0,0 +1 @@\n" + "+new content\n" + "diff --git test-file test-file\n" + "index e69de29..af28d38 100644\n" + "--- test-file\n" + "+++ test-file\n" + "@@ -0,0 +1 @@\n" + "+another line\n"; private RevCommit commit; private File file; private TestRepository testRepository; @Override @Before public void setUp() throws Exception { super.setUp(); gitDir = new File(project.getProject().getLocationURI().getPath(), Constants.DOT_GIT); testRepository = new TestRepository(gitDir); testRepository.connect(project.getProject()); file = testRepository.createFile(project.getProject(), "test-file"); commit = testRepository.addAndCommit(project.getProject(), file, "new file"); } @Override @After public void tearDown() throws Exception { testRepository.dispose(); super.tearDown(); } @Test public void testSimpleGitPatch() throws Exception { RevCommit secondCommit = testRepository.appendContentAndCommit( project.getProject(), file, "another line\n", "2nd commit");
/******************************************************************************* * Copyright (c) 2011, 2014 Tasktop Technologies 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 *******************************************************************************/ package org.eclipse.egit.core.test.op; public class CreatePatchOperationTest extends GitTestCase { private static final String SIMPLE_GIT_PATCH_CONTENT = "From ca644a113ac60405e54731330be7879f6a36199c Sat, 23 Jul 2011 20:33:24 -0330\n" + "From: J. Git <j.git@egit.org>\n" + "Date: Sat, 15 Aug 2009 20:12:58 -0330\n" + "Subject: [PATCH] 2nd commit\n" + "\n" + "diff --git a/test-file b/test-file\n" + "index e69de29..af28d38 100644\n" + "--- a/test-file\n" + "+++ b/test-file\n" + "@@ -0,0 +1 @@\n" + "+another line\n"; private static final String SIMPLE_ONELINE_PATCH_CONTENT = "ca644a113ac60405e54731330be7879f6a36199c 2nd commit\n" + "diff --git a/test-file b/test-file\n" + "index e69de29..af28d38 100644\n" + "--- a/test-file\n" + "+++ b/test-file\n" + "@@ -0,0 +1 @@\n" + "+another line\n"; private static final String SIMPLE_PATCH_CONTENT = "diff --git a/test-file b/test-file\n" + "index e69de29..af28d38 100644\n" + "--- a/test-file\n" + "+++ b/test-file\n" + "@@ -0,0 +1 @@\n" + "+another line\n"; private static final String SIMPLE_WORKSPACE_PATCH_CONTENT = "### Eclipse Workspace Patch 1.0\n" + "#P Project-1\n" + "diff --git deleted-file deleted-file\n" + "deleted file mode 100644\n" + "index e69de29..0000000\n" + "--- deleted-file\n" + "+++ /dev/null\n" + "diff --git new-file new-file\n" + "new file mode 100644\n" + "index 0000000..b66ba06\n" + "--- /dev/null\n" + "+++ new-file\n" + "@@ -0,0 +1 @@\n" + "+new content\n" + "diff --git test-file test-file\n" + "index e69de29..af28d38 100644\n" + "--- test-file\n" + "+++ test-file\n" + "@@ -0,0 +1 @@\n" + "+another line\n"; private RevCommit commit; private File file; private TestRepository testRepository; @Override @Before public void setUp() throws Exception { super.setUp(); gitDir = new File(project.getProject().getLocationURI().getPath(), Constants.DOT_GIT); testRepository = new TestRepository(gitDir); testRepository.connect(project.getProject()); file = testRepository.createFile(project.getProject(), "test-file"); commit = testRepository.addAndCommit(project.getProject(), file, "new file"); } @Override @After public void tearDown() throws Exception { testRepository.dispose(); super.tearDown(); } @Test public void testSimpleGitPatch() throws Exception { RevCommit secondCommit = testRepository.appendContentAndCommit( project.getProject(), file, "another line\n", "2nd commit");
CreatePatchOperation operation = new CreatePatchOperation(
0
2023-10-20 15:17:51+00:00
16k
Wind-Gone/Vodka
code/src/main/java/benchmark/synchronize/tasks/BatchQueryTask.java
[ { "identifier": "Triple", "path": "code/src/main/java/bean/Triple.java", "snippet": "@Getter\n@Setter\npublic class Triple<A, B, C> {\n private A first;\n private B second;\n private C third;\n\n public Triple(A first, B second, C third) {\n this.first = first;\n this.second = ...
import java.sql.*; import java.util.*; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.locks.Lock; import bean.Triple; import benchmark.synchronize.components.HTAPCheckInfo; import benchmark.synchronize.components.HTAPCheckType; import config.CommonConfig; import org.apache.commons.math3.util.Pair; import static benchmark.oltp.OLTPClient.*;
12,612
" IN (" + inClause + ")"; } if (dbType == CommonConfig.DB_OCEANBASE && this.isWeakRead) { System.out.println("Isweakread for OB!!!"); checkSql4AP = "SELECT /*+READ_CONSISTENCY(WEAK) */ sum(access_version)" + " FROM vodka_order_line " + " WHERE ol_w_id = ? AND ol_d_id = ? AND ol_o_id = ?;"; } } private String buildInClause(int freshnessDataBound) { long lowerBound = currentTime - freshnessDataBound; List<String> dateStrings = new ArrayList<>(); Iterator<Pair<Long, Long>> iterator = deliveryList.descendingIterator(); while (iterator.hasNext()) { Pair<Long, Long> pair = iterator.next(); if (pair.getKey() <= currentTime) { if (pair.getKey() >= lowerBound) { dateStrings.add("'" + new Timestamp(pair.getValue()) + "'"); } else break; } } if (!dateStrings.isEmpty()) { return String.join(", ", dateStrings); } return "''"; // 默认情况,如果没有匹配项 } @Override public TaskResult runTask(ArrayList<Connection> conns, int threadId) { if (htapCheckQueryNumber.get() <= 0) printFreshnessReport(); System.out.printf("Remain #%d Real-time query\n", htapCheckQueryNumber.decrementAndGet()); int tryNum = 0; boolean pass = true; boolean isApConnErr = false; boolean resultMatch = false; // try { // // prepare sql for tp // stmtTP = conns.get(1).prepareStatement(checkSql4TP); // stmtTP.setInt(1, w_id); // stmtTP.setInt(2, d_id); // stmtTP.setInt(3, o_id); // // prepare sql for ap // stmtAP = conns.get(0).prepareStatement(checkSql4AP); // stmtAP.setInt(1, w_id); // stmtAP.setInt(2, d_id); // stmtAP.setInt(3, o_id); // resultSetTP = stmtTP.executeQuery(); // int resultTP = Integer.MAX_VALUE; // if (resultSetTP.next()) // resultTP = resultSetTP.getInt(1); // if (dbType == CommonConfig.DB_TIDB) { // Statement ps = conns.get(0).createStatement(); // ps.execute(tidbSql); // } // startTime = System.nanoTime(); // if (isWeakRead) { // if (dbType == CommonConfig.DB_OCEANBASE) { // Statement weakStatement = conns.get(0).createStatement(); // weakStatement.execute("SET ob_read_consistency = WEAK;"); // } else if (dbType == CommonConfig.DB_TIDB) { // Statement weakStatement = conns.get(0).createStatement(); // weakStatement.execute("set @@tidb_read_staleness=\"-5\";"); // } // } // while (!resultMatch) { // resultSetAP = stmtAP.executeQuery(); // if (resultSetAP.next()) { // int resultAP = resultSetAP.getInt(1); // if (resultAP >= resultTP) { // System.out.printf("[BATCH_QUERY] [%d] version in AP is [%d], and version in // TP is [%d]", // threadId, resultAP, resultTP); // txnCompleteTime = System.nanoTime(); // resultMatch = true; // } else { // tryNum++; // if (tryNum % 10000 == 0) // System.out.printf( // "[BATCH_QUERY] [%d] version in AP is [%d], and version in TP is [%d], // checksql is [%s]\n", // threadId, resultAP, resultTP, stmtAP.toString() + ";"); // } // } // } // resultSetAP.close(); // stmtAP.close(); // resultSetTP.close(); // stmtTP.close(); // } catch (Exception e) { // e.printStackTrace(); // } System.out.println("Check Done and Start Second Query!"); try { double freshness = 0; double tmpLatency = 0; // double freshness = tryNum == 0 ? 0 // : Math.abs(txnCompleteTime - startTime) / // 1_000_000.0; // double tmpLatency = tryNum == 0 ? Math.abs(txnCompleteTime - startTime) / // 1_000_000.0 : 0; stmtAP = conns.get(0).prepareStatement(batchQuerySql); stmtAP.setInt(1, start_wid); stmtAP.setInt(2, end_wid); Statement weakStatement = conns.get(0).createStatement(); if (dbType == CommonConfig.DB_OCEANBASE && this.isWeakRead) { weakStatement.execute("SET ob_read_consistency = WEAK;"); } startTime = System.nanoTime(); result = stmtAP.executeQuery(); txnCompleteTime = System.nanoTime(); if (result.next()) { System.out.println(result.getString(1)); } System.out.println(batchQuerySql); double latency = Math.abs(txnCompleteTime - startTime) / 1_000_000.0;
package benchmark.synchronize.tasks; public class BatchQueryTask extends Task { // task info private final int o_id; private final int d_id; private final int w_id; private final int start_wid; private final int end_wid; private final long ol_delivery_d; private final int freshnessDataBound; private final long currentTime; public int lFreshLagBound; public int rFreshLagBound; // parallel sample public Lock parallelThreads = null; // datebase statement private PreparedStatement stmtTP; private PreparedStatement stmtAP; private ResultSet resultSetAP; private ResultSet resultSetTP; private String checkSql4TP = "SELECT sum(access_version)" + " FROM vodka_order_line " + " WHERE ol_w_id = ? AND ol_d_id = ? AND ol_o_id = ?;"; private String checkSql4AP = checkSql4TP; private String inClause; private String batchQuerySql; private String tidbSql; private int dbType; private boolean isWeakRead; private int weakReadTime; Random random = new Random(2023); public BatchQueryTask(int o_id, int d_id, int w_id, long ol_delivery_d, int dbType, HTAPCheckInfo htapCheckInfo, long currentTime) { this.taskType = HTAPCheckType.BATCH_QUERY; this.txnCompleteTime = System.currentTimeMillis(); this.o_id = o_id; this.d_id = d_id; this.w_id = w_id; this.ol_delivery_d = ol_delivery_d; this.start_wid = random.nextInt(numWarehouses - htapCheckInfo.warehouseNum + 1); this.end_wid = start_wid + htapCheckInfo.warehouseNum; this.gapTime = htapCheckInfo.gapTime; this.freshnessDataBound = htapCheckInfo.htapCheckFreshnessDataBound; this.lFreshLagBound = htapCheckInfo.lFreshLagBound; this.rFreshLagBound = htapCheckInfo.rFreshLagBound; this.currentTime = currentTime; this.isWeakRead = htapCheckInfo.isWeakRead; this.weakReadTime = htapCheckInfo.weakReadTime; inClause = buildInClause(freshnessDataBound); batchQuerySql = "SELECT /*+READ_CONSISTENCY(WEAK) */ *" + " FROM vodka_order_line" + " WHERE" + " ol_w_id >= ? AND" + " ol_w_id <= ? AND ol_delivery_d " + " IN (" + inClause + ")"; this.dbType = dbType; initSQLs(dbType); } private void initSQLs(int dbType) { if (dbType == CommonConfig.DB_TIDB) { checkSql4AP = "SELECT /*+ read_from_storage(tiflash[vodka_order_line]) */ sum(access_version)" + " FROM vodka_order_line " + " WHERE ol_w_id = ? AND ol_d_id = ? AND ol_o_id = ?;"; if (this.isWeakRead) { checkSql4AP = "SELECT /*+ read_from_storage(tiflash[vodka_order_line]) */ sum(access_version)" + " FROM vodka_order_line AS OF TIMESTAMP TIDB_BOUNDED_STALENESS(NOW() - INTERVAL 5 SECOND, NOW()) " + " WHERE ol_w_id = ? AND ol_d_id = ? AND ol_o_id = ?;"; } tidbSql = "set SESSION tidb_isolation_read_engines = \"tiflash\""; batchQuerySql = "SELECT /*+ read_from_storage(tiflash[vodka_order_line]) */ *" + " FROM vodka_order_line " + " WHERE" + " ol_w_id >= ? AND" + " ol_w_id <= ? AND ol_delivery_d " + " IN (" + inClause + ")"; } if (dbType == CommonConfig.DB_OCEANBASE && this.isWeakRead) { System.out.println("Isweakread for OB!!!"); checkSql4AP = "SELECT /*+READ_CONSISTENCY(WEAK) */ sum(access_version)" + " FROM vodka_order_line " + " WHERE ol_w_id = ? AND ol_d_id = ? AND ol_o_id = ?;"; } } private String buildInClause(int freshnessDataBound) { long lowerBound = currentTime - freshnessDataBound; List<String> dateStrings = new ArrayList<>(); Iterator<Pair<Long, Long>> iterator = deliveryList.descendingIterator(); while (iterator.hasNext()) { Pair<Long, Long> pair = iterator.next(); if (pair.getKey() <= currentTime) { if (pair.getKey() >= lowerBound) { dateStrings.add("'" + new Timestamp(pair.getValue()) + "'"); } else break; } } if (!dateStrings.isEmpty()) { return String.join(", ", dateStrings); } return "''"; // 默认情况,如果没有匹配项 } @Override public TaskResult runTask(ArrayList<Connection> conns, int threadId) { if (htapCheckQueryNumber.get() <= 0) printFreshnessReport(); System.out.printf("Remain #%d Real-time query\n", htapCheckQueryNumber.decrementAndGet()); int tryNum = 0; boolean pass = true; boolean isApConnErr = false; boolean resultMatch = false; // try { // // prepare sql for tp // stmtTP = conns.get(1).prepareStatement(checkSql4TP); // stmtTP.setInt(1, w_id); // stmtTP.setInt(2, d_id); // stmtTP.setInt(3, o_id); // // prepare sql for ap // stmtAP = conns.get(0).prepareStatement(checkSql4AP); // stmtAP.setInt(1, w_id); // stmtAP.setInt(2, d_id); // stmtAP.setInt(3, o_id); // resultSetTP = stmtTP.executeQuery(); // int resultTP = Integer.MAX_VALUE; // if (resultSetTP.next()) // resultTP = resultSetTP.getInt(1); // if (dbType == CommonConfig.DB_TIDB) { // Statement ps = conns.get(0).createStatement(); // ps.execute(tidbSql); // } // startTime = System.nanoTime(); // if (isWeakRead) { // if (dbType == CommonConfig.DB_OCEANBASE) { // Statement weakStatement = conns.get(0).createStatement(); // weakStatement.execute("SET ob_read_consistency = WEAK;"); // } else if (dbType == CommonConfig.DB_TIDB) { // Statement weakStatement = conns.get(0).createStatement(); // weakStatement.execute("set @@tidb_read_staleness=\"-5\";"); // } // } // while (!resultMatch) { // resultSetAP = stmtAP.executeQuery(); // if (resultSetAP.next()) { // int resultAP = resultSetAP.getInt(1); // if (resultAP >= resultTP) { // System.out.printf("[BATCH_QUERY] [%d] version in AP is [%d], and version in // TP is [%d]", // threadId, resultAP, resultTP); // txnCompleteTime = System.nanoTime(); // resultMatch = true; // } else { // tryNum++; // if (tryNum % 10000 == 0) // System.out.printf( // "[BATCH_QUERY] [%d] version in AP is [%d], and version in TP is [%d], // checksql is [%s]\n", // threadId, resultAP, resultTP, stmtAP.toString() + ";"); // } // } // } // resultSetAP.close(); // stmtAP.close(); // resultSetTP.close(); // stmtTP.close(); // } catch (Exception e) { // e.printStackTrace(); // } System.out.println("Check Done and Start Second Query!"); try { double freshness = 0; double tmpLatency = 0; // double freshness = tryNum == 0 ? 0 // : Math.abs(txnCompleteTime - startTime) / // 1_000_000.0; // double tmpLatency = tryNum == 0 ? Math.abs(txnCompleteTime - startTime) / // 1_000_000.0 : 0; stmtAP = conns.get(0).prepareStatement(batchQuerySql); stmtAP.setInt(1, start_wid); stmtAP.setInt(2, end_wid); Statement weakStatement = conns.get(0).createStatement(); if (dbType == CommonConfig.DB_OCEANBASE && this.isWeakRead) { weakStatement.execute("SET ob_read_consistency = WEAK;"); } startTime = System.nanoTime(); result = stmtAP.executeQuery(); txnCompleteTime = System.nanoTime(); if (result.next()) { System.out.println(result.getString(1)); } System.out.println(batchQuerySql); double latency = Math.abs(txnCompleteTime - startTime) / 1_000_000.0;
Triple<Double, Double, Double> freshnessItem = new Triple<>(freshness, latency, tmpLatency);
0
2023-10-22 11:22:32+00:00
16k
Kyrotechnic/KyroClient
Client/src/main/java/me/kyroclient/KyroClient.java
[ { "identifier": "PacketSentEvent", "path": "Client/src/main/java/me/kyroclient/events/PacketSentEvent.java", "snippet": "@Cancelable\npublic class PacketSentEvent extends Event {\n public Packet<?> packet;\n public PacketSentEvent(Packet<?> packet)\n {\n this.packet = packet;\n }\n\n ...
import lombok.SneakyThrows; import me.kyroclient.events.PacketSentEvent; import me.kyroclient.forge.ForgeRegister; import me.kyroclient.forge.ForgeSpoofer; import me.kyroclient.managers.*; import me.kyroclient.modules.Module; import me.kyroclient.modules.client.Capes; import me.kyroclient.modules.client.CustomBrand; import me.kyroclient.modules.client.Tickless; import me.kyroclient.modules.combat.*; import me.kyroclient.modules.garden.CropNuker; import me.kyroclient.modules.garden.FarmingMacro; import me.kyroclient.modules.mining.MiningQOL; import me.kyroclient.modules.misc.*; import me.kyroclient.modules.player.*; import me.kyroclient.modules.render.*; import me.kyroclient.notifications.Notification; import me.kyroclient.util.SkyblockUtils; import me.kyroclient.util.font.Fonts; import me.kyroclient.util.render.BlurUtils; import net.minecraft.client.Minecraft; import net.minecraft.network.play.client.C01PacketChatMessage; import net.minecraft.util.ChatComponentText; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import javax.net.ssl.*; import java.awt.*; import java.lang.reflect.Method; import java.security.SecureRandom; import java.util.List; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.stream.Collectors;
11,070
package me.kyroclient; public class KyroClient { //Vars public static final String MOD_ID = "dankers"; public static String VERSION = "0.2-b3"; public static List<String> changelog; public static ModuleManager moduleManager; public static NotificationManager notificationManager; public static ConfigManager configManager; public static ThemeManager themeManager; public static FriendManager friendManager; public static CapeManager capeManager; public static Minecraft mc; public static boolean isDev = true; public static Color iconColor = new Color(237, 107, 0); public static long gameStarted; public static boolean banned = false; //Module Dependencies public static Gui clickGui; public static NickHider nickHider; public static CropNuker cropNuker; public static Velocity velocity; public static FastPlace fastPlace; public static Modless modless; public static Speed speed; public static AntiBot antiBot; public static Interfaces interfaces; public static Delays delays; public static Hitboxes hitBoxes; public static NoSlow noSlow; public static FreeCam freeCam; public static Giants giants; public static Animations animations; public static Aura aura; public static AutoBlock autoBlock; public static PopupAnimation popupAnimation; public static GuiMove guiMove; public static Camera camera; public static Reach reach; public static InventoryDisplay inventoryDisplay; public static LoreDisplay loreDisplay; public static FarmingMacro macro; public static MiningQOL miningQol; public static Tickless tickless; public static TeleportExploit teleportExploit; public static Hud hud; public static FakeLag fakeLag; public static Proxy proxy;
package me.kyroclient; public class KyroClient { //Vars public static final String MOD_ID = "dankers"; public static String VERSION = "0.2-b3"; public static List<String> changelog; public static ModuleManager moduleManager; public static NotificationManager notificationManager; public static ConfigManager configManager; public static ThemeManager themeManager; public static FriendManager friendManager; public static CapeManager capeManager; public static Minecraft mc; public static boolean isDev = true; public static Color iconColor = new Color(237, 107, 0); public static long gameStarted; public static boolean banned = false; //Module Dependencies public static Gui clickGui; public static NickHider nickHider; public static CropNuker cropNuker; public static Velocity velocity; public static FastPlace fastPlace; public static Modless modless; public static Speed speed; public static AntiBot antiBot; public static Interfaces interfaces; public static Delays delays; public static Hitboxes hitBoxes; public static NoSlow noSlow; public static FreeCam freeCam; public static Giants giants; public static Animations animations; public static Aura aura; public static AutoBlock autoBlock; public static PopupAnimation popupAnimation; public static GuiMove guiMove; public static Camera camera; public static Reach reach; public static InventoryDisplay inventoryDisplay; public static LoreDisplay loreDisplay; public static FarmingMacro macro; public static MiningQOL miningQol; public static Tickless tickless; public static TeleportExploit teleportExploit; public static Hud hud; public static FakeLag fakeLag; public static Proxy proxy;
public static CustomBrand customBrand;
5
2023-10-15 16:24:51+00:00
16k
AstroDev2023/2023-studio-1-but-better
source/core/src/main/com/csse3200/game/areas/GameArea.java
[ { "identifier": "GameMap", "path": "source/core/src/main/com/csse3200/game/areas/terrain/GameMap.java", "snippet": "public class GameMap {\n\t/**\n\t * The terrainFactory used for creating the game map\n\t */\n\tprivate final TerrainFactory terrainFactory;\n\t/**\n\t * The TiledMap that stores the creat...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.GridPoint2; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.csse3200.game.areas.terrain.GameMap; import com.csse3200.game.areas.terrain.TerrainComponent; import com.csse3200.game.areas.weather.ClimateController; import com.csse3200.game.entities.Entity; import com.csse3200.game.entities.EntityType; import com.csse3200.game.services.ServiceLocator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
13,912
package com.csse3200.game.areas; /** * Represents an area in the game, such as a level, indoor area, etc. An area has a terrain and * other entities to spawn on that terrain. * * <p>Support for enabling/disabling game areas could be added by making this a Component instead. */ public abstract class GameArea implements Disposable { protected TerrainComponent terrain; protected List<Entity> areaEntities; private static final Logger logger = LoggerFactory.getLogger(GameArea.class); private Entity player; private Entity tractor; private final ArrayList<EntityType> loadableTypes = new ArrayList<>(Arrays.asList(EntityType.TILE, EntityType.COW, EntityType.CHICKEN, EntityType.ASTROLOTL, EntityType.PLANT, EntityType.OXYGEN_EATER, EntityType.SHIP_DEBRIS, EntityType.SHIP, EntityType.SHIP_PART_TILE, EntityType.SPRINKLER, EntityType.PUMP, EntityType.FENCE, EntityType.LIGHT, EntityType.GATE, EntityType.CHEST, EntityType.DRAGONFLY, EntityType.BAT, EntityType.TRACTOR, EntityType.GOLDEN_STATUE, EntityType.SHIP_EATER, EntityType.FIRE_FLIES)); protected GameArea() { areaEntities = new ArrayList<>(); } /** * Create the game area in the world. */ public abstract void create(); /** * Dispose of all internal entities in the area */ public void dispose() { logger.debug("Running dispose; Disposes all internal entities in GameArea"); for (Entity entity : areaEntities) { entity.dispose(); } } /** * Spawn entity at its current position * * @param entity Entity (not yet registered) */ public void spawnEntity(Entity entity) { areaEntities.add(entity); ServiceLocator.getEntityService().register(entity); } /** * de-spawn entity at its current position * * @param entity Entity (not yet registered) */ protected void deSpawnEntity(Entity entity) { areaEntities.remove(entity); } /** * Spawn entity on a given tile. Requires the terrain to be set first. * * @param entity Entity (not yet registered) * @param tilePos tile position to spawn at * @param centerX true to center entity X on the tile, false to align the bottom left corner * @param centerY true to center entity Y on the tile, false to align the bottom left corner */ public void spawnEntityAt(Entity entity, GridPoint2 tilePos, boolean centerX, boolean centerY) { Vector2 worldPos = terrain.tileToWorldPosition(tilePos); float tileSize = terrain.getTileSize(); if (centerX) { worldPos.x += (tileSize / 2) - entity.getCenterPosition().x; } if (centerY) { worldPos.y += (tileSize / 2) - entity.getCenterPosition().y; } entity.setPosition(worldPos); spawnEntity(entity); } public void removeEntity(Entity entity) { entity.setEnabled(false); areaEntities.remove(entity); Gdx.app.postRunnable(entity::dispose); } /** * Loops through the games npcs and removes them. Removes all * animals, crop tiles, and plants from the game. * * @param entities Array of entities currently in game. */ public void removeLoadableEntities(Array<Entity> entities) { logger.debug("Removing all loadable entities"); ArrayList<EntityType> placeableTypes = new ArrayList<>(Arrays.asList(EntityType.TILE, EntityType.CHEST, EntityType.FENCE, EntityType.LIGHT, EntityType.GATE, EntityType.SPRINKLER, EntityType.SHIP_DEBRIS, EntityType.SHIP_PART_TILE, EntityType.PUMP, EntityType.GOLDEN_STATUE, EntityType.SHIP_EATER)); for (Entity e : entities) { if (loadableTypes.contains(e.getType())) { if (placeableTypes.contains(e.getType()) && getMap() != null) { getMap().getTile(e.getPosition()).removeOccupant(); } removeEntity(e); } } } public Entity getPlayer() { return player; } public abstract ClimateController getClimateController(); public Entity getTractor() { return tractor; }
package com.csse3200.game.areas; /** * Represents an area in the game, such as a level, indoor area, etc. An area has a terrain and * other entities to spawn on that terrain. * * <p>Support for enabling/disabling game areas could be added by making this a Component instead. */ public abstract class GameArea implements Disposable { protected TerrainComponent terrain; protected List<Entity> areaEntities; private static final Logger logger = LoggerFactory.getLogger(GameArea.class); private Entity player; private Entity tractor; private final ArrayList<EntityType> loadableTypes = new ArrayList<>(Arrays.asList(EntityType.TILE, EntityType.COW, EntityType.CHICKEN, EntityType.ASTROLOTL, EntityType.PLANT, EntityType.OXYGEN_EATER, EntityType.SHIP_DEBRIS, EntityType.SHIP, EntityType.SHIP_PART_TILE, EntityType.SPRINKLER, EntityType.PUMP, EntityType.FENCE, EntityType.LIGHT, EntityType.GATE, EntityType.CHEST, EntityType.DRAGONFLY, EntityType.BAT, EntityType.TRACTOR, EntityType.GOLDEN_STATUE, EntityType.SHIP_EATER, EntityType.FIRE_FLIES)); protected GameArea() { areaEntities = new ArrayList<>(); } /** * Create the game area in the world. */ public abstract void create(); /** * Dispose of all internal entities in the area */ public void dispose() { logger.debug("Running dispose; Disposes all internal entities in GameArea"); for (Entity entity : areaEntities) { entity.dispose(); } } /** * Spawn entity at its current position * * @param entity Entity (not yet registered) */ public void spawnEntity(Entity entity) { areaEntities.add(entity); ServiceLocator.getEntityService().register(entity); } /** * de-spawn entity at its current position * * @param entity Entity (not yet registered) */ protected void deSpawnEntity(Entity entity) { areaEntities.remove(entity); } /** * Spawn entity on a given tile. Requires the terrain to be set first. * * @param entity Entity (not yet registered) * @param tilePos tile position to spawn at * @param centerX true to center entity X on the tile, false to align the bottom left corner * @param centerY true to center entity Y on the tile, false to align the bottom left corner */ public void spawnEntityAt(Entity entity, GridPoint2 tilePos, boolean centerX, boolean centerY) { Vector2 worldPos = terrain.tileToWorldPosition(tilePos); float tileSize = terrain.getTileSize(); if (centerX) { worldPos.x += (tileSize / 2) - entity.getCenterPosition().x; } if (centerY) { worldPos.y += (tileSize / 2) - entity.getCenterPosition().y; } entity.setPosition(worldPos); spawnEntity(entity); } public void removeEntity(Entity entity) { entity.setEnabled(false); areaEntities.remove(entity); Gdx.app.postRunnable(entity::dispose); } /** * Loops through the games npcs and removes them. Removes all * animals, crop tiles, and plants from the game. * * @param entities Array of entities currently in game. */ public void removeLoadableEntities(Array<Entity> entities) { logger.debug("Removing all loadable entities"); ArrayList<EntityType> placeableTypes = new ArrayList<>(Arrays.asList(EntityType.TILE, EntityType.CHEST, EntityType.FENCE, EntityType.LIGHT, EntityType.GATE, EntityType.SPRINKLER, EntityType.SHIP_DEBRIS, EntityType.SHIP_PART_TILE, EntityType.PUMP, EntityType.GOLDEN_STATUE, EntityType.SHIP_EATER)); for (Entity e : entities) { if (loadableTypes.contains(e.getType())) { if (placeableTypes.contains(e.getType()) && getMap() != null) { getMap().getTile(e.getPosition()).removeOccupant(); } removeEntity(e); } } } public Entity getPlayer() { return player; } public abstract ClimateController getClimateController(); public Entity getTractor() { return tractor; }
public abstract GameMap getMap();
0
2023-10-17 22:34:04+00:00
16k
moeinfatehi/PassiveDigger
src/burp/BurpExtender.java
[ { "identifier": "PassiveAnalyzer", "path": "src/PassiveDigger/PassiveAnalyzer.java", "snippet": "public class PassiveAnalyzer extends javax.swing.JPanel implements burp.IHttpListener{\n private static String extension_name=\"Analyzer\";\n private static Scanner sc;\n public static List<vulnerab...
import PassiveDigger.PassiveAnalyzer; import java.io.PrintWriter; import javax.swing.*; import PassiveDigger.menuItem; import PassiveDigger.tab;
11,008
package burp; public class BurpExtender extends JPanel implements IBurpExtender { public static IBurpExtenderCallbacks callbacks; static JScrollPane frame; public static PrintWriter output; public static String project_Name="PassiveDigger"; private static final String project_Version="2.0.0"; public BurpExtender() { // this.historyModel = (DefaultTableModel)mainPanel.historyTable.getModel(); } @Override public void registerExtenderCallbacks(final IBurpExtenderCallbacks callbacks) { // keep a reference to our callbacks object this.callbacks = callbacks; callbacks.registerHttpListener(new PassiveAnalyzer()); output = new PrintWriter(callbacks.getStdout(), true); // create our UI SwingUtilities.invokeLater(new Runnable() { @Override public void run() { initComponents(); // customize our UI components
package burp; public class BurpExtender extends JPanel implements IBurpExtender { public static IBurpExtenderCallbacks callbacks; static JScrollPane frame; public static PrintWriter output; public static String project_Name="PassiveDigger"; private static final String project_Version="2.0.0"; public BurpExtender() { // this.historyModel = (DefaultTableModel)mainPanel.historyTable.getModel(); } @Override public void registerExtenderCallbacks(final IBurpExtenderCallbacks callbacks) { // keep a reference to our callbacks object this.callbacks = callbacks; callbacks.registerHttpListener(new PassiveAnalyzer()); output = new PrintWriter(callbacks.getStdout(), true); // create our UI SwingUtilities.invokeLater(new Runnable() { @Override public void run() { initComponents(); // customize our UI components
callbacks.customizeUiComponent(tab.panel);
2
2023-10-23 12:13:00+00:00
16k
RoessinghResearch/senseeact
SenSeeActServiceLib/src/main/java/nl/rrd/senseeact/service/controller/CommonCrudController.java
[ { "identifier": "ErrorCode", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/exception/ErrorCode.java", "snippet": "public class ErrorCode {\n\tpublic static final String AUTH_TOKEN_NOT_FOUND = \"AUTH_TOKEN_NOT_FOUND\";\n\tpublic static final String AUTH_TOKEN_INVALID = \"AUTH_TOKEN_INVAL...
import nl.rrd.utils.datetime.DateTimeUtils; import nl.rrd.senseeact.client.exception.ErrorCode; import nl.rrd.senseeact.client.exception.HttpError; import nl.rrd.senseeact.client.model.User; import nl.rrd.senseeact.client.model.sample.LocalTimeSample; import nl.rrd.senseeact.client.model.sample.Sample; import nl.rrd.senseeact.client.model.sample.UTCSample; import nl.rrd.senseeact.dao.DatabaseObject; import nl.rrd.senseeact.service.exception.BadRequestException; import nl.rrd.senseeact.service.exception.HttpException; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Map;
11,587
package nl.rrd.senseeact.service.controller; public class CommonCrudController { /** * Validates the time fields of a record written by a user. If the data * class of the table is a {@link Sample Sample}, it ensures that * "localTime" is set. If the data class is a {@link UTCSample UTCSample}, * it also ensures that "utcTime" and "timezone" are set. For any of these * fields that were set, this method validates the values. * * @param subject the subject user * @param record the record * @param map the original data map contained field utcTime * @throws HttpException if the sample has invalid values */ public static void validateWriteRecordTime(User subject,
package nl.rrd.senseeact.service.controller; public class CommonCrudController { /** * Validates the time fields of a record written by a user. If the data * class of the table is a {@link Sample Sample}, it ensures that * "localTime" is set. If the data class is a {@link UTCSample UTCSample}, * it also ensures that "utcTime" and "timezone" are set. For any of these * fields that were set, this method validates the values. * * @param subject the subject user * @param record the record * @param map the original data map contained field utcTime * @throws HttpException if the sample has invalid values */ public static void validateWriteRecordTime(User subject,
DatabaseObject record, Map<?,?> map) throws HttpException {
6
2023-10-24 09:36:50+00:00
16k
Spectrum3847/SpectrumTraining
src/main/java/frc/robot/swerve/Swerve.java
[ { "identifier": "Robot", "path": "src/main/java/frc/robot/Robot.java", "snippet": "public class Robot extends LoggedRobot {\n public static RobotConfig config;\n public static RobotTelemetry telemetry;\n\n /** Create a single static instance of all of your subsystems */\n public static Train...
import edu.wpi.first.math.Matrix; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.math.numbers.N1; import edu.wpi.first.math.numbers.N3; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Subsystem; import frc.robot.Robot; import frc.robot.RobotTelemetry; import frc.robot.swerve.configs.MUSICDISC2023; import frc.robot.swerve.configs.NOTEBLOCK2023; import frc.spectrumLib.swerve.Drivetrain; import frc.spectrumLib.swerve.Drivetrain.DriveState; import frc.spectrumLib.swerve.Request; import frc.spectrumLib.swerve.config.SwerveConfig; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.function.DoubleSupplier; import java.util.function.Supplier; import org.littletonrobotics.junction.Logger;
11,550
package frc.robot.swerve; public class Swerve implements Subsystem { public final SwerveConfig config; private final Drivetrain drivetrain; private final RotationController rotationController; private double OdometryUpdateFrequency = 250; private double targetHeading = 0; private ReadWriteLock m_stateLock = new ReentrantReadWriteLock(); private SwerveModuleState[] Setpoints = new SwerveModuleState[] {}; public Swerve() { RobotTelemetry.print("Swerve Subsystem Starting: "); // Choose the correct swerve configuration
package frc.robot.swerve; public class Swerve implements Subsystem { public final SwerveConfig config; private final Drivetrain drivetrain; private final RotationController rotationController; private double OdometryUpdateFrequency = 250; private double targetHeading = 0; private ReadWriteLock m_stateLock = new ReentrantReadWriteLock(); private SwerveModuleState[] Setpoints = new SwerveModuleState[] {}; public Swerve() { RobotTelemetry.print("Swerve Subsystem Starting: "); // Choose the correct swerve configuration
switch (Robot.config.getRobotType()) {
0
2023-10-23 17:01:53+00:00
16k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/cases/indicators/CaseIndicatorsService.java
[ { "identifier": "Messages", "path": "src/main/java/org/msh/etbm/commons/Messages.java", "snippet": "@Component\npublic class Messages {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(Messages.class);\n\n public static final String NOT_UNIQUE = \"NotUnique\";\n public static fi...
import org.apache.commons.collections.map.HashedMap; import org.msh.etbm.commons.Messages; import org.msh.etbm.commons.entities.EntityValidationException; import org.msh.etbm.commons.filters.Filter; import org.msh.etbm.commons.filters.FilterGroupData; import org.msh.etbm.commons.indicators.IndicatorGenerator; import org.msh.etbm.commons.indicators.IndicatorRequest; import org.msh.etbm.commons.indicators.indicator.IndicatorDataTable; import org.msh.etbm.commons.indicators.indicator.client.IndicatorData; import org.msh.etbm.commons.indicators.indicator.client.IndicatorDataConverter; import org.msh.etbm.commons.indicators.variables.VariableGroupData; import org.msh.etbm.commons.sqlquery.SQLQueryBuilder; import org.msh.etbm.services.cases.filters.CaseFilters; import org.msh.etbm.services.cases.filters.impl.ScopeFilter; import org.msh.etbm.services.cases.filters.impl.ScopeFilterValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.sql.DataSource; import javax.validation.Valid; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
13,729
package org.msh.etbm.services.cases.indicators; /** * Generates case indicators * * Created by rmemoria on 10/9/16. */ @Service public class CaseIndicatorsService { @Autowired CaseFilters caseFilters; @Autowired DataSource dataSource; @Autowired Messages messages; @Autowired IndicatorGenerator indicatorGenerator; /** * Generate initialization data for a client to request indicators * @return */ public CaseIndicatorInitResponse getInitData() { List<FilterGroupData> filters = caseFilters.getFiltersData(); List<VariableGroupData> variables = caseFilters.getVariablesData(); CaseIndicatorInitResponse res = new CaseIndicatorInitResponse(); res.setFilters(filters); res.setVariables(variables); return res; } /** * Generate a new case indicator based on the request * @param req the instance of {@link CaseIndicatorRequest} containing the indicator request * @return return the indicator data */ public CaseIndicatorResponse execute(@Valid CaseIndicatorRequest req) { IndicatorRequest indReq = new IndicatorRequest(); SQLQueryBuilder builder = new SQLQueryBuilder("tbcase"); // add named joins to be used throughout the queries builder.addNamedJoin("patient", "patient", "patient.id = tbcase.patient_id"); builder.addNamedJoin("ownerUnit", "unit", "$this.id = tbcase.owner_unit_id"); builder.addNamedJoin("ownerAdminUnit", "administrativeunit", "$this.id = ownerUnit.adminunit_id"); builder.addNamedJoin("notifUnit", "unit", "$this.id = tbcase.notification_unit_id"); builder.addNamedJoin("regimen", "regimen", "$this.id = tbcase.regimen_id"); builder.addNamedJoin("prescribedmedicine", "prescribedmedicine", "$this.case_id = tbcase.id"); indReq.setQueryBuilder(builder); // get list of column variables if (req.getColumnVariables() != null) { indReq.setColumnVariables(req.getColumnVariables() .stream() .map(vname -> caseFilters.variableById(vname)) .collect(Collectors.toList())); } // get list of row variables if (req.getRowVariables() != null) { indReq.setRowVariables(req.getRowVariables() .stream() .map(vname -> caseFilters.variableById(vname)) .collect(Collectors.toList())); } // set the filters Map<Filter, Object> fvalues = new HashedMap(); // add restrictions by scope addScopeRestriction(fvalues, req); if (req.getFilters() != null) { for (Map.Entry<String, Object> entry: req.getFilters().entrySet()) { Filter filter = caseFilters.filterById(entry.getKey()); if (filter == null) { throw new EntityValidationException(req, "filters", "Filter not found: " + entry.getKey(), null); } fvalues.put(filter, entry.getValue()); } } indReq.setFilterValues(fvalues); indReq.setColumnTotal(true); indReq.setRowTotal(true); IndicatorDataTable indDataTable = indicatorGenerator.execute(indReq, dataSource, messages);
package org.msh.etbm.services.cases.indicators; /** * Generates case indicators * * Created by rmemoria on 10/9/16. */ @Service public class CaseIndicatorsService { @Autowired CaseFilters caseFilters; @Autowired DataSource dataSource; @Autowired Messages messages; @Autowired IndicatorGenerator indicatorGenerator; /** * Generate initialization data for a client to request indicators * @return */ public CaseIndicatorInitResponse getInitData() { List<FilterGroupData> filters = caseFilters.getFiltersData(); List<VariableGroupData> variables = caseFilters.getVariablesData(); CaseIndicatorInitResponse res = new CaseIndicatorInitResponse(); res.setFilters(filters); res.setVariables(variables); return res; } /** * Generate a new case indicator based on the request * @param req the instance of {@link CaseIndicatorRequest} containing the indicator request * @return return the indicator data */ public CaseIndicatorResponse execute(@Valid CaseIndicatorRequest req) { IndicatorRequest indReq = new IndicatorRequest(); SQLQueryBuilder builder = new SQLQueryBuilder("tbcase"); // add named joins to be used throughout the queries builder.addNamedJoin("patient", "patient", "patient.id = tbcase.patient_id"); builder.addNamedJoin("ownerUnit", "unit", "$this.id = tbcase.owner_unit_id"); builder.addNamedJoin("ownerAdminUnit", "administrativeunit", "$this.id = ownerUnit.adminunit_id"); builder.addNamedJoin("notifUnit", "unit", "$this.id = tbcase.notification_unit_id"); builder.addNamedJoin("regimen", "regimen", "$this.id = tbcase.regimen_id"); builder.addNamedJoin("prescribedmedicine", "prescribedmedicine", "$this.case_id = tbcase.id"); indReq.setQueryBuilder(builder); // get list of column variables if (req.getColumnVariables() != null) { indReq.setColumnVariables(req.getColumnVariables() .stream() .map(vname -> caseFilters.variableById(vname)) .collect(Collectors.toList())); } // get list of row variables if (req.getRowVariables() != null) { indReq.setRowVariables(req.getRowVariables() .stream() .map(vname -> caseFilters.variableById(vname)) .collect(Collectors.toList())); } // set the filters Map<Filter, Object> fvalues = new HashedMap(); // add restrictions by scope addScopeRestriction(fvalues, req); if (req.getFilters() != null) { for (Map.Entry<String, Object> entry: req.getFilters().entrySet()) { Filter filter = caseFilters.filterById(entry.getKey()); if (filter == null) { throw new EntityValidationException(req, "filters", "Filter not found: " + entry.getKey(), null); } fvalues.put(filter, entry.getValue()); } } indReq.setFilterValues(fvalues); indReq.setColumnTotal(true); indReq.setRowTotal(true); IndicatorDataTable indDataTable = indicatorGenerator.execute(indReq, dataSource, messages);
IndicatorData data = IndicatorDataConverter.convertFromDataTableIndicator(indDataTable);
8
2023-10-23 13:47:54+00:00
16k
weibocom/rill-flow
rill-flow-impl/src/main/java/com/weibo/rill/flow/impl/statistic/TenantTaskStatisticImpl.java
[ { "identifier": "ProfileType", "path": "rill-flow-common/src/main/java/com/weibo/rill/flow/common/model/ProfileType.java", "snippet": "public class ProfileType {\n private final String type;\n private final long interval1;\n private final long interval2;\n private final long interval3;\n ...
import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Maps; import com.weibo.rill.flow.common.model.ProfileType; import com.weibo.rill.flow.impl.redis.JedisFlowClient; import com.weibo.rill.flow.interfaces.model.resource.Resource; import com.weibo.rill.flow.interfaces.model.task.FunctionTask; import com.weibo.rill.flow.interfaces.model.task.TaskInfo; import com.weibo.rill.flow.interfaces.model.task.TaskInvokeMsg; import com.weibo.rill.flow.olympicene.core.helper.DAGWalkHelper; import com.weibo.rill.flow.olympicene.core.model.NotifyInfo; import com.weibo.rill.flow.olympicene.core.model.dag.DAG; import com.weibo.rill.flow.olympicene.core.model.dag.DAGInfo; import com.weibo.rill.flow.olympicene.core.model.dag.DAGInvokeMsg; import com.weibo.rill.flow.olympicene.core.model.strategy.CallbackConfig; import com.weibo.rill.flow.olympicene.core.model.task.TaskCategory; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.service.dconfs.BizDConfs; import com.weibo.rill.flow.service.statistic.TenantTaskStatistic; import com.weibo.rill.flow.service.storage.RuntimeRedisClients; import com.weibo.rill.flow.service.util.*; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong;
14,120
/* * 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.impl.statistic; @Slf4j @Service public class TenantTaskStatisticImpl implements TenantTaskStatistic { private static final String BUSINESS_AGGREGATE_KEY = "%s_%s"; private static final String BUSINESS_AGGREGATE_TASK_COUNT_FIELD = "%s_task_%s_count"; private static final String BUSINESS_AGGREGATE_RESOURCE_COUNT_FIELD = "%s_resource_%s_count"; private static final String BUSINESS_AGGREGATE_RESOURCE_EXECUTE_TIME_FIELD = "%s_resource_%s_execute_time"; private static final String BUSINESS_AGGREGATE_RESOURCE_WAIT_TIME_FIELD = "%s_resource_%s_wait_time"; private static final int BUSINESS_AGGREGATE_EXPIRE_TIME_IN_SECOND = 180 * 24 * 3600; private static final String FLOW_AGGREGATE_KEY = "fa_%s"; private static final String FLOW_AGGREGATE_RESOURCE_EXECUTE_TIME_FIELD = "%s_execute_time"; private static final String FLOW_AGGREGATE_RESOURCE_WAIT_TIME_FIELD = "%s_wait_time"; private static final ProfileType TENANT = new ProfileType("tenant"); private static final String TENANT_TASK_EXECUTION = "task_%s_%s_%s"; private static final String TENANT_TASK_STASH_EXECUTION = "stash_%s_%s_%s_%s"; private static final String TENANT_FLOW_STASH_EXECUTION = "stash_%s_%s_%s"; private static final String TENANT_STR = "tenant_"; private final Map<Pair<String, String>, AtomicLong> fieldIncrValue = new ConcurrentHashMap<>(); @Autowired private BizDConfs bizDConfs; @Autowired private SwitcherManager switcherManagerImpl; @Autowired @Qualifier("dagDefaultStorageRedisClient") private JedisFlowClient businessAggregateClient; @Autowired @Qualifier("runtimeRedisClients") private RuntimeRedisClients runtimeRedisClients; public void recordTaskRun(long executionTime, String executionId, TaskInfo taskInfo) { taskProfileLog(executionTime, executionId, taskInfo.getName(), "submit"); taskRunCount(executionId, taskInfo); } public void taskProfileLog(long executionTime, String executionId, String taskInfoName, String taskExecutionType) { if (StringUtils.isBlank(taskInfoName) || StringUtils.isBlank(taskExecutionType)) { return; } String baseTaskName = DAGWalkHelper.getInstance().getBaseTaskName(taskInfoName); String serviceId = ExecutionIdUtil.getServiceId(executionId); String businessId = ExecutionIdUtil.getBusinessIdFromServiceId(serviceId); Optional.ofNullable(bizDConfs.getTenantDefinedTaskInvokeProfileLog()) .map(it -> it.get(businessId)) .filter(it -> it.contains(baseTaskName)) .ifPresent(it -> { String name = String.format(TENANT_TASK_EXECUTION, serviceId, baseTaskName, taskExecutionType); ProfileUtil.accessStatistic(TENANT, name, System.currentTimeMillis(), executionTime); // 记录prometheus PrometheusUtil.statisticsTotalTime(PrometheusActions.METER_PREFIX + TENANT_STR + name, executionTime); }); } public void recordTaskStashProfileLog(long executionTime, String executionId, String taskInfoName, String stashType, boolean isSuccess) { if (StringUtils.isBlank(taskInfoName) || StringUtils.isBlank(stashType)) { return; } String baseTaskName = DAGWalkHelper.getInstance().getBaseTaskName(taskInfoName); String serviceId = ExecutionIdUtil.getServiceId(executionId); String name = String.format(TENANT_TASK_STASH_EXECUTION, serviceId, baseTaskName, stashType, isSuccess ? "success" : "fail"); ProfileUtil.accessStatistic(TENANT, name, System.currentTimeMillis(), executionTime); // 记录prometheus PrometheusUtil.statisticsTotalTime(PrometheusActions.METER_PREFIX + TENANT_STR + name, executionTime); } public void recordFlowStashProfileLog(long executionTime, String executionId, String stashType, boolean isSuccess) { if (StringUtils.isBlank(executionId)) { return; } String serviceId = ExecutionIdUtil.getServiceId(executionId); String name = String.format(TENANT_FLOW_STASH_EXECUTION, serviceId, stashType, isSuccess ? "success" : "fail"); ProfileUtil.accessStatistic(TENANT, name, System.currentTimeMillis(), executionTime); // 记录prometheus PrometheusUtil.statisticsTotalTime(PrometheusActions.METER_PREFIX + TENANT_STR + name, executionTime); } private void taskRunCount(String executionId, TaskInfo taskInfo) { try { String businessKey = buildBusinessKey(executionId); String taskCategory = taskInfo.getTask().getCategory(); String serviceId = ExecutionIdUtil.getServiceId(executionId); String taskCountField = buildBusinessTaskCountField(serviceId, taskCategory); AtomicLong taskCountIncr = getIncrValue(Pair.of(businessKey, taskCountField)); taskCountIncr.incrementAndGet(); if (Objects.equals(taskCategory, TaskCategory.FUNCTION.getValue())) {
/* * 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.impl.statistic; @Slf4j @Service public class TenantTaskStatisticImpl implements TenantTaskStatistic { private static final String BUSINESS_AGGREGATE_KEY = "%s_%s"; private static final String BUSINESS_AGGREGATE_TASK_COUNT_FIELD = "%s_task_%s_count"; private static final String BUSINESS_AGGREGATE_RESOURCE_COUNT_FIELD = "%s_resource_%s_count"; private static final String BUSINESS_AGGREGATE_RESOURCE_EXECUTE_TIME_FIELD = "%s_resource_%s_execute_time"; private static final String BUSINESS_AGGREGATE_RESOURCE_WAIT_TIME_FIELD = "%s_resource_%s_wait_time"; private static final int BUSINESS_AGGREGATE_EXPIRE_TIME_IN_SECOND = 180 * 24 * 3600; private static final String FLOW_AGGREGATE_KEY = "fa_%s"; private static final String FLOW_AGGREGATE_RESOURCE_EXECUTE_TIME_FIELD = "%s_execute_time"; private static final String FLOW_AGGREGATE_RESOURCE_WAIT_TIME_FIELD = "%s_wait_time"; private static final ProfileType TENANT = new ProfileType("tenant"); private static final String TENANT_TASK_EXECUTION = "task_%s_%s_%s"; private static final String TENANT_TASK_STASH_EXECUTION = "stash_%s_%s_%s_%s"; private static final String TENANT_FLOW_STASH_EXECUTION = "stash_%s_%s_%s"; private static final String TENANT_STR = "tenant_"; private final Map<Pair<String, String>, AtomicLong> fieldIncrValue = new ConcurrentHashMap<>(); @Autowired private BizDConfs bizDConfs; @Autowired private SwitcherManager switcherManagerImpl; @Autowired @Qualifier("dagDefaultStorageRedisClient") private JedisFlowClient businessAggregateClient; @Autowired @Qualifier("runtimeRedisClients") private RuntimeRedisClients runtimeRedisClients; public void recordTaskRun(long executionTime, String executionId, TaskInfo taskInfo) { taskProfileLog(executionTime, executionId, taskInfo.getName(), "submit"); taskRunCount(executionId, taskInfo); } public void taskProfileLog(long executionTime, String executionId, String taskInfoName, String taskExecutionType) { if (StringUtils.isBlank(taskInfoName) || StringUtils.isBlank(taskExecutionType)) { return; } String baseTaskName = DAGWalkHelper.getInstance().getBaseTaskName(taskInfoName); String serviceId = ExecutionIdUtil.getServiceId(executionId); String businessId = ExecutionIdUtil.getBusinessIdFromServiceId(serviceId); Optional.ofNullable(bizDConfs.getTenantDefinedTaskInvokeProfileLog()) .map(it -> it.get(businessId)) .filter(it -> it.contains(baseTaskName)) .ifPresent(it -> { String name = String.format(TENANT_TASK_EXECUTION, serviceId, baseTaskName, taskExecutionType); ProfileUtil.accessStatistic(TENANT, name, System.currentTimeMillis(), executionTime); // 记录prometheus PrometheusUtil.statisticsTotalTime(PrometheusActions.METER_PREFIX + TENANT_STR + name, executionTime); }); } public void recordTaskStashProfileLog(long executionTime, String executionId, String taskInfoName, String stashType, boolean isSuccess) { if (StringUtils.isBlank(taskInfoName) || StringUtils.isBlank(stashType)) { return; } String baseTaskName = DAGWalkHelper.getInstance().getBaseTaskName(taskInfoName); String serviceId = ExecutionIdUtil.getServiceId(executionId); String name = String.format(TENANT_TASK_STASH_EXECUTION, serviceId, baseTaskName, stashType, isSuccess ? "success" : "fail"); ProfileUtil.accessStatistic(TENANT, name, System.currentTimeMillis(), executionTime); // 记录prometheus PrometheusUtil.statisticsTotalTime(PrometheusActions.METER_PREFIX + TENANT_STR + name, executionTime); } public void recordFlowStashProfileLog(long executionTime, String executionId, String stashType, boolean isSuccess) { if (StringUtils.isBlank(executionId)) { return; } String serviceId = ExecutionIdUtil.getServiceId(executionId); String name = String.format(TENANT_FLOW_STASH_EXECUTION, serviceId, stashType, isSuccess ? "success" : "fail"); ProfileUtil.accessStatistic(TENANT, name, System.currentTimeMillis(), executionTime); // 记录prometheus PrometheusUtil.statisticsTotalTime(PrometheusActions.METER_PREFIX + TENANT_STR + name, executionTime); } private void taskRunCount(String executionId, TaskInfo taskInfo) { try { String businessKey = buildBusinessKey(executionId); String taskCategory = taskInfo.getTask().getCategory(); String serviceId = ExecutionIdUtil.getServiceId(executionId); String taskCountField = buildBusinessTaskCountField(serviceId, taskCategory); AtomicLong taskCountIncr = getIncrValue(Pair.of(businessKey, taskCountField)); taskCountIncr.incrementAndGet(); if (Objects.equals(taskCategory, TaskCategory.FUNCTION.getValue())) {
String resourceName = ((FunctionTask) taskInfo.getTask()).getResourceName();
3
2023-11-03 03:46:01+00:00
16k
aliyun/alibabacloud-compute-nest-saas-boost
boost.server/src/main/java/org/example/service/impl/OrderServiceImpl.java
[ { "identifier": "BaseResult", "path": "boost.common/src/main/java/org/example/common/BaseResult.java", "snippet": "@Data\npublic class BaseResult<T> implements Serializable {\n private static final long serialVersionUID = 5680133981298179266L;\n\n /**\n * Status code.\n */\n protected S...
import com.alicloud.openservices.tablestore.model.search.sort.FieldSort; import com.alicloud.openservices.tablestore.model.search.sort.Sort.Sorter; import com.alicloud.openservices.tablestore.model.search.sort.SortOrder; import com.alipay.api.AlipayApiException; import com.aliyun.computenestsupplier20210521.models.CreateServiceInstanceResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.example.common.BaseResult; import org.example.common.ListResult; import org.example.common.constant.ComputeNestConstants; import org.example.common.constant.OrderOtsConstant; import org.example.common.constant.PayPeriodUnit; import org.example.common.constant.TradeStatus; import org.example.common.dataobject.OrderDO; import org.example.common.dto.OrderDTO; import org.example.common.errorinfo.ErrorInfo; import org.example.common.exception.BizException; import org.example.common.helper.BaseOtsHelper.OtsFilter; import org.example.common.helper.OrderOtsHelper; import org.example.common.helper.ServiceInstanceLifeStyleHelper; import org.example.common.helper.WalletHelper; import org.example.common.model.ServiceMetadataModel; import org.example.common.model.UserInfoModel; import org.example.common.param.CreateOrderParam; import org.example.common.param.GetOrderParam; import org.example.common.param.GetServiceCostParam; import org.example.common.param.GetServiceMetadataParam; import org.example.common.param.ListOrdersParam; import org.example.common.param.RefundOrderParam; import org.example.common.param.UpdateServiceInstanceAttributeParam; import org.example.common.utils.BeanUtil; import org.example.common.utils.DateUtil; import org.example.common.utils.JsonUtil; import org.example.common.utils.UuidUtil; import org.example.service.AlipayService; import org.example.service.OrderService; import org.example.service.ServiceInstanceLifecycleService; import org.example.service.ServiceManager; import org.springframework.beans.BeanUtils; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import static org.example.common.constant.ComputeNestConstants.PAY_PERIOD; import static org.example.common.constant.ComputeNestConstants.PAY_PERIOD_UNIT;
13,031
/* *Copyright (c) Alibaba Group; *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package org.example.service.impl; @Service @Slf4j public class OrderServiceImpl implements OrderService { @Resource private AlipayService alipayService; @Resource private OrderOtsHelper orderOtsHelper; @Resource private WalletHelper walletHelper; @Resource private ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Resource private ServiceManager serviceManager; @Resource private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; private static final Integer DEFAULT_RETENTION_DAYS = 15; @Override public BaseResult<String> createOrder(UserInfoModel userInfoModel, CreateOrderParam param) throws AlipayApiException { Long accountId = userInfoModel.getAid() == null ? null : Long.parseLong(userInfoModel.getAid()); String orderId = UuidUtil.generateOrderId(accountId, param.getType().getValue(), userInfoModel.getSub()); Map<String, Object> nestParameters = (Map<String, Object>) JsonUtil.parseObjectCustom(param.getProductComponents(), Map.class); if (nestParameters == null) { return BaseResult.fail("product components can't be null."); } Long payPeriod = ((Number) nestParameters.remove(PAY_PERIOD)).longValue(); PayPeriodUnit payPeriodUnit = PayPeriodUnit.valueOf(String.valueOf(nestParameters.remove(PAY_PERIOD_UNIT))); Object serviceInstanceIdObj = nestParameters.remove(ComputeNestConstants.SERVICE_INSTANCE_ID); String serviceInstanceId = serviceInstanceIdObj != null ? String.valueOf(serviceInstanceIdObj) : null; GetServiceCostParam getServiceCostParam = new GetServiceCostParam(); BeanUtil.populateObject(nestParameters, getServiceCostParam); getServiceCostParam.setPayPeriodUnit(payPeriodUnit); getServiceCostParam.setPayPeriod(payPeriod); Double cost = serviceManager.getServiceCost(userInfoModel, getServiceCostParam).getData(); if (StringUtils.isEmpty(serviceInstanceId)) { CreateServiceInstanceResponse response = serviceInstanceLifecycleService.createServiceInstance(userInfoModel, nestParameters, true, null); if (response == null || !response.getStatusCode().equals(HttpStatus.OK.value())) { return BaseResult.fail(ErrorInfo.SERVER_UNAVAILABLE); } } String webForm = alipayService.createTransaction(cost, param.getProductName().getDisplayName(), orderId); if (StringUtils.isNotEmpty(webForm)) {
/* *Copyright (c) Alibaba Group; *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package org.example.service.impl; @Service @Slf4j public class OrderServiceImpl implements OrderService { @Resource private AlipayService alipayService; @Resource private OrderOtsHelper orderOtsHelper; @Resource private WalletHelper walletHelper; @Resource private ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Resource private ServiceManager serviceManager; @Resource private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; private static final Integer DEFAULT_RETENTION_DAYS = 15; @Override public BaseResult<String> createOrder(UserInfoModel userInfoModel, CreateOrderParam param) throws AlipayApiException { Long accountId = userInfoModel.getAid() == null ? null : Long.parseLong(userInfoModel.getAid()); String orderId = UuidUtil.generateOrderId(accountId, param.getType().getValue(), userInfoModel.getSub()); Map<String, Object> nestParameters = (Map<String, Object>) JsonUtil.parseObjectCustom(param.getProductComponents(), Map.class); if (nestParameters == null) { return BaseResult.fail("product components can't be null."); } Long payPeriod = ((Number) nestParameters.remove(PAY_PERIOD)).longValue(); PayPeriodUnit payPeriodUnit = PayPeriodUnit.valueOf(String.valueOf(nestParameters.remove(PAY_PERIOD_UNIT))); Object serviceInstanceIdObj = nestParameters.remove(ComputeNestConstants.SERVICE_INSTANCE_ID); String serviceInstanceId = serviceInstanceIdObj != null ? String.valueOf(serviceInstanceIdObj) : null; GetServiceCostParam getServiceCostParam = new GetServiceCostParam(); BeanUtil.populateObject(nestParameters, getServiceCostParam); getServiceCostParam.setPayPeriodUnit(payPeriodUnit); getServiceCostParam.setPayPeriod(payPeriod); Double cost = serviceManager.getServiceCost(userInfoModel, getServiceCostParam).getData(); if (StringUtils.isEmpty(serviceInstanceId)) { CreateServiceInstanceResponse response = serviceInstanceLifecycleService.createServiceInstance(userInfoModel, nestParameters, true, null); if (response == null || !response.getStatusCode().equals(HttpStatus.OK.value())) { return BaseResult.fail(ErrorInfo.SERVER_UNAVAILABLE); } } String webForm = alipayService.createTransaction(cost, param.getProductName().getDisplayName(), orderId); if (StringUtils.isNotEmpty(webForm)) {
OrderDO orderDataObject = createPrePayOrderDataObject(orderId, param, accountId, cost, accountId, getServiceCostParam);
6
2023-11-01 08:19:34+00:00
16k