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
vitozs/api-zelda
zelda-service/src/main/java/com/github/zeldaservice/service/ZeldaService.java
[ { "identifier": "FavoriteRepository", "path": "zelda-service/src/main/java/com/github/zeldaservice/Repository/FavoriteRepository.java", "snippet": "@Repository\npublic interface FavoriteRepository extends JpaRepository<FavoriteGameModel, Long> {\n\n @Query(value = \"select id from jogos where id_jogo...
import com.github.zeldaservice.Repository.FavoriteRepository; import com.github.zeldaservice.infra.exception.GameNotFoundException; import com.github.zeldaservice.infra.exception.SomethingWentWrongException; import com.github.zeldaservice.infra.security.SecurityZeldaFilter; import com.github.zeldaservice.model.RequestModel; import com.github.zeldaservice.model.SingleRequestModel; import com.github.zeldaservice.model.favoriteModel.FavoriteGameModel; import com.github.zeldaservice.model.favoriteModel.ReturnFavoritesModel; import jakarta.servlet.http.HttpServletRequest; import lombok.AllArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.WebClientException;
1,653
package com.github.zeldaservice.service; @Service public class ZeldaService { private final TokenService tokenService; private final FavoriteRepository favoriteRepository; public ZeldaService(TokenService tokenService, FavoriteRepository favoriteRepository) { this.tokenService = tokenService; this.favoriteRepository = favoriteRepository; } private final SecurityZeldaFilter securityZeldaFilter = new SecurityZeldaFilter(); public RequestModel getAllGames() throws SomethingWentWrongException{ try { RequestModel zeldaResponse = WebClient.create("https://zelda.fanapis.com/api/games") .get() .retrieve() .bodyToMono(RequestModel.class) .block(); return zeldaResponse; }catch (WebClientException e){ throw new SomethingWentWrongException("Algo deu errado! Tente novamente mais tarde"); } } public RequestModel getGameByName(String name) throws GameNotFoundException { try { RequestModel zeldaResponse = WebClient.create("https://zelda.fanapis.com/api/games?name=" + name) .get() .retrieve() .bodyToMono(RequestModel.class) .block(); if (zeldaResponse.getCount() == 0){ throw new GameNotFoundException("O Jogo nao foi encontrado"); }else{ return zeldaResponse; } }catch (WebClientException e){ throw new SomethingWentWrongException("Algo deu errado, tente novamente mais tarde"); } } public SingleRequestModel getGameById(String id) throws GameNotFoundException { try { SingleRequestModel zeldaResponse = WebClient.create("https://zelda.fanapis.com/api/games/" + id) .get() .retrieve() .bodyToMono(SingleRequestModel.class) .block(); return zeldaResponse; }catch (WebClientException e){ throw new GameNotFoundException("Id do jogo digitado incorretamente, tente novamente mais tarde"); } }
package com.github.zeldaservice.service; @Service public class ZeldaService { private final TokenService tokenService; private final FavoriteRepository favoriteRepository; public ZeldaService(TokenService tokenService, FavoriteRepository favoriteRepository) { this.tokenService = tokenService; this.favoriteRepository = favoriteRepository; } private final SecurityZeldaFilter securityZeldaFilter = new SecurityZeldaFilter(); public RequestModel getAllGames() throws SomethingWentWrongException{ try { RequestModel zeldaResponse = WebClient.create("https://zelda.fanapis.com/api/games") .get() .retrieve() .bodyToMono(RequestModel.class) .block(); return zeldaResponse; }catch (WebClientException e){ throw new SomethingWentWrongException("Algo deu errado! Tente novamente mais tarde"); } } public RequestModel getGameByName(String name) throws GameNotFoundException { try { RequestModel zeldaResponse = WebClient.create("https://zelda.fanapis.com/api/games?name=" + name) .get() .retrieve() .bodyToMono(RequestModel.class) .block(); if (zeldaResponse.getCount() == 0){ throw new GameNotFoundException("O Jogo nao foi encontrado"); }else{ return zeldaResponse; } }catch (WebClientException e){ throw new SomethingWentWrongException("Algo deu errado, tente novamente mais tarde"); } } public SingleRequestModel getGameById(String id) throws GameNotFoundException { try { SingleRequestModel zeldaResponse = WebClient.create("https://zelda.fanapis.com/api/games/" + id) .get() .retrieve() .bodyToMono(SingleRequestModel.class) .block(); return zeldaResponse; }catch (WebClientException e){ throw new GameNotFoundException("Id do jogo digitado incorretamente, tente novamente mais tarde"); } }
public FavoriteGameModel saveFavoriteGame(String id, HttpServletRequest request) {
6
2023-11-22 00:20:25+00:00
4k
skippy-io/skippy
skippy-junit-common/src/main/java/io/skippy/junit/SkippyAnalysis.java
[ { "identifier": "Profiler", "path": "skippy-common/src/main/java/io/skippy/core/Profiler.java", "snippet": "public final class Profiler {\n\n record InvocationCountAndTime(AtomicInteger invocationCount, AtomicLong time) {};\n\n private static Map<String, InvocationCountAndTime> data = new Concurre...
import io.skippy.core.Profiler; import io.skippy.core.SkippyConstants; import io.skippy.core.SkippyUtils; import java.nio.file.Path; import static io.skippy.junit.SkippyAnalysis.Reason.*;
1,909
/* * Copyright 2023-2024 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 io.skippy.junit; /** * The result of a Skippy analysis: * <ul> * <li>a {@link HashedClass} list</li> * <li>a {@link CoverageData} for all tests that use Skippy</li> * </ul> * * @author Florian McKee */ class SkippyAnalysis { enum Reason { NO_CHANGE, NO_COVERAGE_DATA_FOR_TEST, BYTECODE_CHANGE_IN_TEST, NO_HASH_FOR_TEST, NO_HASH_FOR_COVERED_CLASS, BYTECODE_CHANGE_IN_COVERED_CLASS } enum Prediction { EXECUTE, SKIP } record PredictionWithReason(Prediction prediction, Reason reason) { static PredictionWithReason execute(Reason reason) { return new PredictionWithReason(Prediction.EXECUTE, reason); } static PredictionWithReason skip(Reason reason) { return new PredictionWithReason(Prediction.SKIP, reason); } } private static final SkippyAnalysis UNAVAILABLE = new SkippyAnalysis(HashedClasses.UNAVAILABLE, CoverageData.UNAVAILABLE); static final SkippyAnalysis INSTANCE = parse(SkippyUtils.getSkippyFolder()); private final HashedClasses hashedClasses; private final CoverageData coverageData; /** * C'tor. * * @param hashedClasses in-memory representation of the {@code classes.md5} file * @param coverageData in-memory representation of the {@code .cov} files in the skippy folder */ private SkippyAnalysis(HashedClasses hashedClasses, CoverageData coverageData) { this.hashedClasses = hashedClasses; this.coverageData = coverageData; } static SkippyAnalysis parse(Path skippyDirectory) {
/* * Copyright 2023-2024 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 io.skippy.junit; /** * The result of a Skippy analysis: * <ul> * <li>a {@link HashedClass} list</li> * <li>a {@link CoverageData} for all tests that use Skippy</li> * </ul> * * @author Florian McKee */ class SkippyAnalysis { enum Reason { NO_CHANGE, NO_COVERAGE_DATA_FOR_TEST, BYTECODE_CHANGE_IN_TEST, NO_HASH_FOR_TEST, NO_HASH_FOR_COVERED_CLASS, BYTECODE_CHANGE_IN_COVERED_CLASS } enum Prediction { EXECUTE, SKIP } record PredictionWithReason(Prediction prediction, Reason reason) { static PredictionWithReason execute(Reason reason) { return new PredictionWithReason(Prediction.EXECUTE, reason); } static PredictionWithReason skip(Reason reason) { return new PredictionWithReason(Prediction.SKIP, reason); } } private static final SkippyAnalysis UNAVAILABLE = new SkippyAnalysis(HashedClasses.UNAVAILABLE, CoverageData.UNAVAILABLE); static final SkippyAnalysis INSTANCE = parse(SkippyUtils.getSkippyFolder()); private final HashedClasses hashedClasses; private final CoverageData coverageData; /** * C'tor. * * @param hashedClasses in-memory representation of the {@code classes.md5} file * @param coverageData in-memory representation of the {@code .cov} files in the skippy folder */ private SkippyAnalysis(HashedClasses hashedClasses, CoverageData coverageData) { this.hashedClasses = hashedClasses; this.coverageData = coverageData; } static SkippyAnalysis parse(Path skippyDirectory) {
return Profiler.profile("SkippyAnalysis#parse", () -> {
0
2023-11-24 14:19:17+00:00
4k
CaoBaoQi/homework-android
work-account-book/src/main/java/jz/cbq/work_account_book/ui/home/Expenditure.java
[ { "identifier": "AccountItemAdapter", "path": "work-account-book/src/main/java/jz/cbq/work_account_book/AccountItemAdapter.java", "snippet": "public class AccountItemAdapter extends RecyclerView.Adapter<AccountItemAdapter.ViewHolder> {\n private List<MyDatabase> itemsList;\n\n static class ViewHol...
import android.app.Dialog; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import jz.cbq.work_account_book.AccountItemAdapter; import jz.cbq.work_account_book.R; import jz.cbq.work_account_book.database.DatabaseAction; import jz.cbq.work_account_book.database.MyDatabase; import java.util.ArrayList; import java.util.List; import java.util.Locale;
2,571
package jz.cbq.work_account_book.ui.home; public class Expenditure extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; public static List<MyDatabase> expenditureList = new ArrayList<>(); public static AccountItemAdapter adapter = new AccountItemAdapter(expenditureList); public Expenditure() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment BlankFragment1. */ // TODO: Rename and change types and number of parameters public static Expenditure newInstance(String param1, String param2) { Expenditure fragment = new Expenditure(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { // TODO: Rename and change types of parameters String mParam1 = getArguments().getString(ARG_PARAM1); String mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View root = inflater.inflate(R.layout.expenditure, container, false); RecyclerView recyclerView = root.findViewById(R.id.expenditureList); LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext()); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); refreshList(); adapter.setOnItemClickListener(new AccountItemAdapter.OnItemClickListener() { @Override public void onClick(int position, View v) { Dialog dialog = new Dialog(getContext()); //去掉标题线 dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); View view = LayoutInflater.from(getContext()).inflate(R.layout.detail, null, false); MyDatabase mdb = expenditureList.get(position); TextView txt = view.findViewById(R.id.detailInOut); txt.setText((mdb.getInOut() ? "支出" : "收入")); txt = view.findViewById(R.id.detailType); txt.setText(":" + mdb.getType()); txt = view.findViewById(R.id.detailDate); txt.setText(String.format(Locale.CHINA, "%d年%d月%d日", mdb.getYear(), mdb.getMonth(), mdb.getDay())); txt = view.findViewById(R.id.detailMoney); txt.setText(String.format("%.2f", (double) mdb.getMoney() / 100)); txt = view.findViewById(R.id.detailRemark); txt.setText(mdb.getRemark()); dialog.setContentView(view); //背景透明 dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); dialog.show(); } @Override public void onLongClick(int position, View v) { editMenu(position, v); } }); return root; } private void editMenu(int position, View v) { PopupMenu popupMenu = new PopupMenu(getContext(), v); popupMenu.getMenuInflater().inflate(R.menu.long_click_menu, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(item -> { if (item.getItemId() == R.id.delete) { new Thread(() -> {
package jz.cbq.work_account_book.ui.home; public class Expenditure extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; public static List<MyDatabase> expenditureList = new ArrayList<>(); public static AccountItemAdapter adapter = new AccountItemAdapter(expenditureList); public Expenditure() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment BlankFragment1. */ // TODO: Rename and change types and number of parameters public static Expenditure newInstance(String param1, String param2) { Expenditure fragment = new Expenditure(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { // TODO: Rename and change types of parameters String mParam1 = getArguments().getString(ARG_PARAM1); String mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View root = inflater.inflate(R.layout.expenditure, container, false); RecyclerView recyclerView = root.findViewById(R.id.expenditureList); LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext()); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); refreshList(); adapter.setOnItemClickListener(new AccountItemAdapter.OnItemClickListener() { @Override public void onClick(int position, View v) { Dialog dialog = new Dialog(getContext()); //去掉标题线 dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); View view = LayoutInflater.from(getContext()).inflate(R.layout.detail, null, false); MyDatabase mdb = expenditureList.get(position); TextView txt = view.findViewById(R.id.detailInOut); txt.setText((mdb.getInOut() ? "支出" : "收入")); txt = view.findViewById(R.id.detailType); txt.setText(":" + mdb.getType()); txt = view.findViewById(R.id.detailDate); txt.setText(String.format(Locale.CHINA, "%d年%d月%d日", mdb.getYear(), mdb.getMonth(), mdb.getDay())); txt = view.findViewById(R.id.detailMoney); txt.setText(String.format("%.2f", (double) mdb.getMoney() / 100)); txt = view.findViewById(R.id.detailRemark); txt.setText(mdb.getRemark()); dialog.setContentView(view); //背景透明 dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); dialog.show(); } @Override public void onLongClick(int position, View v) { editMenu(position, v); } }); return root; } private void editMenu(int position, View v) { PopupMenu popupMenu = new PopupMenu(getContext(), v); popupMenu.getMenuInflater().inflate(R.menu.long_click_menu, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(item -> { if (item.getItemId() == R.id.delete) { new Thread(() -> {
DatabaseAction.getInstance(getContext()).getAllIncomesDao().delete(expenditureList.get(position));
1
2023-11-20 17:30:01+00:00
4k
tommyskeff/futur4j
futur-api/src/main/java/dev/tommyjs/futur/impl/SimplePromise.java
[ { "identifier": "AbstractPromise", "path": "futur-api/src/main/java/dev/tommyjs/futur/promise/AbstractPromise.java", "snippet": "public abstract class AbstractPromise<T> implements Promise<T> {\n\n private final Collection<PromiseListener<T>> listeners;\n\n private @Nullable PromiseCompletion<T> c...
import dev.tommyjs.futur.promise.AbstractPromise; import dev.tommyjs.futur.promise.PromiseFactory; import org.slf4j.Logger; import java.util.concurrent.ScheduledExecutorService;
2,869
package dev.tommyjs.futur.impl; public class SimplePromise<T> extends AbstractPromise<T> { private final ScheduledExecutorService executor; private final Logger logger;
package dev.tommyjs.futur.impl; public class SimplePromise<T> extends AbstractPromise<T> { private final ScheduledExecutorService executor; private final Logger logger;
private final PromiseFactory factory;
1
2023-11-19 20:56:51+00:00
4k
phamdung2209/FAP
src/main/java/com/persons/Administrator.java
[ { "identifier": "Course", "path": "src/main/java/com/course/Course.java", "snippet": "public class Course {\n private String id;\n private String courseName;\n private String description;\n private long cost;\n private Student student;\n private Lecturer lecturer;\n private List<Sch...
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.course.Course; import com.date.DateOfBirth; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.func.Grade; import com.func.ClassroomHandler.Classroom; import com.persons.personType.PersonType;
2,188
package com.persons; // Component interface interface getNotify { void display(); } class AdministratorGroup implements getNotify { private List<getNotify> administrators = new ArrayList<>(); public AdministratorGroup() { } public void addAdministrator(getNotify administrator) { administrators.add(administrator); } @Override public void display() { System.out.println("Administrator Group"); administrators.forEach(getNotify::display); } } public class Administrator extends User implements getNotify { // Composite pattern - Structural Pattern @Override public void display() { System.out.println("Administrator" + getFullName() + "has been added"); } public static final String filePath = "C:\\Users\\ACER\\Documents\\Course\\Advance Programming\\Assignment 2\\Project\\FAP\\src\\main\\java\\service\\data.json"; // ThreadSafe Singleton Pattern - Creational Pattern private Administrator() { } private static Administrator admin; public static synchronized Administrator getAdministrator() { if (admin == null) { admin = new Administrator(); } return admin; } // iterator pattern - Behavioral Pattern public void viewStudents(){ Student student1 = new Student("Dung Pham"); Student student2 = new Student("John Wick"); Student student3 = new Student("Tony Stark"); List<Student> students = new ArrayList<>(); students.add(student1); students.add(student2); students.add(student3); Iterator student = students.iterator(); while(student.hasNext()){ Student std = (Student) student.next(); System.out.println(std.getFullName()); } } // person type
package com.persons; // Component interface interface getNotify { void display(); } class AdministratorGroup implements getNotify { private List<getNotify> administrators = new ArrayList<>(); public AdministratorGroup() { } public void addAdministrator(getNotify administrator) { administrators.add(administrator); } @Override public void display() { System.out.println("Administrator Group"); administrators.forEach(getNotify::display); } } public class Administrator extends User implements getNotify { // Composite pattern - Structural Pattern @Override public void display() { System.out.println("Administrator" + getFullName() + "has been added"); } public static final String filePath = "C:\\Users\\ACER\\Documents\\Course\\Advance Programming\\Assignment 2\\Project\\FAP\\src\\main\\java\\service\\data.json"; // ThreadSafe Singleton Pattern - Creational Pattern private Administrator() { } private static Administrator admin; public static synchronized Administrator getAdministrator() { if (admin == null) { admin = new Administrator(); } return admin; } // iterator pattern - Behavioral Pattern public void viewStudents(){ Student student1 = new Student("Dung Pham"); Student student2 = new Student("John Wick"); Student student3 = new Student("Tony Stark"); List<Student> students = new ArrayList<>(); students.add(student1); students.add(student2); students.add(student3); Iterator student = students.iterator(); while(student.hasNext()){ Student std = (Student) student.next(); System.out.println(std.getFullName()); } } // person type
public PersonType getPersonType() {
4
2023-11-23 18:42:19+00:00
4k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/tools/certificate/cryptoops/CryptoStoreManager.java
[ { "identifier": "IKeyStoreConfig", "path": "src/main/java/de/morihofi/acmeserver/tools/certificate/cryptoops/ksconfig/IKeyStoreConfig.java", "snippet": "public interface IKeyStoreConfig {\n /**\n * Gets the password for the keystore configuration.\n *\n * @return The keystore password as ...
import de.morihofi.acmeserver.tools.certificate.cryptoops.ksconfig.IKeyStoreConfig; import de.morihofi.acmeserver.tools.certificate.cryptoops.ksconfig.PKCS11KeyStoreConfig; import de.morihofi.acmeserver.tools.certificate.cryptoops.ksconfig.PKCS12KeyStoreConfig; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.nio.file.Files; import java.security.*; import java.security.cert.CertificateException;
1,978
package de.morihofi.acmeserver.tools.certificate.cryptoops; /** * The CryptoStoreManager class manages cryptographic operations, including loading and saving * key stores, providing access to key pairs, and handling various keystore configurations. * It supports both PKCS#11 and PKCS#12 keystore configurations. */ public class CryptoStoreManager { /** * Alias for the root certificate authority in the keystore. */ public static final String KEYSTORE_ALIAS_ROOTCA = "rootCA"; /** * Alias for the ACME API certificate in the keystore. */ public static final String KEYSTORE_ALIAS_ACMEAPI = "serverAcmeApi"; /** * Prefix for aliases of intermediate certificate authorities in the keystore. */ public static final String KEYSTORE_ALIASPREFIX_INTERMEDIATECA = "intermediateCA_"; /** * Logger for logging messages and events. */ public final Logger log = LogManager.getLogger(getClass()); /** * Key store configuration, including type and parameters. */ private final IKeyStoreConfig keyStoreConfig; /** * The loaded keystore instance for cryptographic operations. */ private KeyStore keyStore; public static String getKeyStoreAliasForProvisionerIntermediate(String provisioner) { return KEYSTORE_ALIASPREFIX_INTERMEDIATECA + provisioner; } /** * Constructs a CryptoStoreManager with the specified key store configuration. * * @param keyStoreConfig The key store configuration to use. * @throws CertificateException If there is an issue with certificates. * @throws IOException If there is an I/O error. * @throws NoSuchAlgorithmException If a required cryptographic algorithm is not available. * @throws KeyStoreException If there is an issue with the keystore. * @throws ClassNotFoundException If a required class is not found. * @throws InvocationTargetException If there is an issue with invoking a method. * @throws InstantiationException If there is an issue with instantiating a class. * @throws IllegalAccessException If there is an issue with accessing a class or method. * @throws NoSuchMethodException If a required method is not found. * @throws NoSuchProviderException If a cryptographic provider is not found. */ public CryptoStoreManager(IKeyStoreConfig keyStoreConfig) throws CertificateException, IOException, NoSuchAlgorithmException, KeyStoreException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchProviderException { this.keyStoreConfig = keyStoreConfig; if (keyStoreConfig instanceof PKCS11KeyStoreConfig pkcs11Config) { String libraryLocation = pkcs11Config.getLibraryPath().toAbsolutePath().toString(); log.info("Using PKCS#11 KeyStore with native library at {} with slot {}", libraryLocation, pkcs11Config.getSlot()); keyStore = PKCS11KeyStoreLoader.loadPKCS11Keystore(pkcs11Config.getPassword(), pkcs11Config.getSlot(), libraryLocation); }
package de.morihofi.acmeserver.tools.certificate.cryptoops; /** * The CryptoStoreManager class manages cryptographic operations, including loading and saving * key stores, providing access to key pairs, and handling various keystore configurations. * It supports both PKCS#11 and PKCS#12 keystore configurations. */ public class CryptoStoreManager { /** * Alias for the root certificate authority in the keystore. */ public static final String KEYSTORE_ALIAS_ROOTCA = "rootCA"; /** * Alias for the ACME API certificate in the keystore. */ public static final String KEYSTORE_ALIAS_ACMEAPI = "serverAcmeApi"; /** * Prefix for aliases of intermediate certificate authorities in the keystore. */ public static final String KEYSTORE_ALIASPREFIX_INTERMEDIATECA = "intermediateCA_"; /** * Logger for logging messages and events. */ public final Logger log = LogManager.getLogger(getClass()); /** * Key store configuration, including type and parameters. */ private final IKeyStoreConfig keyStoreConfig; /** * The loaded keystore instance for cryptographic operations. */ private KeyStore keyStore; public static String getKeyStoreAliasForProvisionerIntermediate(String provisioner) { return KEYSTORE_ALIASPREFIX_INTERMEDIATECA + provisioner; } /** * Constructs a CryptoStoreManager with the specified key store configuration. * * @param keyStoreConfig The key store configuration to use. * @throws CertificateException If there is an issue with certificates. * @throws IOException If there is an I/O error. * @throws NoSuchAlgorithmException If a required cryptographic algorithm is not available. * @throws KeyStoreException If there is an issue with the keystore. * @throws ClassNotFoundException If a required class is not found. * @throws InvocationTargetException If there is an issue with invoking a method. * @throws InstantiationException If there is an issue with instantiating a class. * @throws IllegalAccessException If there is an issue with accessing a class or method. * @throws NoSuchMethodException If a required method is not found. * @throws NoSuchProviderException If a cryptographic provider is not found. */ public CryptoStoreManager(IKeyStoreConfig keyStoreConfig) throws CertificateException, IOException, NoSuchAlgorithmException, KeyStoreException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchProviderException { this.keyStoreConfig = keyStoreConfig; if (keyStoreConfig instanceof PKCS11KeyStoreConfig pkcs11Config) { String libraryLocation = pkcs11Config.getLibraryPath().toAbsolutePath().toString(); log.info("Using PKCS#11 KeyStore with native library at {} with slot {}", libraryLocation, pkcs11Config.getSlot()); keyStore = PKCS11KeyStoreLoader.loadPKCS11Keystore(pkcs11Config.getPassword(), pkcs11Config.getSlot(), libraryLocation); }
if (keyStoreConfig instanceof PKCS12KeyStoreConfig pkcs12Config) {
2
2023-11-22 15:54:36+00:00
4k
sakura-ryoko/afkplus
src/main/java/io/github/sakuraryoko/afkplus/mixin/ServerPlayerMixin.java
[ { "identifier": "CONFIG", "path": "src/main/java/io/github/sakuraryoko/afkplus/config/ConfigManager.java", "snippet": "public static ConfigData CONFIG = new ConfigData();" }, { "identifier": "IAfkPlayer", "path": "src/main/java/io/github/sakuraryoko/afkplus/data/IAfkPlayer.java", "snippe...
import static io.github.sakuraryoko.afkplus.config.ConfigManager.CONFIG; import net.minecraft.world.GameMode; import org.apache.commons.lang3.time.DurationFormatUtils; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import eu.pb4.placeholders.api.PlaceholderContext; import eu.pb4.placeholders.api.Placeholders; import eu.pb4.placeholders.api.TextParserUtils; import io.github.sakuraryoko.afkplus.data.IAfkPlayer; import io.github.sakuraryoko.afkplus.util.AfkPlusLogger; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.network.packet.s2c.play.PlayerListS2CPacket; import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.Text; import net.minecraft.util.Util; import net.minecraft.world.World;
1,899
package io.github.sakuraryoko.afkplus.mixin; @Mixin(ServerPlayerEntity.class) public abstract class ServerPlayerMixin extends Entity implements IAfkPlayer { @Shadow @Final public MinecraftServer server; @Shadow public abstract boolean isCreative(); @Shadow public abstract boolean isSpectator(); @Unique public ServerPlayerEntity player = (ServerPlayerEntity) (Object) this; @Unique private boolean isAfk = false; @Unique private long afkTimeMs = 0; @Unique private String afkTimeString = ""; @Unique private String afkReason = ""; @Unique private boolean isDamageEnabled = true; @Unique private boolean isLockDamageDisabled = false; public ServerPlayerMixin(EntityType<?> type, World world) { super(type, world); } @Unique public boolean afkplus$isAfk() { return this.isAfk; } @Unique public long afkplus$getAfkTimeMs() { return this.afkTimeMs; } @Unique public String afkplus$getAfkTimeString() { return this.afkTimeString; } @Unique public String afkplus$getAfkReason() { return this.afkReason; } @Unique public boolean afkplus$isDamageEnabled() { return this.isDamageEnabled; } @Unique public boolean afkplus$isLockDamageDisabled() { return this.isLockDamageDisabled; } @Unique public void afkplus$registerAfk(String reason) { if (afkplus$isAfk()) return; setAfkTime(); if (reason == null && CONFIG.messageOptions.defaultReason == null) { setAfkReason("<red>none"); } else if (reason == null || reason.isEmpty()) { setAfkReason("<red>none"); Text mess = Placeholders.parseText(TextParserUtils.formatTextSafe(CONFIG.messageOptions.whenAfk), PlaceholderContext.of(this)); //AfkPlusLogger.debug("registerafk-mess().toString(): " + mess.toString()); sendAfkMessage(mess); } else { setAfkReason(reason); String mess1 = CONFIG.messageOptions.whenAfk + "<yellow>,<r> " + reason; Text mess2 = Placeholders.parseText(TextParserUtils.formatTextSafe(mess1), PlaceholderContext.of(player)); sendAfkMessage(mess2); } setAfk(true); if (CONFIG.packetOptions.disableDamage && CONFIG.packetOptions.disableDamageCooldown < 1) afkplus$disableDamage(); afkplus$updatePlayerList(); } @Unique public void afkplus$unregisterAfk() { if (!afkplus$isAfk()) { // Maybe it was called by PlayerManagerMixin? setAfk(false); clearAfkTime(); clearAfkReason(); return; } if (CONFIG.messageOptions.prettyDuration) { long duration = Util.getMeasuringTimeMs() - (this.afkTimeMs); String ret = CONFIG.messageOptions.whenReturn + " <gray>(Gone for: <green>" + DurationFormatUtils.formatDurationWords(duration, true, true) + "<gray>)<r>"; //AfkPlusLogger.debug("unregisterAfk-ret: " + ret); Text mess1 = TextParserUtils.formatTextSafe(ret); //AfkPlusLogger.debug("unregisterafk-mess1().toString(): " + mess1.toString()); Text mess2 = Placeholders.parseText(mess1, PlaceholderContext.of(this)); //AfkPlusLogger.debug("unregisterafk-mess2().toString(): " + mess2.toString()); sendAfkMessage(mess2); } else { long duration = Util.getMeasuringTimeMs() - (this.afkTimeMs); String ret = CONFIG.messageOptions.whenReturn + " <gray>(Gone for: <green>" + DurationFormatUtils.formatDurationHMS(duration) + "<gray>)<r>"; //AfkPlusLogger.debug("unregisterAfk-ret: " + ret); Text mess1 = TextParserUtils.formatTextSafe(ret); //AfkPlusLogger.debug("unregisterafk-mess1().toString(): " + mess1.toString()); Text mess2 = Placeholders.parseText(mess1, PlaceholderContext.of(player)); //AfkPlusLogger.debug("unregisterafk-mess2().toString(): " + mess2.toString()); sendAfkMessage(mess2); } setAfk(false); clearAfkTime(); clearAfkReason(); if (!afkplus$isDamageEnabled()) afkplus$enableDamage(); afkplus$updatePlayerList(); } @Unique public void afkplus$updatePlayerList() { this.server.getPlayerManager().sendToAll(new PlayerListS2CPacket(PlayerListS2CPacket.Action.UPDATE_DISPLAY_NAME, player));
package io.github.sakuraryoko.afkplus.mixin; @Mixin(ServerPlayerEntity.class) public abstract class ServerPlayerMixin extends Entity implements IAfkPlayer { @Shadow @Final public MinecraftServer server; @Shadow public abstract boolean isCreative(); @Shadow public abstract boolean isSpectator(); @Unique public ServerPlayerEntity player = (ServerPlayerEntity) (Object) this; @Unique private boolean isAfk = false; @Unique private long afkTimeMs = 0; @Unique private String afkTimeString = ""; @Unique private String afkReason = ""; @Unique private boolean isDamageEnabled = true; @Unique private boolean isLockDamageDisabled = false; public ServerPlayerMixin(EntityType<?> type, World world) { super(type, world); } @Unique public boolean afkplus$isAfk() { return this.isAfk; } @Unique public long afkplus$getAfkTimeMs() { return this.afkTimeMs; } @Unique public String afkplus$getAfkTimeString() { return this.afkTimeString; } @Unique public String afkplus$getAfkReason() { return this.afkReason; } @Unique public boolean afkplus$isDamageEnabled() { return this.isDamageEnabled; } @Unique public boolean afkplus$isLockDamageDisabled() { return this.isLockDamageDisabled; } @Unique public void afkplus$registerAfk(String reason) { if (afkplus$isAfk()) return; setAfkTime(); if (reason == null && CONFIG.messageOptions.defaultReason == null) { setAfkReason("<red>none"); } else if (reason == null || reason.isEmpty()) { setAfkReason("<red>none"); Text mess = Placeholders.parseText(TextParserUtils.formatTextSafe(CONFIG.messageOptions.whenAfk), PlaceholderContext.of(this)); //AfkPlusLogger.debug("registerafk-mess().toString(): " + mess.toString()); sendAfkMessage(mess); } else { setAfkReason(reason); String mess1 = CONFIG.messageOptions.whenAfk + "<yellow>,<r> " + reason; Text mess2 = Placeholders.parseText(TextParserUtils.formatTextSafe(mess1), PlaceholderContext.of(player)); sendAfkMessage(mess2); } setAfk(true); if (CONFIG.packetOptions.disableDamage && CONFIG.packetOptions.disableDamageCooldown < 1) afkplus$disableDamage(); afkplus$updatePlayerList(); } @Unique public void afkplus$unregisterAfk() { if (!afkplus$isAfk()) { // Maybe it was called by PlayerManagerMixin? setAfk(false); clearAfkTime(); clearAfkReason(); return; } if (CONFIG.messageOptions.prettyDuration) { long duration = Util.getMeasuringTimeMs() - (this.afkTimeMs); String ret = CONFIG.messageOptions.whenReturn + " <gray>(Gone for: <green>" + DurationFormatUtils.formatDurationWords(duration, true, true) + "<gray>)<r>"; //AfkPlusLogger.debug("unregisterAfk-ret: " + ret); Text mess1 = TextParserUtils.formatTextSafe(ret); //AfkPlusLogger.debug("unregisterafk-mess1().toString(): " + mess1.toString()); Text mess2 = Placeholders.parseText(mess1, PlaceholderContext.of(this)); //AfkPlusLogger.debug("unregisterafk-mess2().toString(): " + mess2.toString()); sendAfkMessage(mess2); } else { long duration = Util.getMeasuringTimeMs() - (this.afkTimeMs); String ret = CONFIG.messageOptions.whenReturn + " <gray>(Gone for: <green>" + DurationFormatUtils.formatDurationHMS(duration) + "<gray>)<r>"; //AfkPlusLogger.debug("unregisterAfk-ret: " + ret); Text mess1 = TextParserUtils.formatTextSafe(ret); //AfkPlusLogger.debug("unregisterafk-mess1().toString(): " + mess1.toString()); Text mess2 = Placeholders.parseText(mess1, PlaceholderContext.of(player)); //AfkPlusLogger.debug("unregisterafk-mess2().toString(): " + mess2.toString()); sendAfkMessage(mess2); } setAfk(false); clearAfkTime(); clearAfkReason(); if (!afkplus$isDamageEnabled()) afkplus$enableDamage(); afkplus$updatePlayerList(); } @Unique public void afkplus$updatePlayerList() { this.server.getPlayerManager().sendToAll(new PlayerListS2CPacket(PlayerListS2CPacket.Action.UPDATE_DISPLAY_NAME, player));
AfkPlusLogger.debug("sending player list update for " + afkplus$getName());
2
2023-11-22 00:21:36+00:00
4k
AzFyXi/slotMachine
SlotMachine/src/main/java/SlotMachine/SlotMachine.java
[ { "identifier": "Config", "path": "SlotMachine/src/main/java/ressources/Config.java", "snippet": "public class Config {\n\n public static void init() {\n\n JSONObject parsedSymbols = parseSymbols();\n assert parsedSymbols != null;\n\n Collection<Symbol> symbols = createSymbolsCol...
import ressources.Config; import User.User; import org.json.simple.JSONObject; import javax.swing.*; import java.util.*; import java.util.stream.Collectors;
1,730
package SlotMachine; public class SlotMachine { private Collection<Column> columns; private static int numberColumns; private static Symbol finalSymbol; public SlotMachine(Collection<Column> columns, int numberColumns) { this.columns = columns; SlotMachine.numberColumns = numberColumns; finalSymbol = new Symbol(0); } public Collection<Column> getColumns() { return columns; } public void setColumns(Collection<Column> columns) { this.columns = columns; } public int getNumberColumns() { return numberColumns; } public void setNumberColumns(int numberColumns) { SlotMachine.numberColumns = numberColumns; } public static Symbol getFinalSymbol() { return finalSymbol; } public static void setFinalSymbol(Symbol finalSymbol) { SlotMachine.finalSymbol = finalSymbol; }
package SlotMachine; public class SlotMachine { private Collection<Column> columns; private static int numberColumns; private static Symbol finalSymbol; public SlotMachine(Collection<Column> columns, int numberColumns) { this.columns = columns; SlotMachine.numberColumns = numberColumns; finalSymbol = new Symbol(0); } public Collection<Column> getColumns() { return columns; } public void setColumns(Collection<Column> columns) { this.columns = columns; } public int getNumberColumns() { return numberColumns; } public void setNumberColumns(int numberColumns) { SlotMachine.numberColumns = numberColumns; } public static Symbol getFinalSymbol() { return finalSymbol; } public static void setFinalSymbol(Symbol finalSymbol) { SlotMachine.finalSymbol = finalSymbol; }
public boolean startMachine(User mainUser, Collection<Column> columns) { //function to start the SlotMachine
1
2023-11-22 09:39:59+00:00
4k
trgpnt/java-class-jacksonizer
src/test/java/com/test_helper_utils/StringInputGenerator.java
[ { "identifier": "IndentationUtils", "path": "src/main/java/com/aggregated/IndentationUtils.java", "snippet": "public class IndentationUtils {\n private static final Logger LOG = LoggerFactory.getLogger(IndentationUtils.class);\n private static int currentIndentValue;\n public...
import com.aggregated.IndentationUtils; import com.aggregated.ThreadUtils; import org.apache.commons.lang3.RandomStringUtils; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static com.aggregated.CharacterRepository.*;
2,520
package com.test_helper_utils; public class StringInputGenerator extends BaseInputGenerator { private static final StringInputGenerator INSTANCE = new StringInputGenerator(); private static final String NULL_AS_STRING = "null"; private static final String NULL_KEYWORD = null; private static final String EMPTY = ""; private static final int DEFAULT_CHARACTER_SIZE = 10; private static final String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static final String DIGITS = "0123456789"; private static final String SPECIAL_CHARACTERS = "!@#$%^&*()-_=+[]{}|;:'\",.<>/?`~"; private static final String ALL_CHARACTERS = LETTERS + DIGITS + SPECIAL_CHARACTERS + " "; public String randomWith(int length, RANDOM_TYPE... type) { final int availThreads = Runtime.getRuntime().availableProcessors(); int possibleThreads = length / availThreads; StringBuffer chosen = new StringBuffer(chooseString(type)); int bound = chosen.length(); if (possibleThreads < 2 || possibleThreads > availThreads) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(chosen.charAt(RandomUtils.randomInt((bound)))); } return sb.toString(); } Thread[] threads = new Thread[possibleThreads]; int threadIdx = 0; AtomicReference<char[]> container = new AtomicReference<>(new char[length]); AtomicInteger decreaser = new AtomicInteger(possibleThreads); AtomicInteger increaser = new AtomicInteger(0); for (int i = 0; i < threads.length; i++) { AtomicInteger idx = new AtomicInteger(increaser.get()); AtomicInteger atomicLen = new AtomicInteger(length / decreaser.get()); Runnable runnable = (() -> { for (; idx.get() < atomicLen.get() - 1;) { container.get()[idx.getAndIncrement()] = chosen.charAt(RandomUtils.randomInt(bound)); } }); threads[threadIdx++] = new Thread(runnable); increaser.set(atomicLen.get() + 1); decreaser.getAndDecrement(); }
package com.test_helper_utils; public class StringInputGenerator extends BaseInputGenerator { private static final StringInputGenerator INSTANCE = new StringInputGenerator(); private static final String NULL_AS_STRING = "null"; private static final String NULL_KEYWORD = null; private static final String EMPTY = ""; private static final int DEFAULT_CHARACTER_SIZE = 10; private static final String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static final String DIGITS = "0123456789"; private static final String SPECIAL_CHARACTERS = "!@#$%^&*()-_=+[]{}|;:'\",.<>/?`~"; private static final String ALL_CHARACTERS = LETTERS + DIGITS + SPECIAL_CHARACTERS + " "; public String randomWith(int length, RANDOM_TYPE... type) { final int availThreads = Runtime.getRuntime().availableProcessors(); int possibleThreads = length / availThreads; StringBuffer chosen = new StringBuffer(chooseString(type)); int bound = chosen.length(); if (possibleThreads < 2 || possibleThreads > availThreads) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(chosen.charAt(RandomUtils.randomInt((bound)))); } return sb.toString(); } Thread[] threads = new Thread[possibleThreads]; int threadIdx = 0; AtomicReference<char[]> container = new AtomicReference<>(new char[length]); AtomicInteger decreaser = new AtomicInteger(possibleThreads); AtomicInteger increaser = new AtomicInteger(0); for (int i = 0; i < threads.length; i++) { AtomicInteger idx = new AtomicInteger(increaser.get()); AtomicInteger atomicLen = new AtomicInteger(length / decreaser.get()); Runnable runnable = (() -> { for (; idx.get() < atomicLen.get() - 1;) { container.get()[idx.getAndIncrement()] = chosen.charAt(RandomUtils.randomInt(bound)); } }); threads[threadIdx++] = new Thread(runnable); increaser.set(atomicLen.get() + 1); decreaser.getAndDecrement(); }
ThreadUtils.executeAndJoinAll(threads);
1
2023-11-23 10:59:01+00:00
4k
DewmithMihisara/car-rental-hibernate
src/main/java/lk/ijse/controller/UserFormController.java
[ { "identifier": "BOFactory", "path": "src/main/java/lk/ijse/bo/BOFactory.java", "snippet": "public class BOFactory {\n private static BOFactory factory;\n private BOFactory(){}\n public static BOFactory getInstance(){\n return factory == null ? new BOFactory() : factory;\n }\n publ...
import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.shape.Line; import lk.ijse.bo.BOFactory; import lk.ijse.bo.custom.UserBO; import lk.ijse.controller.util.AlertTypes; import lk.ijse.controller.util.PopUpAlerts; import lk.ijse.controller.util.Validation; import lk.ijse.dto.UserDto; import lk.ijse.dto.tm.UserTM;
1,966
package lk.ijse.controller; public class UserFormController { @FXML private Button addBtn; @FXML private Button deleteBtn; @FXML private Line firstNameLine; @FXML private TableColumn<?, ?> roleClm; @FXML private TextField firstNameTxt; @FXML private TableColumn<?, ?> fullNameColm; @FXML private TableColumn<?, ?> idColm; @FXML private Label idLbl; @FXML private Line lastNameLine; @FXML private TextField pwTxt; @FXML private Line roleLine; @FXML private TextField roleTxt; @FXML private Button searchBtn; @FXML private TextField searchTxt; @FXML private Button svBtn; @FXML private Button upBtn; @FXML private TableColumn<?, ?> userNameColm; @FXML private Line userNameLine; @FXML private TextField userNameTxt; @FXML private Line pwLine; @FXML private TextField lastNameTxt; @FXML private TableView<UserTM> usrTbl;
package lk.ijse.controller; public class UserFormController { @FXML private Button addBtn; @FXML private Button deleteBtn; @FXML private Line firstNameLine; @FXML private TableColumn<?, ?> roleClm; @FXML private TextField firstNameTxt; @FXML private TableColumn<?, ?> fullNameColm; @FXML private TableColumn<?, ?> idColm; @FXML private Label idLbl; @FXML private Line lastNameLine; @FXML private TextField pwTxt; @FXML private Line roleLine; @FXML private TextField roleTxt; @FXML private Button searchBtn; @FXML private TextField searchTxt; @FXML private Button svBtn; @FXML private Button upBtn; @FXML private TableColumn<?, ?> userNameColm; @FXML private Line userNameLine; @FXML private TextField userNameTxt; @FXML private Line pwLine; @FXML private TextField lastNameTxt; @FXML private TableView<UserTM> usrTbl;
private final UserBO userBO = (UserBO) BOFactory.getInstance().getBO(BOFactory.BOTypes.USER);
0
2023-11-27 17:28:48+00:00
4k
inferior3x/JNU-course-seat-alert-Server
src/main/java/com/coco3x/jnu_course_seat_alert/controller/ApplicantController.java
[ { "identifier": "ApiResponseCreator", "path": "src/main/java/com/coco3x/jnu_course_seat_alert/config/apiresponse/ApiResponseCreator.java", "snippet": "public class ApiResponseCreator {\n public static <T> ApiResponse<T> success(T data){\n return new ApiResponse<>(true, data, HttpStatus.OK.valu...
import com.coco3x.jnu_course_seat_alert.config.annotation.Session; import com.coco3x.jnu_course_seat_alert.config.apiresponse.ApiMessage; import com.coco3x.jnu_course_seat_alert.config.apiresponse.ApiResponse; import com.coco3x.jnu_course_seat_alert.config.apiresponse.ApiResponseCreator; import com.coco3x.jnu_course_seat_alert.config.constant.CommonConst; import com.coco3x.jnu_course_seat_alert.config.exception.ApplicationLimitExceededException; import com.coco3x.jnu_course_seat_alert.domain.dto.layer.request.CourseCreateReqDTO; import com.coco3x.jnu_course_seat_alert.domain.dto.request.ApplicantCreateReqDTO; import com.coco3x.jnu_course_seat_alert.domain.dto.request.ApplicantDeleteReqDTO; import com.coco3x.jnu_course_seat_alert.domain.dto.response.CourseResDTO; import com.coco3x.jnu_course_seat_alert.domain.entity.Course; import com.coco3x.jnu_course_seat_alert.domain.entity.User; import com.coco3x.jnu_course_seat_alert.service.ApplicantService; import com.coco3x.jnu_course_seat_alert.service.CourseService; import com.coco3x.jnu_course_seat_alert.service.UserService; import com.coco3x.jnu_course_seat_alert.util.CourseValidationCrawler; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*;
2,953
package com.coco3x.jnu_course_seat_alert.controller; @RestController @RequestMapping("/applicant") @RequiredArgsConstructor public class ApplicantController { private final ApplicantService applicantService; private final CourseService courseService; private final UserService userService; private final CourseValidationCrawler courseValidationCrawler; @PostMapping("/course") public ApiResponse<?> enrollApplicantInCourse(@Session(attr = "id") Long id, @RequestBody @Valid ApplicantCreateReqDTO applicantCreateReqDTO){ User user = userService.findUserById(id); if (applicantService.countApplicants(user) >= CommonConst.APPLICATION_LIMIT)
package com.coco3x.jnu_course_seat_alert.controller; @RestController @RequestMapping("/applicant") @RequiredArgsConstructor public class ApplicantController { private final ApplicantService applicantService; private final CourseService courseService; private final UserService userService; private final CourseValidationCrawler courseValidationCrawler; @PostMapping("/course") public ApiResponse<?> enrollApplicantInCourse(@Session(attr = "id") Long id, @RequestBody @Valid ApplicantCreateReqDTO applicantCreateReqDTO){ User user = userService.findUserById(id); if (applicantService.countApplicants(user) >= CommonConst.APPLICATION_LIMIT)
throw new ApplicationLimitExceededException("신청 가능한 강의 수는 "+ CommonConst.APPLICATION_LIMIT+"개입니다.");
2
2023-11-26 05:01:32+00:00
4k
feiniaojin/ddd-event-sourcing-snapshot
ddd-event-sourcing-snapshot-infrastructure-persistence/src/main/java/com/feiniaojin/ddd/eventsourcing/infrastructure/persistence/ProductRepositoryImpl.java
[ { "identifier": "Entity", "path": "ddd-event-sourcing-snapshot-infrastructure-persistence/src/main/java/com/feiniaojin/ddd/eventsourcing/infrastructure/persistence/jdbc/data/Entity.java", "snippet": "@Data\n@Table(\"t_entity\")\n@Generated(\"generator\")\npublic class Entity implements Serializable {\n ...
import com.feiniaojin.ddd.eventsourcing.domain.*; import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.data.Entity; import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.data.Event; import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.data.Snapshot; import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.repository.EntityJdbcRepository; import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.repository.EventJdbcRepository; import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.repository.SnapshotJdbcRepository; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; import java.util.Objects; import java.util.stream.Collectors;
1,728
package com.feiniaojin.ddd.eventsourcing.infrastructure.persistence; @Component public class ProductRepositoryImpl implements ProductRepository { ProductFactory productFactory = new ProductFactory(); @Resource private EventJdbcRepository eventJdbcRepository; @Resource private EntityJdbcRepository entityJdbcRepository; @Resource private SnapshotJdbcRepository snapshotJdbcRepository; @Override @Transactional public void save(Product product) { //1.存事件 List<DomainEvent> domainEvents = product.getDomainEvents(); List<Event> eventList = domainEvents.stream().map(de -> { Event event = new Event(); event.setEventTime(de.getEventTime()); event.setEventType(de.getEventType()); event.setEventData(JSON.toJsonString(de)); event.setEntityId(de.getEntityId()); event.setDeleted(0); event.setEventId(de.getEventId()); return event; }).collect(Collectors.toList()); eventJdbcRepository.saveAll(eventList); //2.存实体 Entity entity = new Entity(); entity.setId(product.getId()); entity.setDeleted(product.getDeleted()); entity.setEntityId(product.getProductId().getValue()); entity.setDeleted(0); entity.setVersion(product.getVersion()); entityJdbcRepository.save(entity); //3.快照生成 if (product.getTakeSnapshot()) {
package com.feiniaojin.ddd.eventsourcing.infrastructure.persistence; @Component public class ProductRepositoryImpl implements ProductRepository { ProductFactory productFactory = new ProductFactory(); @Resource private EventJdbcRepository eventJdbcRepository; @Resource private EntityJdbcRepository entityJdbcRepository; @Resource private SnapshotJdbcRepository snapshotJdbcRepository; @Override @Transactional public void save(Product product) { //1.存事件 List<DomainEvent> domainEvents = product.getDomainEvents(); List<Event> eventList = domainEvents.stream().map(de -> { Event event = new Event(); event.setEventTime(de.getEventTime()); event.setEventType(de.getEventType()); event.setEventData(JSON.toJsonString(de)); event.setEntityId(de.getEntityId()); event.setDeleted(0); event.setEventId(de.getEventId()); return event; }).collect(Collectors.toList()); eventJdbcRepository.saveAll(eventList); //2.存实体 Entity entity = new Entity(); entity.setId(product.getId()); entity.setDeleted(product.getDeleted()); entity.setEntityId(product.getProductId().getValue()); entity.setDeleted(0); entity.setVersion(product.getVersion()); entityJdbcRepository.save(entity); //3.快照生成 if (product.getTakeSnapshot()) {
Snapshot snapshot = snapshotJdbcRepository.queryOneByEntityId(product.getProductId().getValue());
2
2023-11-25 09:36:05+00:00
4k
clasSeven7/sebo-cultural
src/Tests/ClienteTest.java
[ { "identifier": "Cliente", "path": "src/Domain/Entities/Cliente.java", "snippet": "public class Cliente extends Usuario {\n\n // Lista de gêneros favoritos do cliente.\n private ArrayList<String> generosFavoritos = new ArrayList<String>();\n\n // Lista de pedidos feitos pelo cliente.\n priva...
import Domain.Entities.Cliente; import Domain.Entities.Endereco; import Domain.Entities.Pedido; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.assertEquals;
2,179
package Tests; public class ClienteTest { @Test public void testGetHistoricoPedidosSortedByDate() { Endereco endereco = new Endereco("rua dos bobos", "bossa", "Nova", "12345", "Brasil"); ArrayList<String> generosFavoritos = new ArrayList<>(Arrays.asList("Genre1", "Genre2"));
package Tests; public class ClienteTest { @Test public void testGetHistoricoPedidosSortedByDate() { Endereco endereco = new Endereco("rua dos bobos", "bossa", "Nova", "12345", "Brasil"); ArrayList<String> generosFavoritos = new ArrayList<>(Arrays.asList("Genre1", "Genre2"));
ArrayList<Pedido> historicoPedidos = new ArrayList<>();
2
2023-11-19 02:11:46+00:00
4k
lk-eternal/AI-Assistant-Plus
src/main/java/lk/eternal/ai/model/ai/GeminiAiModel.java
[ { "identifier": "Message", "path": "src/main/java/lk/eternal/ai/dto/req/Message.java", "snippet": "@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)\n@JsonIgnoreProperties(\"think\")\npublic final class Message {\n private String role;\n private String content;\n private List<GPT...
import lk.eternal.ai.dto.req.GeminiReq; import lk.eternal.ai.dto.req.Message; import lk.eternal.ai.dto.req.Tool; import lk.eternal.ai.dto.resp.GPTResp; import lk.eternal.ai.dto.resp.GeminiResp; import lk.eternal.ai.exception.GPTException; import lk.eternal.ai.util.Mapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ProxySelector; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors;
2,771
package lk.eternal.ai.model.ai; @Component public class GeminiAiModel implements AiModel { private static final Logger LOGGER = LoggerFactory.getLogger(GeminiAiModel.class); private final HttpClient HTTP_CLIENT; @Value("${google.gemini.key}") private String key; public GeminiAiModel(ProxySelector proxySelector) { HTTP_CLIENT = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1) .connectTimeout(Duration.ofMinutes(1)) .proxy(proxySelector).build(); } @Override public String getName() { return "gemini"; } @Override
package lk.eternal.ai.model.ai; @Component public class GeminiAiModel implements AiModel { private static final Logger LOGGER = LoggerFactory.getLogger(GeminiAiModel.class); private final HttpClient HTTP_CLIENT; @Value("${google.gemini.key}") private String key; public GeminiAiModel(ProxySelector proxySelector) { HTTP_CLIENT = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1) .connectTimeout(Duration.ofMinutes(1)) .proxy(proxySelector).build(); } @Override public String getName() { return "gemini"; } @Override
public void request(String prompt, List<Message> messages, List<String> stop, List<Tool> tools, Supplier<Boolean> stopCheck, Consumer<GPTResp> respConsumer) throws GPTException {
2
2023-11-23 01:12:34+00:00
4k
Guan-Meng-Yuan/spring-ex
spring-boot-starter-web/src/main/java/com/guanmengyuan/spring/ex/web/config/GlobalErrorController.java
[ { "identifier": "Res", "path": "spring-ex-common-model/src/main/java/com/guanmengyuan/spring/ex/common/model/dto/res/Res.java", "snippet": "@Data\npublic class Res<T> implements Serializable {\n /**\n * 是否成功<br/>\n * true 操作成功<br/>\n * false 操作失败\n */\n private Boolean success;\n\n...
import java.util.Collections; import java.util.Map; import org.dromara.hutool.core.bean.BeanUtil; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import com.guanmengyuan.spring.ex.common.model.dto.res.Res; import com.guanmengyuan.spring.ex.common.model.exception.ServiceException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j;
2,257
package com.guanmengyuan.spring.ex.web.config; @Slf4j public class GlobalErrorController extends BasicErrorController { public GlobalErrorController(ServerProperties serverProperties) { super(new DefaultErrorAttributes(), serverProperties.getError()); } @Override public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); Map<String, Object> model = Collections .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); ModelAndView modelAndView = resolveErrorView(request, response, status, model); Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL)); ServiceException serviceException = new ServiceException(status, body.get("error").toString(), "网络异常"); log.error("request error:{}", body.get("path") + ":" + body.get("error"), serviceException); response.setContentType(MediaType.APPLICATION_JSON_VALUE); return (modelAndView != null) ? modelAndView : new ModelAndView(new MappingJackson2JsonView())
package com.guanmengyuan.spring.ex.web.config; @Slf4j public class GlobalErrorController extends BasicErrorController { public GlobalErrorController(ServerProperties serverProperties) { super(new DefaultErrorAttributes(), serverProperties.getError()); } @Override public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); Map<String, Object> model = Collections .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); ModelAndView modelAndView = resolveErrorView(request, response, status, model); Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL)); ServiceException serviceException = new ServiceException(status, body.get("error").toString(), "网络异常"); log.error("request error:{}", body.get("path") + ":" + body.get("error"), serviceException); response.setContentType(MediaType.APPLICATION_JSON_VALUE); return (modelAndView != null) ? modelAndView : new ModelAndView(new MappingJackson2JsonView())
.addAllObjects(BeanUtil.beanToMap(Res.error(serviceException), false, true));
0
2023-11-21 09:20:17+00:00
4k
Neelesh-Janga/23-Java-Design-Patterns
src/com/neelesh/design/patterns/creational/builder/products/Mobile.java
[ { "identifier": "Battery", "path": "src/com/neelesh/design/patterns/creational/builder/components/Battery.java", "snippet": "public class Battery {\n private int capacitymAh;\n private int currentChargePercentage;\n private boolean isCharging;\n private BatteryHealth health;\n private Str...
import com.neelesh.design.patterns.creational.builder.components.Battery; import com.neelesh.design.patterns.creational.builder.components.Camera; import com.neelesh.design.patterns.creational.builder.components.Display; import com.neelesh.design.patterns.creational.builder.components.Network;
2,511
package com.neelesh.design.patterns.creational.builder.products; public class Mobile { private String color; private boolean isWaterResistant; private boolean hasScreenProtection; private Battery battery; private Camera camera;
package com.neelesh.design.patterns.creational.builder.products; public class Mobile { private String color; private boolean isWaterResistant; private boolean hasScreenProtection; private Battery battery; private Camera camera;
private Display display;
2
2023-11-22 10:19:01+00:00
4k
angga7togk/LuckyCrates-PNX
src/main/java/angga7togk/luckycrates/listener/Listeners.java
[ { "identifier": "LuckyCrates", "path": "src/main/java/angga7togk/luckycrates/LuckyCrates.java", "snippet": "public class LuckyCrates extends PluginBase {\r\n\r\n @Getter\r\n private static LuckyCrates instance;\r\n public static Config crates, pos;\r\n public static int offsetIdEntity = 1;\r...
import angga7togk.luckycrates.LuckyCrates; import angga7togk.luckycrates.crates.Crates; import angga7togk.luckycrates.language.Languages; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.EventHandler; import cn.nukkit.event.Listener; import cn.nukkit.event.block.BlockBreakEvent; import cn.nukkit.event.player.PlayerInteractEvent; import cn.nukkit.event.player.PlayerQuitEvent; import java.util.Map; import java.util.Objects;
3,581
package angga7togk.luckycrates.listener; public class Listeners implements Listener { @EventHandler public void onQuit(PlayerQuitEvent event){ Player player = event.getPlayer(); LuckyCrates.setMode.remove(player); } @EventHandler public void onBreak(BlockBreakEvent event){ Player player = event.getPlayer(); Block block = event.getBlock(); Crates crates = new Crates();
package angga7togk.luckycrates.listener; public class Listeners implements Listener { @EventHandler public void onQuit(PlayerQuitEvent event){ Player player = event.getPlayer(); LuckyCrates.setMode.remove(player); } @EventHandler public void onBreak(BlockBreakEvent event){ Player player = event.getPlayer(); Block block = event.getBlock(); Crates crates = new Crates();
Map<String, String> lang = new Languages().getLanguage();
2
2023-11-20 08:04:22+00:00
4k
ca-webdev/exchange-backed-java
src/main/java/ca/webdev/exchange/web/OpenHighLowCloseComponent.java
[ { "identifier": "MatchingEngine", "path": "src/main/java/ca/webdev/exchange/matching/MatchingEngine.java", "snippet": "public class MatchingEngine {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(MatchingEngine.class);\n private final double tickSize;\n private final int tickS...
import ca.webdev.exchange.matching.MatchingEngine; import ca.webdev.exchange.web.model.OpenHighLowClose; import ca.webdev.exchange.web.websocket.Publisher; import org.springframework.stereotype.Component; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.SortedMap; import java.util.concurrent.ConcurrentSkipListMap;
2,976
package ca.webdev.exchange.web; @Component public class OpenHighLowCloseComponent { private final SortedMap<Instant, OpenHighLowClose> oneMinuteOhlcMap = new ConcurrentSkipListMap<>();
package ca.webdev.exchange.web; @Component public class OpenHighLowCloseComponent { private final SortedMap<Instant, OpenHighLowClose> oneMinuteOhlcMap = new ConcurrentSkipListMap<>();
public OpenHighLowCloseComponent(MatchingEngine matchingEngine, Publisher publisher) {
2
2023-11-20 16:03:59+00:00
4k
FalkorDB/JFalkorDB
src/main/java/com/falkordb/impl/api/AbstractGraph.java
[ { "identifier": "Graph", "path": "src/main/java/com/falkordb/Graph.java", "snippet": "public interface Graph extends Closeable {\n\n /**\n * Execute a Cypher query.\n * @param query Cypher query\n * @return a result set\n */\n ResultSet query(String query);\n\n /**\n * Execu...
import com.falkordb.Graph; import com.falkordb.ResultSet; import com.falkordb.impl.Utils; import java.util.List; import java.util.Map;
2,298
package com.falkordb.impl.api; /** * An abstract class to handle non implementation specific user requests */ public abstract class AbstractGraph implements Graph { /** * Sends a query to the redis graph. Implementation and context dependent * @param preparedQuery prepared query * @return Result set */ protected abstract ResultSet sendQuery(String preparedQuery); /** * Sends a read-only query to the redis graph. Implementation and context dependent * @param preparedQuery prepared query * @return Result set */ protected abstract ResultSet sendReadOnlyQuery(String preparedQuery); /** * Sends a query to the redis graph.Implementation and context dependent * @param preparedQuery prepared query * @param timeout timeout in milliseconds * @return Result set */ protected abstract ResultSet sendQuery(String preparedQuery, long timeout); /** * Sends a read-query to the redis graph.Implementation and context dependent * @param preparedQuery prepared query * @param timeout timeout in milliseconds * @return Result set */ protected abstract ResultSet sendReadOnlyQuery(String preparedQuery, long timeout); /** * Execute a Cypher query. * @param query Cypher query * @return a result set */ @Override public ResultSet query(String query) { return sendQuery(query); } /** * Execute a Cypher read-only query. * @param query Cypher query * @return a result set */ @Override public ResultSet readOnlyQuery(String query) { return sendReadOnlyQuery(query); } /** * Execute a Cypher query with timeout. * @param query Cypher query * @param timeout timeout in milliseconds * @return a result set */ @Override public ResultSet query(String query, long timeout) { return sendQuery(query, timeout); } /** * Execute a Cypher read-only query with timeout. * @param query Cypher query * @param timeout timeout in milliseconds * @return a result set */ @Override public ResultSet readOnlyQuery(String query, long timeout) { return sendReadOnlyQuery(query, timeout); } /** * Executes a cypher query with parameters. * @param query Cypher query. * @param params parameters map. * @return a result set. */ @Override public ResultSet query(String query, Map<String, Object> params) {
package com.falkordb.impl.api; /** * An abstract class to handle non implementation specific user requests */ public abstract class AbstractGraph implements Graph { /** * Sends a query to the redis graph. Implementation and context dependent * @param preparedQuery prepared query * @return Result set */ protected abstract ResultSet sendQuery(String preparedQuery); /** * Sends a read-only query to the redis graph. Implementation and context dependent * @param preparedQuery prepared query * @return Result set */ protected abstract ResultSet sendReadOnlyQuery(String preparedQuery); /** * Sends a query to the redis graph.Implementation and context dependent * @param preparedQuery prepared query * @param timeout timeout in milliseconds * @return Result set */ protected abstract ResultSet sendQuery(String preparedQuery, long timeout); /** * Sends a read-query to the redis graph.Implementation and context dependent * @param preparedQuery prepared query * @param timeout timeout in milliseconds * @return Result set */ protected abstract ResultSet sendReadOnlyQuery(String preparedQuery, long timeout); /** * Execute a Cypher query. * @param query Cypher query * @return a result set */ @Override public ResultSet query(String query) { return sendQuery(query); } /** * Execute a Cypher read-only query. * @param query Cypher query * @return a result set */ @Override public ResultSet readOnlyQuery(String query) { return sendReadOnlyQuery(query); } /** * Execute a Cypher query with timeout. * @param query Cypher query * @param timeout timeout in milliseconds * @return a result set */ @Override public ResultSet query(String query, long timeout) { return sendQuery(query, timeout); } /** * Execute a Cypher read-only query with timeout. * @param query Cypher query * @param timeout timeout in milliseconds * @return a result set */ @Override public ResultSet readOnlyQuery(String query, long timeout) { return sendReadOnlyQuery(query, timeout); } /** * Executes a cypher query with parameters. * @param query Cypher query. * @param params parameters map. * @return a result set. */ @Override public ResultSet query(String query, Map<String, Object> params) {
String preparedQuery = Utils.prepareQuery(query, params);
2
2023-11-26 13:38:14+00:00
4k
EcoNetsTech/spore-spring-boot-starter
src/main/java/cn/econets/ximutech/spore/retrofit/RetrofitClientFactoryBean.java
[ { "identifier": "RetrofitConfigBean", "path": "src/main/java/cn/econets/ximutech/spore/config/RetrofitConfigBean.java", "snippet": "@Data\npublic class RetrofitConfigBean {\n\n private final RetrofitProperties retrofitProperties;\n\n private RetryInterceptor retryInterceptor;\n\n private Loggin...
import cn.econets.ximutech.spore.*; import cn.econets.ximutech.spore.config.RetrofitConfigBean; import cn.econets.ximutech.spore.retrofit.adapter.*; import cn.econets.ximutech.spore.util.AppContextUtils; import cn.econets.ximutech.spore.*; import cn.econets.ximutech.spore.config.GlobalTimeoutProperty; import cn.econets.ximutech.spore.retrofit.adapter.*; import cn.econets.ximutech.spore.util.BeanExtendUtils; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.FactoryBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.EnvironmentAware; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.env.Environment; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.util.*; import java.util.concurrent.TimeUnit;
1,710
package cn.econets.ximutech.spore.retrofit; /** * retrofitClient 工厂 * * @author ximu */ public class RetrofitClientFactoryBean<T> implements FactoryBean<T>, EnvironmentAware, ApplicationContextAware { private static final Logger logger = LoggerFactory.getLogger(RetrofitClientFactoryBean.class); private final Class<T> targetClass; private Environment environment; private ApplicationContext applicationContext;
package cn.econets.ximutech.spore.retrofit; /** * retrofitClient 工厂 * * @author ximu */ public class RetrofitClientFactoryBean<T> implements FactoryBean<T>, EnvironmentAware, ApplicationContextAware { private static final Logger logger = LoggerFactory.getLogger(RetrofitClientFactoryBean.class); private final Class<T> targetClass; private Environment environment; private ApplicationContext applicationContext;
private RetrofitConfigBean retrofitConfigBean;
0
2023-11-21 18:00:50+00:00
4k
NBHZW/hnustDatabaseCourseDesign
ruoyi-studentInformation/src/main/java/com/ruoyi/studentInformation/service/impl/StudentServiceImpl.java
[ { "identifier": "StudentMapper", "path": "ruoyi-studentInformation/src/main/java/com/ruoyi/studentInformation/mapper/StudentMapper.java", "snippet": "public interface StudentMapper\n{\n /**\n * 查询学生信息\n *\n * @param id 学生信息主键\n * @return 学生信息\n */\n public Student selectStudent...
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.studentInformation.mapper.StudentMapper; import com.ruoyi.studentInformation.domain.Student; import com.ruoyi.studentInformation.service.IStudentService ;
1,606
package com.ruoyi.studentInformation.service.impl; /** * 【请填写功能名称】Service业务层处理 * * @author ruoyi * @date 2023-11-03 */ @Service public class StudentServiceImpl implements IStudentService { @Autowired
package com.ruoyi.studentInformation.service.impl; /** * 【请填写功能名称】Service业务层处理 * * @author ruoyi * @date 2023-11-03 */ @Service public class StudentServiceImpl implements IStudentService { @Autowired
private StudentMapper studentMapper;
0
2023-11-25 02:50:45+00:00
4k
isXander/YetAnotherUILib
src/main/java/dev/isxander/yaul3/impl/ui/PaddedBoxImpl.java
[ { "identifier": "IntState", "path": "src/main/java/dev/isxander/yaul3/api/ui/IntState.java", "snippet": "public interface IntState extends State<Integer> {\n static IntState of(int value) {\n return new IntStateImpl(value);\n }\n\n IntState plus(IntState other);\n\n IntState minus(Int...
import dev.isxander.yaul3.api.ui.IntState; import dev.isxander.yaul3.api.ui.LayoutWidget; import dev.isxander.yaul3.api.ui.PaddedBox; import dev.isxander.yaul3.api.ui.RenderLayer; import org.apache.commons.lang3.Validate;
1,825
package dev.isxander.yaul3.impl.ui; public class PaddedBoxImpl extends AbstractParentLayoutWidget implements PaddedBox { private final LayoutWidget widget; private IntState paddingLeft = IntState.of(0), paddingTop = IntState.of(0), paddingRight = IntState.of(0), paddingBottom = IntState.of(0); public PaddedBoxImpl(LayoutWidget widget) { super.addWidgets(this.widget = widget); } public PaddedBoxImpl() { this.widget = null; } @Override public boolean propagateDown() { if (widgets.isEmpty()) return false; Validate.isTrue(widgets.size() == 1, "PaddedBox can only have one child"); boolean changed = super.propagateDown(); changed |= widget.getX().set(getX().get() + paddingLeft.get()); changed |= widget.getY().set(getY().get() + paddingTop.get()); changed |= widget.getWidth().set(getWidth().get() - paddingLeft.get() - paddingRight.get()); changed |= widget.getHeight().set(getHeight().get() - paddingTop.get() - paddingBottom.get()); return changed; } @Override public PaddedBox fitChild() { if (widgets.isEmpty()) return this; this.getWidth().set(widget.getWidth().get()); this.getHeight().set(widget.getHeight().get()); return this; } @Override public PaddedBox setPadding(IntState padding) { return setPadding(padding, padding, padding, padding); } @Override public PaddedBox setPadding(IntState top, IntState right, IntState bottom, IntState left) { this.setPaddingTop(top); this.setPaddingRight(right); this.setPaddingBottom(bottom); this.setPaddingLeft(left); return this; } @Override public PaddedBox setPadding(IntState topBottom, IntState leftRight) { return setPadding(topBottom, leftRight, topBottom, leftRight); } @Override public PaddedBox setPaddingTop(IntState padding) { this.paddingTop = padding; return this; } @Override public PaddedBox setPaddingRight(IntState padding) { this.paddingRight = padding; return this; } @Override public PaddedBox setPaddingBottom(IntState padding) { this.paddingBottom = padding; return this; } @Override public PaddedBox setPaddingLeft(IntState padding) { this.paddingLeft = padding; return this; } @Override public IntState getPaddingTop() { return paddingTop; } @Override public IntState getPaddingRight() { return paddingRight; } @Override public IntState getPaddingBottom() { return paddingBottom; } @Override public IntState getPaddingLeft() { return paddingLeft; } @Override public PaddedBox addWidgets(LayoutWidget... widgets) { throw new UnsupportedOperationException("PaddedBox can only have one child"); } @Override public PaddedBox setX(IntState x) { super.setX(x); return this; } @Override public PaddedBox setY(IntState y) { super.setY(y); return this; } @Override public PaddedBox setWidth(IntState width) { super.setWidth(width); return this; } @Override public PaddedBox setHeight(IntState height) { super.setHeight(height); return this; } @Override
package dev.isxander.yaul3.impl.ui; public class PaddedBoxImpl extends AbstractParentLayoutWidget implements PaddedBox { private final LayoutWidget widget; private IntState paddingLeft = IntState.of(0), paddingTop = IntState.of(0), paddingRight = IntState.of(0), paddingBottom = IntState.of(0); public PaddedBoxImpl(LayoutWidget widget) { super.addWidgets(this.widget = widget); } public PaddedBoxImpl() { this.widget = null; } @Override public boolean propagateDown() { if (widgets.isEmpty()) return false; Validate.isTrue(widgets.size() == 1, "PaddedBox can only have one child"); boolean changed = super.propagateDown(); changed |= widget.getX().set(getX().get() + paddingLeft.get()); changed |= widget.getY().set(getY().get() + paddingTop.get()); changed |= widget.getWidth().set(getWidth().get() - paddingLeft.get() - paddingRight.get()); changed |= widget.getHeight().set(getHeight().get() - paddingTop.get() - paddingBottom.get()); return changed; } @Override public PaddedBox fitChild() { if (widgets.isEmpty()) return this; this.getWidth().set(widget.getWidth().get()); this.getHeight().set(widget.getHeight().get()); return this; } @Override public PaddedBox setPadding(IntState padding) { return setPadding(padding, padding, padding, padding); } @Override public PaddedBox setPadding(IntState top, IntState right, IntState bottom, IntState left) { this.setPaddingTop(top); this.setPaddingRight(right); this.setPaddingBottom(bottom); this.setPaddingLeft(left); return this; } @Override public PaddedBox setPadding(IntState topBottom, IntState leftRight) { return setPadding(topBottom, leftRight, topBottom, leftRight); } @Override public PaddedBox setPaddingTop(IntState padding) { this.paddingTop = padding; return this; } @Override public PaddedBox setPaddingRight(IntState padding) { this.paddingRight = padding; return this; } @Override public PaddedBox setPaddingBottom(IntState padding) { this.paddingBottom = padding; return this; } @Override public PaddedBox setPaddingLeft(IntState padding) { this.paddingLeft = padding; return this; } @Override public IntState getPaddingTop() { return paddingTop; } @Override public IntState getPaddingRight() { return paddingRight; } @Override public IntState getPaddingBottom() { return paddingBottom; } @Override public IntState getPaddingLeft() { return paddingLeft; } @Override public PaddedBox addWidgets(LayoutWidget... widgets) { throw new UnsupportedOperationException("PaddedBox can only have one child"); } @Override public PaddedBox setX(IntState x) { super.setX(x); return this; } @Override public PaddedBox setY(IntState y) { super.setY(y); return this; } @Override public PaddedBox setWidth(IntState width) { super.setWidth(width); return this; } @Override public PaddedBox setHeight(IntState height) { super.setHeight(height); return this; } @Override
public PaddedBox appendRenderLayers(RenderLayer... layers) {
3
2023-11-25 13:11:05+00:00
4k
DueWesternersProgramming/FRC-2023-Swerve-Offseason
src/main/java/frc/robot/subsystems/BaseSparkMaxPositionSubsystem.java
[ { "identifier": "EntechSubsystem", "path": "src/main/java/entech/subsystems/EntechSubsystem.java", "snippet": "public abstract class EntechSubsystem extends SubsystemBase {\n\n public EntechSubsystem() { \n }\n\tpublic abstract void initialize();\n\tpublic abstract boolean isEnabled();\n}" ...
import java.util.Optional; import com.revrobotics.CANSparkMax; import com.revrobotics.RelativeEncoder; import com.revrobotics.SparkMaxLimitSwitch; import com.revrobotics.SparkMaxLimitSwitch.Type; import edu.wpi.first.util.sendable.SendableBuilder; import edu.wpi.first.wpilibj.DriverStation; import entech.subsystems.EntechSubsystem; import frc.robot.RobotConstants; import frc.robot.controllers.PositionControllerConfig;
3,451
package frc.robot.subsystems; /** * Overview: * * This controller allows user to control a position oriented axis, including * managed homing to a lower limit switch. * * Overall, it works like this: * * user supplies a number of configuration optoins * * user requests moving to a position via requestPosition * * * When the user first requests a position,the axis wil home itself if not * homed. This consists of these steps * * (1) move at config.homingSpeed towards the lower limit * (2) when the lower limit switch is pressed, move fowrard config.backoffCounts * (3) when this position is reached, set position to config.homeCounts * (4) execute the users original move, by moving to requestedPosition * * Requests to move outside the soft limits ( config.mincounts and * config.maxcounts ) are ignored, but a warning is * logged to driver station * * @author davec * */ public abstract class BaseSparkMaxPositionSubsystem extends EntechSubsystem { public enum HomingState { FINDING_LIMIT, HOMED, UNINITIALIZED } public static final int CAN_TIMEOUT_MILLIS = 1000; protected CANSparkMax spark; private HomingState axisState = HomingState.UNINITIALIZED; protected boolean enabled = false;
package frc.robot.subsystems; /** * Overview: * * This controller allows user to control a position oriented axis, including * managed homing to a lower limit switch. * * Overall, it works like this: * * user supplies a number of configuration optoins * * user requests moving to a position via requestPosition * * * When the user first requests a position,the axis wil home itself if not * homed. This consists of these steps * * (1) move at config.homingSpeed towards the lower limit * (2) when the lower limit switch is pressed, move fowrard config.backoffCounts * (3) when this position is reached, set position to config.homeCounts * (4) execute the users original move, by moving to requestedPosition * * Requests to move outside the soft limits ( config.mincounts and * config.maxcounts ) are ignored, but a warning is * logged to driver station * * @author davec * */ public abstract class BaseSparkMaxPositionSubsystem extends EntechSubsystem { public enum HomingState { FINDING_LIMIT, HOMED, UNINITIALIZED } public static final int CAN_TIMEOUT_MILLIS = 1000; protected CANSparkMax spark; private HomingState axisState = HomingState.UNINITIALIZED; protected boolean enabled = false;
private PositionControllerConfig config;
2
2023-11-21 01:49:41+00:00
4k
kkyesyes/Multi-userCommunicationSystem-Client
src/com/kk/qqclient/service/ClientConnectServerThread.java
[ { "identifier": "Utility", "path": "src/com/kk/qqclient/utils/Utility.java", "snippet": "public class Utility {\n\t//静态属性。。。\n private static Scanner scanner = new Scanner(System.in);\n\n \n /**\n * 功能:读取键盘输入的一个菜单选项,值:1——5的范围\n * @return 1——5\n */\n\tpublic static char readMenuSelec...
import com.kk.qqclient.utils.Utility; import com.kk.qqcommon.Message; import com.kk.qqcommon.MessageType; import com.kk.qqcommon.Settings; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.net.Socket;
2,343
package com.kk.qqclient.service; /** * 客户端连接服务端线程 * * @author KK * @version 1.0 */ public class ClientConnectServerThread extends Thread { private Socket socket; public ClientConnectServerThread(Socket socket) { this.socket = socket; } @Override public void run() { while (true) { // System.out.println("客户端线程等待从服务端发送的消息"); try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); Message ms = (Message)ois.readObject(); switch (ms.getMesType()) { // 返回在线用户列表
package com.kk.qqclient.service; /** * 客户端连接服务端线程 * * @author KK * @version 1.0 */ public class ClientConnectServerThread extends Thread { private Socket socket; public ClientConnectServerThread(Socket socket) { this.socket = socket; } @Override public void run() { while (true) { // System.out.println("客户端线程等待从服务端发送的消息"); try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); Message ms = (Message)ois.readObject(); switch (ms.getMesType()) { // 返回在线用户列表
case MessageType.MESSAGE_RET_ONLINE_FRIEND:
2
2023-11-22 16:29:22+00:00
4k
partypankes/ProgettoCalcolatrice2023
ProgrammableCalculator/src/test/java/group21/calculator/test/ExecuteTest.java
[ { "identifier": "Execute", "path": "ProgrammableCalculator/src/main/java/group21/calculator/operation/Execute.java", "snippet": "public class Execute{\n\n private final StackNumber stack;\n private final Variables var;\n\n /**\n * Constructor to initialize the stack and variables.\n */\...
import group21.calculator.operation.Execute; import group21.calculator.type.ComplexNumber; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
2,145
package group21.calculator.test; class ExecuteTest { Execute exe;
package group21.calculator.test; class ExecuteTest { Execute exe;
ComplexNumber n1;
1
2023-11-19 16:11:56+00:00
4k
Staffilon/KestraDataOrchestrator
IoT Simulator/src/main/java/net/acesinc/data/json/generator/RandomJsonGenerator.java
[ { "identifier": "WorkflowConfig", "path": "IoT Simulator/src/main/java/net/acesinc/data/json/generator/config/WorkflowConfig.java", "snippet": "public class WorkflowConfig {\n\t//nome per il flusso di lavoro\n private String workflowName;\n //nome del flie di configurazione del flusso di lavoro da...
import java.io.IOException; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.json.Json; import javax.json.stream.JsonGenerator; import javax.json.stream.JsonGeneratorFactory; import org.apache.commons.math3.random.RandomDataGenerator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import net.acesinc.data.json.generator.config.WorkflowConfig; import net.acesinc.data.json.generator.types.TypeHandler; import net.acesinc.data.json.generator.types.TypeHandlerFactory; import net.acesinc.data.json.util.JsonUtils;
2,732
/* * 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 */ public class RandomJsonGenerator { private static final Logger log = LogManager.getLogger(RandomJsonGenerator.class); private SimpleDateFormat iso8601DF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); private Map<String, Object> config; private static JsonGeneratorFactory factory = Json.createGeneratorFactory(null); private Map<String, Object> generatedValues; private JsonUtils jsonUtils; private WorkflowConfig workflowConfig; public RandomJsonGenerator(Map<String, Object> config, WorkflowConfig workflowConfig) { this.config = config; this.workflowConfig = workflowConfig; jsonUtils = new JsonUtils();
/* * 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 */ public class RandomJsonGenerator { private static final Logger log = LogManager.getLogger(RandomJsonGenerator.class); private SimpleDateFormat iso8601DF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); private Map<String, Object> config; private static JsonGeneratorFactory factory = Json.createGeneratorFactory(null); private Map<String, Object> generatedValues; private JsonUtils jsonUtils; private WorkflowConfig workflowConfig; public RandomJsonGenerator(Map<String, Object> config, WorkflowConfig workflowConfig) { this.config = config; this.workflowConfig = workflowConfig; jsonUtils = new JsonUtils();
TypeHandlerFactory.getInstance().configure(workflowConfig);
2
2023-11-26 10:57:17+00:00
4k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jei/categories/lootbag/LootBagCategory.java
[ { "identifier": "JustEnoughMagiculture", "path": "src/main/java/com/invadermonky/justenoughmagiculture/JustEnoughMagiculture.java", "snippet": "@Mod(\n modid = JustEnoughMagiculture.MOD_ID,\n name = JustEnoughMagiculture.MOD_NAME,\n version = JustEnoughMagiculture.MOD_VERSION,\n ...
import com.invadermonky.justenoughmagiculture.JustEnoughMagiculture; import com.invadermonky.justenoughmagiculture.integrations.jei.JEICategories; import com.invadermonky.justenoughmagiculture.util.Reference; import jeresources.config.Settings; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.ingredients.VanillaTypes; import mezz.jei.api.recipe.IFocus; import mezz.jei.api.recipe.IRecipeCategory; import net.minecraft.client.resources.I18n; import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable;
1,974
package com.invadermonky.justenoughmagiculture.integrations.jei.categories.lootbag; public class LootBagCategory implements IRecipeCategory<LootBagWrapper> { protected static final int ITEMS_PER_ROW = 8; protected static final int ITEMS_PER_COLUMN = 4; protected static int SPACING_X = 166 / ITEMS_PER_ROW; protected static int SPACING_Y = 80 / ITEMS_PER_COLUMN; protected static int ITEMS_PER_PAGE = ITEMS_PER_COLUMN * ITEMS_PER_ROW; public LootBagCategory() {} @Override public String getUid() {
package com.invadermonky.justenoughmagiculture.integrations.jei.categories.lootbag; public class LootBagCategory implements IRecipeCategory<LootBagWrapper> { protected static final int ITEMS_PER_ROW = 8; protected static final int ITEMS_PER_COLUMN = 4; protected static int SPACING_X = 166 / ITEMS_PER_ROW; protected static int SPACING_Y = 80 / ITEMS_PER_COLUMN; protected static int ITEMS_PER_PAGE = ITEMS_PER_COLUMN * ITEMS_PER_ROW; public LootBagCategory() {} @Override public String getUid() {
return JEICategories.LOOT_BAG;
1
2023-11-19 23:09:14+00:00
4k
spring-cloud/spring-functions-catalog
function/spring-twitter-function/src/test/java/org/springframework/cloud/fn/twitter/geo/TwitterGeoFunctionTests.java
[ { "identifier": "TwitterConnectionProperties", "path": "common/spring-twitter-common/src/main/java/org/springframework/cloud/fn/common/twitter/TwitterConnectionProperties.java", "snippet": "@ConfigurationProperties(\"twitter.connection\")\n@Validated\npublic class TwitterConnectionProperties {\n\n\t/**\...
import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Function; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockserver.client.MockServerClient; import org.mockserver.integration.ClientAndServer; import twitter4j.conf.ConfigurationBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.fn.common.twitter.TwitterConnectionProperties; import org.springframework.cloud.fn.common.twitter.util.TwitterTestUtils; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; import org.springframework.util.MimeTypeUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.mockserver.matchers.Times.unlimited; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.verify.VerificationTimes.once;
1,601
/* * Copyright 2020-2024 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 org.springframework.cloud.fn.twitter.geo; /** * @author Christian Tzolov */ @SpringBootTest(properties = { "twitter.connection.consumerKey=consumerKey666", "twitter.connection.consumerSecret=consumerSecret666", "twitter.connection.accessToken=accessToken666", "twitter.connection.accessTokenSecret=accessTokenSecret666" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public abstract class TwitterGeoFunctionTests { private static final String MOCK_SERVER_IP = "127.0.0.1"; private static ClientAndServer mockServer; private static MockServerClient mockClient; @Autowired protected Function<Message<?>, Message<byte[]>> twitterUsersFunction; public static void recordRequestExpectation(Map<String, List<String>> parameters) { mockClient .when(request().withMethod("GET").withPath("/geo/search.json").withQueryStringParameters(parameters), unlimited()) .respond(response().withStatusCode(200) .withHeader("Content-Type", "application/json; charset=utf-8")
/* * Copyright 2020-2024 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 org.springframework.cloud.fn.twitter.geo; /** * @author Christian Tzolov */ @SpringBootTest(properties = { "twitter.connection.consumerKey=consumerKey666", "twitter.connection.consumerSecret=consumerSecret666", "twitter.connection.accessToken=accessToken666", "twitter.connection.accessTokenSecret=accessTokenSecret666" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public abstract class TwitterGeoFunctionTests { private static final String MOCK_SERVER_IP = "127.0.0.1"; private static ClientAndServer mockServer; private static MockServerClient mockClient; @Autowired protected Function<Message<?>, Message<byte[]>> twitterUsersFunction; public static void recordRequestExpectation(Map<String, List<String>> parameters) { mockClient .when(request().withMethod("GET").withPath("/geo/search.json").withQueryStringParameters(parameters), unlimited()) .respond(response().withStatusCode(200) .withHeader("Content-Type", "application/json; charset=utf-8")
.withBody(TwitterTestUtils.asString("classpath:/response/search_places_amsterdam.json"))
1
2023-11-21 04:03:30+00:00
4k
Provismet/ProviHealth
src/main/java/com/provismet/provihealth/compat/SelfApiHook.java
[ { "identifier": "ProviHealthClient", "path": "src/main/java/com/provismet/provihealth/ProviHealthClient.java", "snippet": "public class ProviHealthClient implements ClientModInitializer {\n public static final String MODID = \"provihealth\";\n public static final Logger LOGGER = LoggerFactory.getL...
import com.provismet.provihealth.ProviHealthClient; import com.provismet.provihealth.api.ProviHealthApi; import net.minecraft.entity.EntityGroup; import net.minecraft.item.Items;
2,950
package com.provismet.provihealth.compat; public class SelfApiHook implements ProviHealthApi { @Override public void onInitialize () { this.registerIcon(EntityGroup.AQUATIC, Items.COD); this.registerIcon(EntityGroup.ARTHROPOD, Items.COBWEB); this.registerIcon(EntityGroup.ILLAGER, Items.IRON_AXE); this.registerIcon(EntityGroup.UNDEAD, Items.ROTTEN_FLESH);
package com.provismet.provihealth.compat; public class SelfApiHook implements ProviHealthApi { @Override public void onInitialize () { this.registerIcon(EntityGroup.AQUATIC, Items.COD); this.registerIcon(EntityGroup.ARTHROPOD, Items.COBWEB); this.registerIcon(EntityGroup.ILLAGER, Items.IRON_AXE); this.registerIcon(EntityGroup.UNDEAD, Items.ROTTEN_FLESH);
this.registerPortrait(EntityGroup.AQUATIC, ProviHealthClient.identifier("textures/gui/healthbars/aquatic.png"));
0
2023-11-26 02:46:37+00:00
4k
OysterRiverOverdrive/SwerveTemplate
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "TeleopCmd", "path": "src/main/java/frc/robot/commands/TeleopCmd.java", "snippet": "public class TeleopCmd extends Command {\n /** Creates a new TeleopCmd. */\n private final DrivetrainSubsystem driveSub;\n // Create a controller object\n private final Joystick controller = new Joyst...
import frc.robot.subsystems.DrivetrainSubsystem; import edu.wpi.first.wpilibj2.command.Command; import frc.robot.commands.TeleopCmd;
3,272
// 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; public class RobotContainer { // Subsystems private final DrivetrainSubsystem drivetrain = new DrivetrainSubsystem(); // Commands
// 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; public class RobotContainer { // Subsystems private final DrivetrainSubsystem drivetrain = new DrivetrainSubsystem(); // Commands
private final TeleopCmd teleopCmd = new TeleopCmd(drivetrain);
0
2023-11-19 18:40:10+00:00
4k
EnigmaGuest/fnk-server
service-api/service-api-admin/src/main/java/fun/isite/service/api/admin/controller/AccountController.java
[ { "identifier": "RestResponse", "path": "service-common/service-common-bean/src/main/java/fun/isite/service/common/bean/http/RestResponse.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Schema(name = \"RestResponse\", description = \"接口响应\")\n@Slf4j\npublic class RestResponse<T> impl...
import fun.isite.service.common.bean.http.RestResponse; import fun.isite.service.core.basic.annotation.AnonymousApi; import fun.isite.service.core.basic.controller.BaseController; import fun.isite.service.core.basic.vo.TokenVO; import fun.isite.service.core.system.dto.LoginAdminDTO; import fun.isite.service.core.system.service.IAdminUserService; import fun.isite.service.core.system.vo.AdminUserVO; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.AllArgsConstructor; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*;
2,230
package fun.isite.service.api.admin.controller; /** * @author Enigma */ @RestController @RequestMapping("/account") @Tag(name = "认证接口") @AllArgsConstructor @AnonymousApi public class AccountController extends BaseController { private IAdminUserService adminUserService; @PostMapping("/login") @Operation(summary = "登录")
package fun.isite.service.api.admin.controller; /** * @author Enigma */ @RestController @RequestMapping("/account") @Tag(name = "认证接口") @AllArgsConstructor @AnonymousApi public class AccountController extends BaseController { private IAdminUserService adminUserService; @PostMapping("/login") @Operation(summary = "登录")
public RestResponse<TokenVO> create(@RequestBody @Validated LoginAdminDTO dto) {
2
2023-12-26 01:55:01+00:00
4k
yutianqaq/BypassAV-Online
BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/controller/CodeController.java
[ { "identifier": "ApplicationProperties", "path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/config/ApplicationProperties.java", "snippet": "@Getter\n@Setter\n@Configuration\n@ConfigurationProperties(prefix = \"bypassav\")\npublic class ApplicationProperties {\n private String templat...
import com.fasterxml.jackson.databind.ObjectMapper; import com.yutian4090.bypass.config.ApplicationProperties; import com.yutian4090.bypass.dto.CompilationResponseDTO; import com.yutian4090.bypass.dto.CompileRequestDTO; import com.yutian4090.bypass.enums.Result; import com.yutian4090.bypass.service.CompileService; import com.yutian4090.bypass.utils.TextFileProcessor; import jakarta.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import static com.yutian4090.bypass.utils.FileProcessor.*;
2,897
package com.yutian4090.bypass.controller; @RestController public class CodeController { private static ApplicationProperties applicationProperties; @Autowired private ObjectMapper objectMapper; @Autowired public void setApplicationProperties(ApplicationProperties applicationProperties) { CodeController.applicationProperties = applicationProperties; } @Resource
package com.yutian4090.bypass.controller; @RestController public class CodeController { private static ApplicationProperties applicationProperties; @Autowired private ObjectMapper objectMapper; @Autowired public void setApplicationProperties(ApplicationProperties applicationProperties) { CodeController.applicationProperties = applicationProperties; } @Resource
CompileService CompileService;
4
2023-12-28 06:22:12+00:00
4k
37214728aaa/android_key_logger
app/src/main/java/com/maemresen/infsec/keylogapp/KeyLogger.java
[ { "identifier": "KeyLog", "path": "app/src/main/java/com/maemresen/infsec/keylogapp/model/KeyLog.java", "snippet": "public class KeyLog {\n\n private String uuid;\n private Date keyLogDate;\n private String accessibilityEvent;\n private String msg;\n\n\n public String getUuid() {\n ...
import android.accessibilityservice.AccessibilityService; import android.util.Log; import android.view.accessibility.AccessibilityEvent; import com.android.volley.AuthFailureError; import com.android.volley.RequestQueue; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.maemresen.infsec.keylogapp.model.KeyLog; import com.maemresen.infsec.keylogapp.util.DateTimeHelper; import com.maemresen.infsec.keylogapp.util.Helper; import org.json.JSONObject; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map;
2,151
package com.maemresen.infsec.keylogapp; /** * @author Emre Sen, 14.05.2019 * @contact maemresen07@gmail.com */ public class KeyLogger extends AccessibilityService { private final static String LOG_TAG = Helper.getLogTag(KeyLogger.class); @Override public void onServiceConnected() { Log.i(LOG_TAG, "Starting service"); } @Override public void onAccessibilityEvent(AccessibilityEvent event) { String uuid = Helper.getUuid(); Date now = DateTimeHelper.getCurrentDay(); String accessibilityEvent = null; String msg = null; switch (event.getEventType()) { case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED: { accessibilityEvent = "TYPE_VIEW_TEXT_CHANGED"; msg = String.valueOf(event.getText()); break; } case AccessibilityEvent.TYPE_VIEW_FOCUSED: { accessibilityEvent = "TYPE_VIEW_FOCUSED"; msg = String.valueOf(event.getText()); break; } case AccessibilityEvent.TYPE_VIEW_CLICKED: { accessibilityEvent = "TYPE_VIEW_CLICKED"; msg = String.valueOf(event.getText()); break; } default: } if (accessibilityEvent == null) { return; } Log.i(LOG_TAG, msg);
package com.maemresen.infsec.keylogapp; /** * @author Emre Sen, 14.05.2019 * @contact maemresen07@gmail.com */ public class KeyLogger extends AccessibilityService { private final static String LOG_TAG = Helper.getLogTag(KeyLogger.class); @Override public void onServiceConnected() { Log.i(LOG_TAG, "Starting service"); } @Override public void onAccessibilityEvent(AccessibilityEvent event) { String uuid = Helper.getUuid(); Date now = DateTimeHelper.getCurrentDay(); String accessibilityEvent = null; String msg = null; switch (event.getEventType()) { case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED: { accessibilityEvent = "TYPE_VIEW_TEXT_CHANGED"; msg = String.valueOf(event.getText()); break; } case AccessibilityEvent.TYPE_VIEW_FOCUSED: { accessibilityEvent = "TYPE_VIEW_FOCUSED"; msg = String.valueOf(event.getText()); break; } case AccessibilityEvent.TYPE_VIEW_CLICKED: { accessibilityEvent = "TYPE_VIEW_CLICKED"; msg = String.valueOf(event.getText()); break; } default: } if (accessibilityEvent == null) { return; } Log.i(LOG_TAG, msg);
KeyLog keyLog = new KeyLog();
0
2023-12-27 12:35:31+00:00
4k
codingmiao/hppt
sc/src/main/java/org/wowtools/hppt/sc/service/ClientPort.java
[ { "identifier": "BytesUtil", "path": "common/src/main/java/org/wowtools/hppt/common/util/BytesUtil.java", "snippet": "public class BytesUtil {\n /**\n * 按每个数组的最大长度限制,将一个数组拆分为多个\n *\n * @param originalArray 原数组\n * @param maxChunkSize 最大长度限制\n * @return 拆分结果\n */\n public s...
import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.ByteToMessageDecoder; import lombok.extern.slf4j.Slf4j; import org.wowtools.hppt.common.util.BytesUtil; import org.wowtools.hppt.sc.StartSc; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
2,813
package org.wowtools.hppt.sc.service; /** * 客户端端口 * * @author liuyu * @date 2023/11/17 */ @Slf4j public class ClientPort { @FunctionalInterface public interface OnClientConn { void on(ClientPort clientPort, ChannelHandlerContext channelHandlerContext); } private final OnClientConn onClientConn; private final ClientPort clientPort = this; public ClientPort(int localPort, OnClientConn onClientConn) { this.onClientConn = onClientConn; EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); Thread.startVirtualThread(() -> { try { int bufferSize = StartSc.config.maxSendBodySize * 100 / 1024 * 1024; ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_SNDBUF, bufferSize) .childOption(ChannelOption.SO_RCVBUF, bufferSize) // .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { // ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO)); ch.pipeline().addLast(new SimpleHandler()); ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(bufferSize)); ch.config().setSendBufferSize(bufferSize); } }); // 绑定端口,启动服务器 b.bind(localPort).sync().channel().closeFuture().sync(); } catch (Exception e) { throw new RuntimeException(e); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }); } private final Map<ChannelHandlerContext, ClientSession> clientSessionMapByCtx = new ConcurrentHashMap<>(); private class SimpleHandler extends ByteToMessageDecoder { @Override public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception { log.debug("client channelActive {}", channelHandlerContext.hashCode()); super.channelActive(channelHandlerContext); //用户发起新连接 触发onClientConn事件 onClientConn.on(clientPort, channelHandlerContext); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { log.debug("client channelInactive {}", ctx.hashCode()); super.channelInactive(ctx); ClientSession clientSession = clientSessionMapByCtx.get(ctx); if (null != clientSession) { ClientSessionManager.disposeClientSession(clientSession, "client channelInactive"); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { log.debug("client exceptionCaught {}", ctx.hashCode(), cause); ClientSession clientSession = clientSessionMapByCtx.get(ctx); if (null != clientSession) { ClientSessionManager.disposeClientSession(clientSession, "client exceptionCaught"); } } @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
package org.wowtools.hppt.sc.service; /** * 客户端端口 * * @author liuyu * @date 2023/11/17 */ @Slf4j public class ClientPort { @FunctionalInterface public interface OnClientConn { void on(ClientPort clientPort, ChannelHandlerContext channelHandlerContext); } private final OnClientConn onClientConn; private final ClientPort clientPort = this; public ClientPort(int localPort, OnClientConn onClientConn) { this.onClientConn = onClientConn; EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); Thread.startVirtualThread(() -> { try { int bufferSize = StartSc.config.maxSendBodySize * 100 / 1024 * 1024; ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_SNDBUF, bufferSize) .childOption(ChannelOption.SO_RCVBUF, bufferSize) // .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { // ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO)); ch.pipeline().addLast(new SimpleHandler()); ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(bufferSize)); ch.config().setSendBufferSize(bufferSize); } }); // 绑定端口,启动服务器 b.bind(localPort).sync().channel().closeFuture().sync(); } catch (Exception e) { throw new RuntimeException(e); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }); } private final Map<ChannelHandlerContext, ClientSession> clientSessionMapByCtx = new ConcurrentHashMap<>(); private class SimpleHandler extends ByteToMessageDecoder { @Override public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception { log.debug("client channelActive {}", channelHandlerContext.hashCode()); super.channelActive(channelHandlerContext); //用户发起新连接 触发onClientConn事件 onClientConn.on(clientPort, channelHandlerContext); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { log.debug("client channelInactive {}", ctx.hashCode()); super.channelInactive(ctx); ClientSession clientSession = clientSessionMapByCtx.get(ctx); if (null != clientSession) { ClientSessionManager.disposeClientSession(clientSession, "client channelInactive"); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { log.debug("client exceptionCaught {}", ctx.hashCode(), cause); ClientSession clientSession = clientSessionMapByCtx.get(ctx); if (null != clientSession) { ClientSessionManager.disposeClientSession(clientSession, "client exceptionCaught"); } } @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
byte[] bytes = BytesUtil.byteBuf2bytes(byteBuf);
0
2023-12-22 14:14:27+00:00
4k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/pathfinder/movement/MovementPathfinder.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.AllArgsConstructor; import lombok.Data; import me.earth.phobot.Phobot; import me.earth.phobot.event.MoveEvent; import me.earth.phobot.event.PathfinderUpdateEvent; import me.earth.phobot.event.RenderEvent; import me.earth.phobot.pathfinder.Path; import me.earth.phobot.pathfinder.algorithm.AlgorithmRenderer; import me.earth.phobot.pathfinder.mesh.MeshNode; import me.earth.phobot.util.NullabilityUtil; import me.earth.pingbypass.PingBypass; import me.earth.pingbypass.api.event.SubscriberImpl; import me.earth.pingbypass.api.event.listeners.generic.Listener; import me.earth.pingbypass.commons.event.SafeListener; import me.earth.pingbypass.commons.event.network.PacketEvent; import me.earth.pingbypass.commons.event.network.ReceiveListener; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; import static net.minecraft.ChatFormatting.RED;
2,857
package me.earth.phobot.pathfinder.movement; public class MovementPathfinder extends SubscriberImpl { protected State state; public MovementPathfinder(PingBypass pingBypass) {
package me.earth.phobot.pathfinder.movement; public class MovementPathfinder extends SubscriberImpl { protected State state; public MovementPathfinder(PingBypass pingBypass) {
listen(new SafeListener<PathfinderUpdateEvent>(pingBypass.getMinecraft()) {
2
2023-12-22 14:32:16+00:00
4k
Video-Hub-Org/video-hub
backend/src/main/java/org/videohub/demo/RedBookDownloaderNode.java
[ { "identifier": "VideoHubConstants", "path": "backend/src/main/java/org/videohub/constant/VideoHubConstants.java", "snippet": "public class VideoHubConstants {\n // 文件下载路径,默认为项目同级目录下\n public static final String VIDEOHUB_FILEPATH = \"videoHubDownload/\";\n\n public static final String USER_AGEN...
import lombok.extern.slf4j.Slf4j; import org.springframework.util.CollectionUtils; import org.videohub.constant.VideoHubConstants; import org.videohub.controller.RedBookController; import org.videohub.model.RedBookRequest; import org.videohub.service.RedBookService; import org.videohub.utils.VideoHubUtils; import java.util.List;
3,447
package org.videohub.demo; /** * 本地运行-小红书批量笔记下载 * 如果你是把笔记链接直接放到了redbook-node.link文件里,可以直接运行这个类 * * @author @fmz200 * @date 2023-12-18 */ @Slf4j public class RedBookDownloaderNode { public static void main(String[] args) { // 小红书笔记的分享链接
package org.videohub.demo; /** * 本地运行-小红书批量笔记下载 * 如果你是把笔记链接直接放到了redbook-node.link文件里,可以直接运行这个类 * * @author @fmz200 * @date 2023-12-18 */ @Slf4j public class RedBookDownloaderNode { public static void main(String[] args) { // 小红书笔记的分享链接
RedBookRequest redBookRequest = new RedBookRequest();
2
2023-12-23 03:43:13+00:00
4k
ArmanKhanDev/FakepixelDungeonHelper
build/sources/main/java/io/github/quantizr/utils/Utils.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"...
import com.google.gson.JsonElement; import io.github.quantizr.DungeonRooms; import io.github.quantizr.handlers.ScoreboardHandler; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.util.BlockPos; import net.minecraft.world.World; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*;
2,604
package io.github.quantizr.utils; public class Utils { /* checkForSkyblock and checkForDungeons were taken from Danker's Skyblock Mod (https://github.com/bowser0000/SkyblockMod/). Those methods were released under GNU General Public License v3.0 and remains under said license. Modified by Quantizr (_risk) in Feb. 2021. */ public static boolean inSkyblock = false; public static boolean inDungeons = false; public static boolean dungeonOverride = false; public static BlockPos originBlock = null; public static String originCorner = null; public static void checkForSkyblock() { Minecraft mc = Minecraft.getMinecraft(); if (mc != null && mc.theWorld != null && !mc.isSingleplayer()) { ScoreObjective scoreboardObj = mc.theWorld.getScoreboard().getObjectiveInDisplaySlot(1); if (scoreboardObj != null) {
package io.github.quantizr.utils; public class Utils { /* checkForSkyblock and checkForDungeons were taken from Danker's Skyblock Mod (https://github.com/bowser0000/SkyblockMod/). Those methods were released under GNU General Public License v3.0 and remains under said license. Modified by Quantizr (_risk) in Feb. 2021. */ public static boolean inSkyblock = false; public static boolean inDungeons = false; public static boolean dungeonOverride = false; public static BlockPos originBlock = null; public static String originCorner = null; public static void checkForSkyblock() { Minecraft mc = Minecraft.getMinecraft(); if (mc != null && mc.theWorld != null && !mc.isSingleplayer()) { ScoreObjective scoreboardObj = mc.theWorld.getScoreboard().getObjectiveInDisplaySlot(1); if (scoreboardObj != null) {
String scObjName = ScoreboardHandler.cleanSB(scoreboardObj.getDisplayName());
1
2023-12-22 04:44:39+00:00
4k
PENEKhun/baekjoon-java-starter
src/main/java/kr/huni/Main.java
[ { "identifier": "JavaCodeGenerator", "path": "src/main/java/kr/huni/code_generator/JavaCodeGenerator.java", "snippet": "@Slf4j\npublic class JavaCodeGenerator implements CodeGenerator {\n\n @Override\n public GeneratedCode generate(Problem problem) {\n if (problem.getTestCases() == null) {\n t...
import java.util.Scanner; import kr.huni.code_generator.JavaCodeGenerator; import kr.huni.code_runner.IdeaCodeOpenManager; import kr.huni.file_generator.JavaSourceCodeFile; import kr.huni.problem_parser.BaekjoonProblemParser; import kr.huni.problem_parser.JsoupWebParser; import kr.huni.user_configuration.UserConfigurationLoader; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j;
1,995
package kr.huni; @Slf4j @RequiredArgsConstructor public class Main { public static void main(String[] args) throws IllegalArgumentException { UserConfigurationLoader.getInstance(); Scanner scanner = new Scanner(System.in); log.info("백준 문제 번호를 입력해 주세요: "); int problemNumber = scanner.nextInt(); BojStarter bojStarter = new BojStarter( new IdeaCodeOpenManager(),
package kr.huni; @Slf4j @RequiredArgsConstructor public class Main { public static void main(String[] args) throws IllegalArgumentException { UserConfigurationLoader.getInstance(); Scanner scanner = new Scanner(System.in); log.info("백준 문제 번호를 입력해 주세요: "); int problemNumber = scanner.nextInt(); BojStarter bojStarter = new BojStarter( new IdeaCodeOpenManager(),
new JavaSourceCodeFile(),
2
2023-12-22 09:23:38+00:00
4k
R2turnTrue/chzzk4j
src/main/java/xyz/r2turntrue/chzzk4j/Chzzk.java
[ { "identifier": "ChzzkChat", "path": "src/main/java/xyz/r2turntrue/chzzk4j/chat/ChzzkChat.java", "snippet": "public class ChzzkChat {\n Chzzk chzzk;\n\n boolean isConnectedToWebsocket = false;\n private ChatWebsocketClient client;\n ArrayList<ChatEventListener> listeners = new ArrayList<>();...
import com.google.gson.Gson; import com.google.gson.JsonElement; import okhttp3.OkHttpClient; import okhttp3.Request; import xyz.r2turntrue.chzzk4j.chat.ChzzkChat; import xyz.r2turntrue.chzzk4j.exception.ChannelNotExistsException; import xyz.r2turntrue.chzzk4j.exception.NotExistsException; import xyz.r2turntrue.chzzk4j.exception.NotLoggedInException; import xyz.r2turntrue.chzzk4j.types.ChzzkFollowingStatusResponse; import xyz.r2turntrue.chzzk4j.types.ChzzkUser; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannelFollowingData; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannelRules; import xyz.r2turntrue.chzzk4j.util.RawApiUtils; import java.io.IOException;
3,203
package xyz.r2turntrue.chzzk4j; public class Chzzk { public static String API_URL = "https://api.chzzk.naver.com"; public static String GAME_API_URL = "https://comm-api.game.naver.com/nng_main"; public boolean isDebug = false; private String nidAuth; private String nidSession; private boolean isAnonymous; private OkHttpClient httpClient; private Gson gson; Chzzk(ChzzkBuilder chzzkBuilder) { this.nidAuth = chzzkBuilder.nidAuth; this.nidSession = chzzkBuilder.nidSession; this.isAnonymous = chzzkBuilder.isAnonymous; this.gson = new Gson(); OkHttpClient.Builder httpBuilder = new OkHttpClient().newBuilder(); if (!chzzkBuilder.isAnonymous) { httpBuilder.addInterceptor(chain -> { Request original = chain.request(); Request authorized = original.newBuilder() .addHeader("Cookie", "NID_AUT=" + chzzkBuilder.nidAuth + "; " + "NID_SES=" + chzzkBuilder.nidSession) .build(); return chain.proceed(authorized); }); } httpClient = httpBuilder.build(); } /** * Get this {@link Chzzk} logged in. */ public boolean isLoggedIn() { return !isAnonymous; } /** * Get new an instance of {@link ChzzkChat} with this {@link Chzzk}. */
package xyz.r2turntrue.chzzk4j; public class Chzzk { public static String API_URL = "https://api.chzzk.naver.com"; public static String GAME_API_URL = "https://comm-api.game.naver.com/nng_main"; public boolean isDebug = false; private String nidAuth; private String nidSession; private boolean isAnonymous; private OkHttpClient httpClient; private Gson gson; Chzzk(ChzzkBuilder chzzkBuilder) { this.nidAuth = chzzkBuilder.nidAuth; this.nidSession = chzzkBuilder.nidSession; this.isAnonymous = chzzkBuilder.isAnonymous; this.gson = new Gson(); OkHttpClient.Builder httpBuilder = new OkHttpClient().newBuilder(); if (!chzzkBuilder.isAnonymous) { httpBuilder.addInterceptor(chain -> { Request original = chain.request(); Request authorized = original.newBuilder() .addHeader("Cookie", "NID_AUT=" + chzzkBuilder.nidAuth + "; " + "NID_SES=" + chzzkBuilder.nidSession) .build(); return chain.proceed(authorized); }); } httpClient = httpBuilder.build(); } /** * Get this {@link Chzzk} logged in. */ public boolean isLoggedIn() { return !isAnonymous; } /** * Get new an instance of {@link ChzzkChat} with this {@link Chzzk}. */
public ChzzkChat chat() {
0
2023-12-30 20:01:23+00:00
4k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/entrypoints/BackgroundService.java
[ { "identifier": "LauncherWindow", "path": "app/src/main/java/net/lonelytransistor/launcher/LauncherWindow.java", "snippet": "@SuppressLint(\"RestrictedApi\")\npublic class LauncherWindow extends GenericWindow {\n private static final String TAG = \"LauncherWindow\";\n\n private final Executor exec...
import android.content.Context; import android.content.Intent; import net.lonelytransistor.commonlib.ForegroundService; import net.lonelytransistor.launcher.LauncherWindow; import net.lonelytransistor.launcher.RecentsWindow; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
3,289
package net.lonelytransistor.launcher.entrypoints; public class BackgroundService extends ForegroundService { public BackgroundService() {}
package net.lonelytransistor.launcher.entrypoints; public class BackgroundService extends ForegroundService { public BackgroundService() {}
private LauncherWindow mLauncher = null;
0
2023-12-28 18:24:12+00:00
4k
Patbox/GlideAway
src/main/java/eu/pb4/glideaway/entity/GliderEntity.java
[ { "identifier": "GlideItems", "path": "src/main/java/eu/pb4/glideaway/item/GlideItems.java", "snippet": "public class GlideItems {\n\n public static final WindInABottleItem WIND_IN_A_BOTTLE = register(\"wind_in_a_bottle\", new WindInABottleItem(new Item.Settings().maxCount(2), true));\n public sta...
import eu.pb4.glideaway.item.GlideItems; import eu.pb4.glideaway.item.HangGliderItem; import eu.pb4.glideaway.util.GlideDimensionTypeTags; import eu.pb4.glideaway.util.GlideGamerules; import eu.pb4.glideaway.util.GlideSoundEvents; import eu.pb4.polymer.core.api.entity.PolymerEntity; import eu.pb4.polymer.virtualentity.api.ElementHolder; import eu.pb4.polymer.virtualentity.api.VirtualEntityUtils; import eu.pb4.polymer.virtualentity.api.attachment.EntityAttachment; import eu.pb4.polymer.virtualentity.api.elements.InteractionElement; import eu.pb4.polymer.virtualentity.api.tracker.DisplayTrackedData; import net.minecraft.block.Blocks; import net.minecraft.block.DispenserBlock; import net.minecraft.entity.*; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.data.DataTracker; import net.minecraft.entity.data.TrackedData; import net.minecraft.entity.data.TrackedDataHandlerRegistry; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.DyeableItem; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; import net.minecraft.network.packet.s2c.play.PlaySoundFromEntityS2CPacket; import net.minecraft.particle.ItemStackParticleEffect; import net.minecraft.particle.ParticleTypes; import net.minecraft.registry.tag.DamageTypeTags; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.text.Text; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.math.*; import net.minecraft.world.World; import net.minecraft.world.event.GameEvent; import org.jetbrains.annotations.Nullable; import org.joml.Quaternionf; import org.joml.Vector3f; import java.util.List;
2,728
package eu.pb4.glideaway.entity; public class GliderEntity extends Entity implements PolymerEntity { private static final TrackedData<Float> ROLL = DataTracker.registerData(GliderEntity.class, TrackedDataHandlerRegistry.FLOAT); private ItemStack itemStack = GlideItems.HANG_GLIDER.getDefaultStack(); private ItemStack modelStack = GlideItems.HANG_GLIDER.getDefaultStack(); private int damageTimer; private int lastAttack = -999; private final ElementHolder holder = new ElementHolder(); private int soundTimer; private int attacks; public static boolean create(World world, LivingEntity rider, ItemStack stack, Hand hand) { if (rider.hasVehicle() || (rider.isSneaking() && !world.getGameRules().getBoolean(GlideGamerules.ALLOW_SNEAK_RELEASE))) { return false; } stack.damage((int) Math.max(0, -rider.getVelocity().y * world.getGameRules().get(GlideGamerules.INITIAL_VELOCITY_GLIDER_DAMAGE).get() * (90 - Math.abs(MathHelper.clamp(rider.getPitch(), -30, 80))) / 90), rider, player -> player.sendEquipmentBreakStatus(hand == Hand.MAIN_HAND ? EquipmentSlot.MAINHAND : EquipmentSlot.OFFHAND)); if (stack.isEmpty()) { return false; } var entity = new GliderEntity(GlideEntities.GLIDER, world); var sitting = rider.getDimensions(EntityPose.SITTING); var currentDim = rider.getDimensions(rider.getPose()); entity.setItemStack(stack); entity.setPosition(rider.getPos().add(0, currentDim.height - sitting.height - rider.getRidingOffset(entity), 0)); entity.setYaw(rider.getYaw()); entity.setPitch(rider.getPitch()); entity.setVelocity(rider.getVelocity().add(rider.getRotationVector().multiply(0.2, 0.02, 0.2).multiply(rider.isSneaking() ? 2 : 1))); world.spawnEntity(entity);
package eu.pb4.glideaway.entity; public class GliderEntity extends Entity implements PolymerEntity { private static final TrackedData<Float> ROLL = DataTracker.registerData(GliderEntity.class, TrackedDataHandlerRegistry.FLOAT); private ItemStack itemStack = GlideItems.HANG_GLIDER.getDefaultStack(); private ItemStack modelStack = GlideItems.HANG_GLIDER.getDefaultStack(); private int damageTimer; private int lastAttack = -999; private final ElementHolder holder = new ElementHolder(); private int soundTimer; private int attacks; public static boolean create(World world, LivingEntity rider, ItemStack stack, Hand hand) { if (rider.hasVehicle() || (rider.isSneaking() && !world.getGameRules().getBoolean(GlideGamerules.ALLOW_SNEAK_RELEASE))) { return false; } stack.damage((int) Math.max(0, -rider.getVelocity().y * world.getGameRules().get(GlideGamerules.INITIAL_VELOCITY_GLIDER_DAMAGE).get() * (90 - Math.abs(MathHelper.clamp(rider.getPitch(), -30, 80))) / 90), rider, player -> player.sendEquipmentBreakStatus(hand == Hand.MAIN_HAND ? EquipmentSlot.MAINHAND : EquipmentSlot.OFFHAND)); if (stack.isEmpty()) { return false; } var entity = new GliderEntity(GlideEntities.GLIDER, world); var sitting = rider.getDimensions(EntityPose.SITTING); var currentDim = rider.getDimensions(rider.getPose()); entity.setItemStack(stack); entity.setPosition(rider.getPos().add(0, currentDim.height - sitting.height - rider.getRidingOffset(entity), 0)); entity.setYaw(rider.getYaw()); entity.setPitch(rider.getPitch()); entity.setVelocity(rider.getVelocity().add(rider.getRotationVector().multiply(0.2, 0.02, 0.2).multiply(rider.isSneaking() ? 2 : 1))); world.spawnEntity(entity);
entity.playSound(GlideSoundEvents.HANG_GLIDER_OPENS, 0.8f, entity.random.nextFloat() * 0.2f + 1.2f);
4
2023-12-22 11:00:52+00:00
4k
andrewlalis/javafx-scene-router
src/test/java/com/andrewlalis/javafx_scene_router/test/SceneRouterTest.java
[ { "identifier": "AnchorPaneRouterView", "path": "src/main/java/com/andrewlalis/javafx_scene_router/AnchorPaneRouterView.java", "snippet": "public class AnchorPaneRouterView implements RouterView {\n private final AnchorPane anchorPane = new AnchorPane();\n private final boolean expandContents;\n\n...
import com.andrewlalis.javafx_scene_router.AnchorPaneRouterView; import com.andrewlalis.javafx_scene_router.SceneRouter; import javafx.application.Platform; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import org.junit.jupiter.api.Test; import java.util.concurrent.CompletableFuture; import static org.junit.jupiter.api.Assertions.*;
3,153
package com.andrewlalis.javafx_scene_router.test; public class SceneRouterTest { @Test public void testNavigate() { var router = getSampleRouter(); // Make some assertions prior to navigation. assertTrue(router.getHistory().getItems().isEmpty()); assertFalse(router.navigateBack().join()); assertFalse(router.navigateForward().join()); assertNull(router.currentRouteProperty().get()); // Test some basic navigation. var contextA = "CONTEXT"; router.navigate("A", contextA).join(); assertEquals(1, router.getHistory().getItems().size()); assertEquals("A", router.currentRouteProperty().get()); assertEquals(contextA, router.getContext()); assertEquals(1, router.getBreadCrumbs().size()); assertTrue(router.getBreadCrumbs().getFirst().current()); router.navigate("B").join(); assertEquals(2, router.getHistory().getItems().size()); assertEquals("B", router.currentRouteProperty().get()); assertNull(router.getContext()); assertEquals(2, router.getBreadCrumbs().size()); assertTrue(router.getBreadCrumbs().getLast().current()); assertFalse(router.getBreadCrumbs().getFirst().current()); // Test that navigating back and forward works. assertTrue(router.navigateBack().join()); assertEquals("A", router.currentRouteProperty().get()); assertEquals(contextA, router.getContext()); assertTrue(router.navigateForward().join()); assertEquals("B", router.currentRouteProperty().get()); assertNull(router.getContext()); assertFalse(router.navigateForward().join()); // Test that navigateBackAndClear works. assertTrue(router.navigateBackAndClear().join()); assertEquals("A", router.currentRouteProperty().get()); assertEquals(1, router.getHistory().getItems().size()); }
package com.andrewlalis.javafx_scene_router.test; public class SceneRouterTest { @Test public void testNavigate() { var router = getSampleRouter(); // Make some assertions prior to navigation. assertTrue(router.getHistory().getItems().isEmpty()); assertFalse(router.navigateBack().join()); assertFalse(router.navigateForward().join()); assertNull(router.currentRouteProperty().get()); // Test some basic navigation. var contextA = "CONTEXT"; router.navigate("A", contextA).join(); assertEquals(1, router.getHistory().getItems().size()); assertEquals("A", router.currentRouteProperty().get()); assertEquals(contextA, router.getContext()); assertEquals(1, router.getBreadCrumbs().size()); assertTrue(router.getBreadCrumbs().getFirst().current()); router.navigate("B").join(); assertEquals(2, router.getHistory().getItems().size()); assertEquals("B", router.currentRouteProperty().get()); assertNull(router.getContext()); assertEquals(2, router.getBreadCrumbs().size()); assertTrue(router.getBreadCrumbs().getLast().current()); assertFalse(router.getBreadCrumbs().getFirst().current()); // Test that navigating back and forward works. assertTrue(router.navigateBack().join()); assertEquals("A", router.currentRouteProperty().get()); assertEquals(contextA, router.getContext()); assertTrue(router.navigateForward().join()); assertEquals("B", router.currentRouteProperty().get()); assertNull(router.getContext()); assertFalse(router.navigateForward().join()); // Test that navigateBackAndClear works. assertTrue(router.navigateBackAndClear().join()); assertEquals("A", router.currentRouteProperty().get()); assertEquals(1, router.getHistory().getItems().size()); }
private SceneRouter getSampleRouter() {
1
2023-12-22 14:26:31+00:00
4k
danielfeitopin/MUNICS-SAPP-P1
src/main/java/es/storeapp/web/exceptions/ErrorHandlingUtils.java
[ { "identifier": "AuthenticationException", "path": "src/main/java/es/storeapp/business/exceptions/AuthenticationException.java", "snippet": "public class AuthenticationException extends Exception {\n \n private static final long serialVersionUID = 9047626511480506926L;\n\n public Authentication...
import es.storeapp.business.exceptions.AuthenticationException; import es.storeapp.business.exceptions.DuplicatedResourceException; import es.storeapp.business.exceptions.InstanceNotFoundException; import es.storeapp.business.exceptions.InvalidStateException; import es.storeapp.common.Constants; import java.util.Locale; import es.storeapp.common.EscapingLoggerWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; import org.springframework.ui.Model; import org.springframework.validation.BindingResult;
2,936
package es.storeapp.web.exceptions; @Component public class ErrorHandlingUtils {
package es.storeapp.web.exceptions; @Component public class ErrorHandlingUtils {
private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(ErrorHandlingUtils.class);
5
2023-12-24 19:24:49+00:00
4k
Brath1024/SensiCheck
src/main/java/cn/brath/sensicheck/strategy/SensiHolder.java
[ { "identifier": "SenKey", "path": "src/main/java/cn/brath/sensicheck/core/SenKey.java", "snippet": "public class SenKey implements Serializable {\n private static final long serialVersionUID = -8879895979621579720L;\n /** The beginning index, inclusive. */\n private final int begin;\n /** Th...
import cn.brath.sensicheck.core.SenKey; import cn.brath.sensicheck.core.SenKeys; import cn.brath.sensicheck.core.SenTrie; import cn.brath.sensicheck.utils.StringUtil; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors;
2,965
package cn.brath.sensicheck.strategy; /** * 敏感词处理 * * @author Brath * @since 2023-07-28 14:17:54 * <p> * 使用AC自动机实现敏感词处理 * </p> */ public class SensiHolder { private static final Logger logger = LoggerFactory.getLogger(SensiHolder.class); //默认敏感词地址 private String filepath = "/senwords.txt"; //核心Trie结构
package cn.brath.sensicheck.strategy; /** * 敏感词处理 * * @author Brath * @since 2023-07-28 14:17:54 * <p> * 使用AC自动机实现敏感词处理 * </p> */ public class SensiHolder { private static final Logger logger = LoggerFactory.getLogger(SensiHolder.class); //默认敏感词地址 private String filepath = "/senwords.txt"; //核心Trie结构
private SenTrie senTrie;
2
2023-12-28 04:50:04+00:00
4k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/chessComponent/ChessComponent.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.controller.ClickController; import Chess.model.ChessColor; import Chess.model.ChessboardPoint; import Chess.utils.ImageUtils; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.InputStream;
3,485
package Chess.chessComponent; /** * 表示棋盘上非空棋子的格子,是所有非空棋子的父类 */ public abstract class ChessComponent extends SquareComponent { protected String name;// 棋子 public ChessComponent(ChessboardPoint chessboardPoint, Point location, ChessColor chessColor, ClickController clickController, int size, int blood, int category) { super(chessboardPoint, location, chessColor, clickController, size, blood, category); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (Main.theme.equals("像素")) { if (isReversal && isSelected()) { InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("chess-pixel-sel")); try {
package Chess.chessComponent; /** * 表示棋盘上非空棋子的格子,是所有非空棋子的父类 */ public abstract class ChessComponent extends SquareComponent { protected String name;// 棋子 public ChessComponent(ChessboardPoint chessboardPoint, Point location, ChessColor chessColor, ClickController clickController, int size, int blood, int category) { super(chessboardPoint, location, chessColor, clickController, size, blood, category); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (Main.theme.equals("像素")) { if (isReversal && isSelected()) { InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("chess-pixel-sel")); try {
g.drawImage(ImageUtils.changeToOriginalSize(new ImageIcon(stream.readAllBytes()),
4
2023-12-31 05:50:13+00:00
4k
Ertinox45/ImmersiveAddon
src/main/java/fr/dynamx/addons/immersive/client/controllers/RadioController.java
[ { "identifier": "ConfigReader", "path": "src/main/java/fr/dynamx/addons/immersive/common/helpers/ConfigReader.java", "snippet": "public class ConfigReader {\n public static ArrayList<RadioFrequency> frequencies;\n\n public static void readFromFile() throws IOException {\n File json = new Fi...
import fr.aym.acsguis.component.GuiComponent; import fr.dynamx.addons.immersive.common.helpers.ConfigReader; import fr.dynamx.addons.immersive.common.modules.RadioModule; import fr.dynamx.api.entities.modules.IVehicleController; import fr.dynamx.common.entities.BaseVehicleEntity; import fr.dynamx.utils.DynamXConfig; import net.minecraft.client.settings.KeyBinding; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Keyboard; import java.util.Collections; import java.util.List;
1,633
package fr.dynamx.addons.immersive.client.controllers; public class RadioController implements IVehicleController { @SideOnly(Side.CLIENT) public static final KeyBinding play = new KeyBinding("Play (radio)", Keyboard.KEY_RMENU, "DynamX radio"); @SideOnly(Side.CLIENT) public static final KeyBinding right = new KeyBinding("Change -> (radio)", Keyboard.KEY_RIGHT, "DynamX radio"); @SideOnly(Side.CLIENT) public static final KeyBinding left = new KeyBinding("Change <- (radio)", Keyboard.KEY_LEFT, "DynamX radio"); private final BaseVehicleEntity<?> entity;
package fr.dynamx.addons.immersive.client.controllers; public class RadioController implements IVehicleController { @SideOnly(Side.CLIENT) public static final KeyBinding play = new KeyBinding("Play (radio)", Keyboard.KEY_RMENU, "DynamX radio"); @SideOnly(Side.CLIENT) public static final KeyBinding right = new KeyBinding("Change -> (radio)", Keyboard.KEY_RIGHT, "DynamX radio"); @SideOnly(Side.CLIENT) public static final KeyBinding left = new KeyBinding("Change <- (radio)", Keyboard.KEY_LEFT, "DynamX radio"); private final BaseVehicleEntity<?> entity;
private final RadioModule module;
1
2023-12-30 08:33:54+00:00
4k
HighlanderRobotics/Crescendo
src/main/java/frc/robot/Robot.java
[ { "identifier": "GyroIO", "path": "src/main/java/frc/robot/subsystems/swerve/GyroIO.java", "snippet": "public interface GyroIO {\n @AutoLog\n public static class GyroIOInputs {\n public boolean connected = false;\n public Rotation2d yawPosition = new Rotation2d();\n public Rotation2d[] odomet...
import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.wpilibj.PowerDistribution; import edu.wpi.first.wpilibj.PowerDistribution.ModuleType; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.CommandScheduler; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.button.CommandXboxController; import frc.robot.subsystems.swerve.GyroIO; import frc.robot.subsystems.swerve.GyroIOPigeon2; import frc.robot.subsystems.swerve.SwerveSubsystem; import org.littletonrobotics.junction.LogFileUtil; import org.littletonrobotics.junction.LoggedRobot; import org.littletonrobotics.junction.Logger; import org.littletonrobotics.junction.networktables.NT4Publisher; import org.littletonrobotics.junction.wpilog.WPILOGReader; import org.littletonrobotics.junction.wpilog.WPILOGWriter;
3,142
// 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; public class Robot extends LoggedRobot { public static enum RobotMode { SIM, REPLAY, REAL } public static final RobotMode mode = Robot.isReal() ? RobotMode.REAL : RobotMode.SIM; private Command autonomousCommand; private final CommandXboxController controller = new CommandXboxController(0);
// 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; public class Robot extends LoggedRobot { public static enum RobotMode { SIM, REPLAY, REAL } public static final RobotMode mode = Robot.isReal() ? RobotMode.REAL : RobotMode.SIM; private Command autonomousCommand; private final CommandXboxController controller = new CommandXboxController(0);
private final SwerveSubsystem swerve =
2
2023-12-26 21:26:46+00:00
4k
Patbox/serveruifix
src/main/java/eu/pb4/serveruifix/mixin/ServerPlayerEntityMixin.java
[ { "identifier": "ModInit", "path": "src/main/java/eu/pb4/serveruifix/ModInit.java", "snippet": "public class ModInit implements ModInitializer {\n\tpublic static final String ID = \"serveruifix\";\n\tpublic static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata()....
import com.llamalad7.mixinextras.sugar.Local; import eu.pb4.serveruifix.ModInit; import eu.pb4.serveruifix.ui.StonecutterGui; import net.minecraft.item.Items; import net.minecraft.screen.NamedScreenHandlerFactory; import net.minecraft.screen.ScreenHandler; import net.minecraft.screen.StonecutterScreenHandler; import net.minecraft.server.network.ServerPlayerEntity; 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.CallbackInfoReturnable; import java.util.OptionalInt;
1,899
package eu.pb4.serveruifix.mixin; @Mixin(ServerPlayerEntity.class) public class ServerPlayerEntityMixin { @Inject(method = "openHandledScreen", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayNetworkHandler;sendPacket(Lnet/minecraft/network/packet/Packet;)V", shift = At.Shift.BEFORE), cancellable = true) private void replaceScreenHandled(NamedScreenHandlerFactory factory, CallbackInfoReturnable<OptionalInt> cir, @Local ScreenHandler handler) { var player = (ServerPlayerEntity) (Object) this;
package eu.pb4.serveruifix.mixin; @Mixin(ServerPlayerEntity.class) public class ServerPlayerEntityMixin { @Inject(method = "openHandledScreen", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayNetworkHandler;sendPacket(Lnet/minecraft/network/packet/Packet;)V", shift = At.Shift.BEFORE), cancellable = true) private void replaceScreenHandled(NamedScreenHandlerFactory factory, CallbackInfoReturnable<OptionalInt> cir, @Local ScreenHandler handler) { var player = (ServerPlayerEntity) (Object) this;
if (handler instanceof StonecutterScreenHandler screenHandler && !(ModInit.DEV_MODE && player.getMainHandStack().isOf(Items.DEBUG_STICK)) ) {
0
2023-12-28 23:01:30+00:00
4k
psobiech/opengr8on
tftp/src/main/java/pl/psobiech/opengr8on/tftp/transfer/client/TFTPClientReceive.java
[ { "identifier": "TFTP", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/TFTP.java", "snippet": "public class TFTP implements Closeable {\n private static final Logger LOGGER = LoggerFactory.getLogger(TFTP.class);\n\n public static final int DEFAULT_PORT = 69;\n\n static final int MIN_PAC...
import java.io.IOException; import java.net.InetAddress; import java.nio.file.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.psobiech.opengr8on.tftp.TFTP; import pl.psobiech.opengr8on.tftp.TFTPTransferMode; import pl.psobiech.opengr8on.tftp.exceptions.TFTPPacketException; import pl.psobiech.opengr8on.tftp.packets.TFTPReadRequestPacket; import pl.psobiech.opengr8on.tftp.transfer.TFTPReceivingTransfer;
2,972
/* * 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.tftp.transfer.client; public class TFTPClientReceive extends TFTPReceivingTransfer { private static final Logger LOGGER = LoggerFactory.getLogger(TFTPClientReceive.class);
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.tftp.transfer.client; public class TFTPClientReceive extends TFTPReceivingTransfer { private static final Logger LOGGER = LoggerFactory.getLogger(TFTPClientReceive.class);
private final TFTPReadRequestPacket tftpPacket;
3
2023-12-23 09:56:14+00:00
4k
Pigmice2733/frc-2024
src/main/java/frc/robot/subsystems/Arm.java
[ { "identifier": "Constants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class Constants {\n public static final ShuffleboardTab DRIVER_TAB = Shuffleboard.getTab(\"Driver\");\n public static final ShuffleboardTab SWERVE_TAB = Shuffleboard.getTab(\"Drivetrain\");\n ...
import com.pigmice.frc.lib.pid_subsystem.PIDSubsystemBase; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMaxLowLevel.MotorType; import edu.wpi.first.math.trajectory.TrapezoidProfile.Constraints; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Commands; import frc.robot.Constants; import frc.robot.Constants.ArmConfig; import frc.robot.Constants.CANConfig; import frc.robot.Constants.ArmConfig.ArmState;
3,088
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; public class Arm extends PIDSubsystemBase { public Arm() {
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; public class Arm extends PIDSubsystemBase { public Arm() {
super(new CANSparkMax(CANConfig.ARM, MotorType.kBrushless), ArmConfig.P, ArmConfig.i, ArmConfig.D,
1
2023-12-30 06:06:45+00:00
4k
373675032/kaka-shop
src/main/java/world/xuewei/service/impl/UserServiceImpl.java
[ { "identifier": "CommodityComment", "path": "src/main/java/world/xuewei/entity/CommodityComment.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class CommodityComment implements Serializable {\n\n private static final long serialVersionUID = -92193160791514971L;\n\...
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import world.xuewei.entity.CommodityComment; import world.xuewei.entity.Order; import world.xuewei.entity.User; import world.xuewei.mapper.UserMapper; import world.xuewei.service.BaseService; import world.xuewei.service.UserService; import javax.annotation.Resource; import java.util.Date; import java.util.List;
2,414
package world.xuewei.service.impl; /** * @author XUEW * @ClassName UserServiceImpl * 用户表(User)表业务接口实现类 * @date 2021-03-13 16:14:04 * @Version 1.0 **/ @Service("userService") public class UserServiceImpl extends BaseService implements UserService { @Resource private UserMapper userMapper; @Value("${default-avatar}") private String defaultAvatar; @Override public boolean insert(User user) { return userMapper.insert(user) == 1; } @Override public boolean insert(String name, String password, String email) { User user = User.builder() .name(name).password(password).email(email).role(0) .img(defaultAvatar) .registerTime(new Date()) .info("-") .build(); return insert(user); } @Override public boolean deleteById(Integer id) { return userMapper.deleteById(id) == 1; } @Override public User getById(Integer id) { return userMapper.getById(id); } @Override public User getByEmail(String email) { return userMapper.getByEmail(email); } @Override public List<User> listUsers() { List<User> users = userMapper.listUsers(); // 处理数据 users.forEach(user -> { // 设置下单数量 Order param = Order.builder().userId(user.getId()).build(); user.setOrderCount(orderMapper.countOrders(param)); // 设置评论数量
package world.xuewei.service.impl; /** * @author XUEW * @ClassName UserServiceImpl * 用户表(User)表业务接口实现类 * @date 2021-03-13 16:14:04 * @Version 1.0 **/ @Service("userService") public class UserServiceImpl extends BaseService implements UserService { @Resource private UserMapper userMapper; @Value("${default-avatar}") private String defaultAvatar; @Override public boolean insert(User user) { return userMapper.insert(user) == 1; } @Override public boolean insert(String name, String password, String email) { User user = User.builder() .name(name).password(password).email(email).role(0) .img(defaultAvatar) .registerTime(new Date()) .info("-") .build(); return insert(user); } @Override public boolean deleteById(Integer id) { return userMapper.deleteById(id) == 1; } @Override public User getById(Integer id) { return userMapper.getById(id); } @Override public User getByEmail(String email) { return userMapper.getByEmail(email); } @Override public List<User> listUsers() { List<User> users = userMapper.listUsers(); // 处理数据 users.forEach(user -> { // 设置下单数量 Order param = Order.builder().userId(user.getId()).build(); user.setOrderCount(orderMapper.countOrders(param)); // 设置评论数量
CommodityComment comment = CommodityComment.builder().userId(user.getId()).build();
0
2023-12-27 15:17:13+00:00
4k
tommyskeff/JObserve
src/main/java/dev/tommyjs/jobserve/attribute/impl/AttributeRegistryImpl.java
[ { "identifier": "AttributeKey", "path": "src/main/java/dev/tommyjs/jobserve/attribute/AttributeKey.java", "snippet": "public class AttributeKey<T> {\n\n private static final Object LOCK = new Object();\n private static final Random RANDOM = new SecureRandom();\n\n private final int id;\n pri...
import dev.tommyjs.jobserve.attribute.AttributeKey; import dev.tommyjs.jobserve.attribute.AttributeRegistry; import dev.tommyjs.jobserve.observer.Observable; import dev.tommyjs.jobserve.observer.ObserverEmitter; import dev.tommyjs.jobserve.observer.impl.ObserverEmitterImpl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Function; import java.util.function.Supplier;
1,735
package dev.tommyjs.jobserve.attribute.impl; public class AttributeRegistryImpl implements AttributeRegistry, Observable { private final ObserverEmitter emitter; private final ReadWriteLock mutex; private final Map<AttributeKey<?>, Object> data; public AttributeRegistryImpl() {
package dev.tommyjs.jobserve.attribute.impl; public class AttributeRegistryImpl implements AttributeRegistry, Observable { private final ObserverEmitter emitter; private final ReadWriteLock mutex; private final Map<AttributeKey<?>, Object> data; public AttributeRegistryImpl() {
this.emitter = new ObserverEmitterImpl();
4
2023-12-26 17:02:45+00:00
4k
fanxiaoning/framifykit
framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/factory/LogisticsExecutorFactory.java
[ { "identifier": "KD100Executor", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/KD100Executor.java", "snippet": "@Slf4j\npublic class KD100Executor extends AbstractLogisticsExecutor<KD100Req, KD100Res>\n implements ILogisticsExecut...
import com.framifykit.starter.logistics.executor.KD100Executor; import com.framifykit.starter.logistics.executor.constant.LogisticsTypeEnum; import com.framifykit.starter.logistics.executor.ILogisticsExecutor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
2,033
package com.framifykit.starter.logistics.executor.factory; /** * <p> * 物流组件执行器工厂 * </p> * * @author fxn * @since 1.0.0 **/ public class LogisticsExecutorFactory { private static final Map<String, ILogisticsExecutor> LOGISTICS_EXECUTOR_CONTEXT = new ConcurrentHashMap<>(); static {
package com.framifykit.starter.logistics.executor.factory; /** * <p> * 物流组件执行器工厂 * </p> * * @author fxn * @since 1.0.0 **/ public class LogisticsExecutorFactory { private static final Map<String, ILogisticsExecutor> LOGISTICS_EXECUTOR_CONTEXT = new ConcurrentHashMap<>(); static {
register(LogisticsTypeEnum.KD_100, new KD100Executor());
1
2023-12-31 03:48:33+00:00
4k
yangpluseven/Simulate-Something
simulation/src/simulator/GridMap.java
[ { "identifier": "Constants", "path": "simulation/src/constants/Constants.java", "snippet": "public class Constants {\n\n\tpublic static final Size INIT_GRID_SIZE = new Size(10, 10);\n\tpublic static final Size NUM_OF_COL_ROW = new Size(50, 30);\n\tpublic static final int BACKGROUND_Z_ORDER = 0;\n\tpubli...
import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.HashSet; import java.util.Iterator; import constants.Constants; import entities.Location; import entities.Pair; import entities.SimuObject; import entities.Size;
1,634
package simulator; /** * GridMap takes up all the SimuObjects in the simulation. * * @author pluseven */ public class GridMap implements Map<Location, simulator.GridMap.Grid> { private Grid[][] grids; private Size numCR; private int numOfObjs; /** * Default constructor. */ public GridMap() { numCR = Constants.NUM_OF_COL_ROW; int numCol = numCR.getWidth(); int numRow = numCR.getHeight(); grids = new Grid[numCol][numRow]; numOfObjs = 0; } /** * Create a GridMap with the given numbers of columns and rows. * * @param numCR */ public GridMap(Size numCR) { this.numCR = numCR; int numCol = numCR.getWidth(); int numRow = numCR.getHeight(); grids = new Grid[numCol][numRow]; numOfObjs = 0; } /** * Add the SimuObject at the given location. * * @param simuObj * @param location */
package simulator; /** * GridMap takes up all the SimuObjects in the simulation. * * @author pluseven */ public class GridMap implements Map<Location, simulator.GridMap.Grid> { private Grid[][] grids; private Size numCR; private int numOfObjs; /** * Default constructor. */ public GridMap() { numCR = Constants.NUM_OF_COL_ROW; int numCol = numCR.getWidth(); int numRow = numCR.getHeight(); grids = new Grid[numCol][numRow]; numOfObjs = 0; } /** * Create a GridMap with the given numbers of columns and rows. * * @param numCR */ public GridMap(Size numCR) { this.numCR = numCR; int numCol = numCR.getWidth(); int numRow = numCR.getHeight(); grids = new Grid[numCol][numRow]; numOfObjs = 0; } /** * Add the SimuObject at the given location. * * @param simuObj * @param location */
public void addObjectAt(SimuObject simuObj, Location location) {
3
2023-12-23 13:51:12+00:00
4k
zxx1119/best-adrules
src/main/java/org/fordes/adg/rule/thread/AbstractRuleThread.java
[ { "identifier": "Util", "path": "src/main/java/org/fordes/adg/rule/Util.java", "snippet": "@Slf4j\npublic class Util {\n\n /**\n * 加锁将集合按行写入文件\n *\n * @param file 目标文件\n * @param content 内容集合\n */\n public static void write(File file, Collection<String> content) {\n i...
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.TimeInterval; import cn.hutool.core.exceptions.ExceptionUtil; import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.LineHandler; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.StrUtil; import com.google.common.hash.BloomFilter; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.fordes.adg.rule.Util; import org.fordes.adg.rule.enums.RuleType; import java.io.File; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference;
1,822
package org.fordes.adg.rule.thread; /** * 规则处理线程抽象 * * @author ChengFengsheng on 2022/7/7 */ @Slf4j @Data public abstract class AbstractRuleThread implements Runnable { private final String ruleUrl;
package org.fordes.adg.rule.thread; /** * 规则处理线程抽象 * * @author ChengFengsheng on 2022/7/7 */ @Slf4j @Data public abstract class AbstractRuleThread implements Runnable { private final String ruleUrl;
private final Map<RuleType, Set<File>> typeFileMap;
1
2023-12-30 04:47:07+00:00
4k
bmarwell/sipper
impl/src/main/java/io/github/bmarwell/sipper/impl/internal/SipConnectionFactory.java
[ { "identifier": "RegisteredSipConnection", "path": "api/src/main/java/io/github/bmarwell/sipper/api/RegisteredSipConnection.java", "snippet": "public interface RegisteredSipConnection extends SipConnection {}" }, { "identifier": "SipConfiguration", "path": "api/src/main/java/io/github/bmarwe...
import org.slf4j.LoggerFactory; import io.github.bmarwell.sipper.api.RegisteredSipConnection; import io.github.bmarwell.sipper.api.SipConfiguration; import io.github.bmarwell.sipper.api.SipConnection; import io.github.bmarwell.sipper.impl.SocketInConnectionReader; import io.github.bmarwell.sipper.impl.ip.IpUtil; import io.github.bmarwell.sipper.impl.proto.*; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.Base64; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.random.RandomGeneratorFactory; import org.slf4j.Logger;
2,517
/* * Copyright (C) 2023-2024 The SIPper project team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.bmarwell.sipper.impl.internal; public class SipConnectionFactory { private static final Logger LOG = LoggerFactory.getLogger(SipConnectionFactory.class); private final SipConfiguration sipConfiguration; private final SipMessageFactory messageFactory; public SipConnectionFactory(SipConfiguration sipConfiguration) { this.sipConfiguration = sipConfiguration; this.messageFactory = new SipMessageFactory(this.sipConfiguration); }
/* * Copyright (C) 2023-2024 The SIPper project team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.bmarwell.sipper.impl.internal; public class SipConnectionFactory { private static final Logger LOG = LoggerFactory.getLogger(SipConnectionFactory.class); private final SipConfiguration sipConfiguration; private final SipMessageFactory messageFactory; public SipConnectionFactory(SipConfiguration sipConfiguration) { this.sipConfiguration = sipConfiguration; this.messageFactory = new SipMessageFactory(this.sipConfiguration); }
public SipConnection build() throws IOException {
2
2023-12-28 13:13:07+00:00
4k
Deenu143/GradleParser
app/src/main/java/org/deenu/gradle/script/visitors/GradleScriptVisitor.java
[ { "identifier": "Dependency", "path": "app/src/main/java/org/deenu/gradle/models/Dependency.java", "snippet": "public class Dependency {\n\n private String configuration;\n private String group;\n private String name;\n private String version;\n\n public Dependency(String group, String name, String...
import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.codehaus.groovy.ast.CodeVisitorSupport; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.deenu.gradle.models.Dependency; import org.deenu.gradle.models.FlatDir; import org.deenu.gradle.models.Include; import org.deenu.gradle.models.Plugin; import org.deenu.gradle.models.Repository;
1,640
package org.deenu.gradle.script.visitors; public class GradleScriptVisitor extends CodeVisitorSupport { private Stack<Boolean> blockStatementStack = new Stack<>(); private int pluginsLastLineNumber = -1; private String pluginsConfigurationName; private boolean inPlugins = false; private List<Plugin> plugins = new ArrayList<>(); private int repositoriesLastLineNumber = -1; private String repositoriesConfigurationName; private boolean inRepositories = false; private List<Repository> repositories = new ArrayList<>(); private int buildscriptRepositoriesLastLineNumber = -1; private String buildscriptRepositoriesConfigurationName; private boolean inBuildScriptRepositories = false; private List<Repository> buildscriptRepositories = new ArrayList<>(); private int buildscriptLastLineNumber = -1; private String buildscriptConfigurationName; private boolean inBuildScript = false; private int allprojectsLastLineNumber = -1; private String allprojectsConfigurationName; private boolean inAllProjects = false; private int allprojectsRepositoriesLastLineNumber = -1; private String allprojectsRepositoriesConfigurationName; private boolean inAllProjectsRepositories = false; private List<Repository> allprojectsRepositories = new ArrayList<>(); private String rootProjectName; private int includeLastLineNumber = -1; private String includeConfigurationName; private boolean inInclude = false; private List<Include> includes = new ArrayList<>(); private int flatDirLastLineNumber = -1; private String flatDirConfigurationName; private boolean inFlatDir = false; private int allprojectsrepositoriesflatDirLastLineNumber = -1; private String allprojectsrepositoriesflatDirConfigurationName; private boolean inAllProjectsRepositoriesFlatDir = false; private int flatDirdirsLastLineNumber = -1; private String flatDirdirsConfigurationName; private boolean inFlatDirDirs = false; private int allprojectsrepositoriesflatDirdirsLastLineNumber = -1; private String allprojectsrepositoriesflatDirdirsConfigurationName; private boolean inAllProjectsRepositoriesFlatDirDirs = false;
package org.deenu.gradle.script.visitors; public class GradleScriptVisitor extends CodeVisitorSupport { private Stack<Boolean> blockStatementStack = new Stack<>(); private int pluginsLastLineNumber = -1; private String pluginsConfigurationName; private boolean inPlugins = false; private List<Plugin> plugins = new ArrayList<>(); private int repositoriesLastLineNumber = -1; private String repositoriesConfigurationName; private boolean inRepositories = false; private List<Repository> repositories = new ArrayList<>(); private int buildscriptRepositoriesLastLineNumber = -1; private String buildscriptRepositoriesConfigurationName; private boolean inBuildScriptRepositories = false; private List<Repository> buildscriptRepositories = new ArrayList<>(); private int buildscriptLastLineNumber = -1; private String buildscriptConfigurationName; private boolean inBuildScript = false; private int allprojectsLastLineNumber = -1; private String allprojectsConfigurationName; private boolean inAllProjects = false; private int allprojectsRepositoriesLastLineNumber = -1; private String allprojectsRepositoriesConfigurationName; private boolean inAllProjectsRepositories = false; private List<Repository> allprojectsRepositories = new ArrayList<>(); private String rootProjectName; private int includeLastLineNumber = -1; private String includeConfigurationName; private boolean inInclude = false; private List<Include> includes = new ArrayList<>(); private int flatDirLastLineNumber = -1; private String flatDirConfigurationName; private boolean inFlatDir = false; private int allprojectsrepositoriesflatDirLastLineNumber = -1; private String allprojectsrepositoriesflatDirConfigurationName; private boolean inAllProjectsRepositoriesFlatDir = false; private int flatDirdirsLastLineNumber = -1; private String flatDirdirsConfigurationName; private boolean inFlatDirDirs = false; private int allprojectsrepositoriesflatDirdirsLastLineNumber = -1; private String allprojectsrepositoriesflatDirdirsConfigurationName; private boolean inAllProjectsRepositoriesFlatDirDirs = false;
private List<FlatDir> allprojectsrepositoriesflatDirDirs = new ArrayList<>();
1
2023-12-27 10:10:31+00:00
4k
NickReset/JavaNPM
src/main/java/social/nickrest/npm/NPM.java
[ { "identifier": "InstalledNPMPackage", "path": "src/main/java/social/nickrest/npm/module/InstalledNPMPackage.java", "snippet": "@Getter\npublic class InstalledNPMPackage {\n\n private final NPM parent;\n private final File dir;\n\n private JSONObject packageJson;\n private NPMPackageData dat...
import lombok.Getter; import lombok.Setter; import social.nickrest.npm.module.InstalledNPMPackage; import social.nickrest.npm.module.NPMPackage; import java.io.File;
1,737
package social.nickrest.npm; @Getter @Setter public class NPM { public static final String BASE_URL = "https://registry.npmjs.org"; private final File nodeModulesDir; private NPMLogger logger; public NPM(File nodeModulesDir) { this.nodeModulesDir = nodeModulesDir; this.logger = new DefualtNPMLogger(); } public NPMPackage getPackage(String name) { return new NPMPackage(this, name); }
package social.nickrest.npm; @Getter @Setter public class NPM { public static final String BASE_URL = "https://registry.npmjs.org"; private final File nodeModulesDir; private NPMLogger logger; public NPM(File nodeModulesDir) { this.nodeModulesDir = nodeModulesDir; this.logger = new DefualtNPMLogger(); } public NPMPackage getPackage(String name) { return new NPMPackage(this, name); }
public InstalledNPMPackage getInstalledPackage(String name) {
0
2023-12-22 20:46:10+00:00
4k
Prototik/TheConfigLib
common/src/main/java/dev/tcl/api/controller/CyclingListControllerBuilder.java
[ { "identifier": "Option", "path": "common/src/main/java/dev/tcl/api/Option.java", "snippet": "public interface Option<T> {\n /**\n * Name of the option\n */\n @NotNull Component name();\n\n @NotNull OptionDescription description();\n\n /**\n * Widget provider for a type of option...
import dev.tcl.api.Option; import dev.tcl.impl.controller.CyclingListControllerBuilderImpl;
1,735
package dev.tcl.api.controller; public interface CyclingListControllerBuilder<T> extends ValueFormattableController<T, CyclingListControllerBuilder<T>> { @SuppressWarnings("unchecked") CyclingListControllerBuilder<T> values(T... values); CyclingListControllerBuilder<T> values(Iterable<? extends T> values); static <T> CyclingListControllerBuilder<T> create(Option<T> option) {
package dev.tcl.api.controller; public interface CyclingListControllerBuilder<T> extends ValueFormattableController<T, CyclingListControllerBuilder<T>> { @SuppressWarnings("unchecked") CyclingListControllerBuilder<T> values(T... values); CyclingListControllerBuilder<T> values(Iterable<? extends T> values); static <T> CyclingListControllerBuilder<T> create(Option<T> option) {
return new CyclingListControllerBuilderImpl<>(option);
1
2023-12-25 14:48:27+00:00
4k
vadage/rs4j
src/main/java/space/provided/rs/option/Option.java
[ { "identifier": "ValueAccessError", "path": "src/main/java/space/provided/rs/error/ValueAccessError.java", "snippet": "public final class ValueAccessError extends Error {\n\n public ValueAccessError(String message) {\n super(message);\n }\n}" }, { "identifier": "ArgInvokable", "...
import space.provided.rs.error.ValueAccessError; import space.provided.rs.ops.ArgInvokable; import space.provided.rs.ops.ArgVoidInvokable; import space.provided.rs.ops.Invokable; import space.provided.rs.ops.PlainInvokable; import space.provided.rs.result.Result; import java.util.function.Predicate;
1,991
package space.provided.rs.option; public final class Option<Some> { private final Some some; private final OptionType type; private Option(Some some, OptionType type) { this.some = some; this.type = type; } public static <Some> Option<Some> some(Some some) { return new Option<>(some, OptionType.SOME); } public static <Some> Option<Some> none() { return new Option<>(null, OptionType.NONE); } public boolean isSome() { return type.equals(OptionType.SOME); } public boolean isNone() { return !isSome(); } public boolean isSomeAnd(ArgInvokable<Some, Boolean> invokable) { return switch (type) { case NONE -> false; case SOME -> invokable.invoke(some); }; } public Some unwrap() throws ValueAccessError { if (!isSome()) { throw new ValueAccessError("Called `unwrap` on %1$s Option.".formatted(type)); } return some; } public Some unwrapOr(Some fallback) { return switch (type) { case SOME -> some; case NONE -> fallback; }; } public <Mapped> Option<Mapped> map(ArgInvokable<Some, Mapped> invokable) { return switch (type) { case SOME -> Option.some(invokable.invoke(some)); case NONE -> Option.none(); }; } public <Mapped> Mapped mapOr(Mapped fallback, ArgInvokable<Some, Mapped> invokable) { return switch (type) { case SOME -> invokable.invoke(some); case NONE -> fallback; }; } public <Mapped> Mapped mapOrElse(PlainInvokable<Mapped> fallback, ArgInvokable<Some, Mapped> invokable) { return switch (type) { case SOME -> invokable.invoke(some); case NONE -> fallback.invoke(); }; } public <Err> Result<Some, Err> okOr(Err error) { return switch (type) { case SOME -> (Result<Some, Err>) Result.ok(some); case NONE -> Result.error(error); }; } public <Err> Result<Some, Err> okOrElse(PlainInvokable<Err> invokable) { return switch (type) { case SOME -> (Result<Some, Err>) Result.ok(some); case NONE -> Result.error(invokable.invoke()); }; } public Option<Some> andThen(ArgInvokable<Some, Option<Some>> invokable) { return switch (type) { case SOME -> invokable.invoke(some); case NONE -> Option.none(); }; }
package space.provided.rs.option; public final class Option<Some> { private final Some some; private final OptionType type; private Option(Some some, OptionType type) { this.some = some; this.type = type; } public static <Some> Option<Some> some(Some some) { return new Option<>(some, OptionType.SOME); } public static <Some> Option<Some> none() { return new Option<>(null, OptionType.NONE); } public boolean isSome() { return type.equals(OptionType.SOME); } public boolean isNone() { return !isSome(); } public boolean isSomeAnd(ArgInvokable<Some, Boolean> invokable) { return switch (type) { case NONE -> false; case SOME -> invokable.invoke(some); }; } public Some unwrap() throws ValueAccessError { if (!isSome()) { throw new ValueAccessError("Called `unwrap` on %1$s Option.".formatted(type)); } return some; } public Some unwrapOr(Some fallback) { return switch (type) { case SOME -> some; case NONE -> fallback; }; } public <Mapped> Option<Mapped> map(ArgInvokable<Some, Mapped> invokable) { return switch (type) { case SOME -> Option.some(invokable.invoke(some)); case NONE -> Option.none(); }; } public <Mapped> Mapped mapOr(Mapped fallback, ArgInvokable<Some, Mapped> invokable) { return switch (type) { case SOME -> invokable.invoke(some); case NONE -> fallback; }; } public <Mapped> Mapped mapOrElse(PlainInvokable<Mapped> fallback, ArgInvokable<Some, Mapped> invokable) { return switch (type) { case SOME -> invokable.invoke(some); case NONE -> fallback.invoke(); }; } public <Err> Result<Some, Err> okOr(Err error) { return switch (type) { case SOME -> (Result<Some, Err>) Result.ok(some); case NONE -> Result.error(error); }; } public <Err> Result<Some, Err> okOrElse(PlainInvokable<Err> invokable) { return switch (type) { case SOME -> (Result<Some, Err>) Result.ok(some); case NONE -> Result.error(invokable.invoke()); }; } public Option<Some> andThen(ArgInvokable<Some, Option<Some>> invokable) { return switch (type) { case SOME -> invokable.invoke(some); case NONE -> Option.none(); }; }
public Option<Some> andThenContinue(ArgVoidInvokable<Some> invokable) {
2
2023-12-27 15:33:17+00:00
4k
wicksonZhang/Spring-Cloud
08-spring-cloud-hystrix-payment-8000/src/main/java/cn/wickson/cloud/hystrix/payment/service/impl/PaymentServiceImpl.java
[ { "identifier": "ResultCodeEnum", "path": "01-spring-cloud-common/src/main/java/cn/wickson/cloud/common/enums/ResultCodeEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum ResultCodeEnum {\n\n /**\n * 成功状态码:1\n */\n SUCCESS(1, \"成功\"),\n /**\n * 失败状态码\n */\n FAI...
import cn.hutool.core.util.IdUtil; import cn.wickson.cloud.common.enums.ResultCodeEnum; import cn.wickson.cloud.common.exception.UserOperationException; import cn.wickson.cloud.common.utils.ResultUtil; import cn.wickson.cloud.hystrix.payment.service.IPaymentService; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit;
2,142
package cn.wickson.cloud.hystrix.payment.service.impl; /** * 支付服务-应用服务实现类 * * @author ZhangZiHeng * @date 2024-01-08 */ @Service public class PaymentServiceImpl implements IPaymentService { /** * 成功 * * @return String */ @Override public ResultUtil paymentBySuccess() { return ResultUtil.success("ThreadPool:" + Thread.currentThread().getName() + ", payment service success"); } /** * 连接超时 * * @return String */ @Override public ResultUtil paymentByTimeOut() { int timeNumber = 3; try { TimeUnit.SECONDS.sleep(timeNumber); } catch (Exception exception) { exception.printStackTrace(); } return ResultUtil.success("ThreadPool:" + Thread.currentThread().getName() + ", payment service timeout:" + timeNumber); } @Override public ResultUtil paymentCircuitBreaker(final Long id) { if (id < 0) {
package cn.wickson.cloud.hystrix.payment.service.impl; /** * 支付服务-应用服务实现类 * * @author ZhangZiHeng * @date 2024-01-08 */ @Service public class PaymentServiceImpl implements IPaymentService { /** * 成功 * * @return String */ @Override public ResultUtil paymentBySuccess() { return ResultUtil.success("ThreadPool:" + Thread.currentThread().getName() + ", payment service success"); } /** * 连接超时 * * @return String */ @Override public ResultUtil paymentByTimeOut() { int timeNumber = 3; try { TimeUnit.SECONDS.sleep(timeNumber); } catch (Exception exception) { exception.printStackTrace(); } return ResultUtil.success("ThreadPool:" + Thread.currentThread().getName() + ", payment service timeout:" + timeNumber); } @Override public ResultUtil paymentCircuitBreaker(final Long id) { if (id < 0) {
throw UserOperationException.getInstance(ResultCodeEnum.PARAM_IS_INVALID);
0
2023-12-27 09:42:02+00:00
4k
behnamnasehi/playsho
app/src/main/java/com/playsho/android/db/SessionStorage.java
[ { "identifier": "ApplicationLoader", "path": "app/src/main/java/com/playsho/android/base/ApplicationLoader.java", "snippet": "public class ApplicationLoader extends Application {\n private static final String TAG = \"ApplicationLoader\";\n @SuppressLint(\"StaticFieldLeak\")\n private static Con...
import android.content.Context; import android.content.SharedPreferences; import com.playsho.android.base.ApplicationLoader; import com.playsho.android.utils.Validator;
2,219
package com.playsho.android.db; /** * A class for managing session storage using SharedPreferences. */ public class SessionStorage { private final SharedPreferences pref; private final SharedPreferences.Editor editor; // Name of the shared preference file private final String SHARED_PREFERENCE_NAME = "main_sp"; /** * Constructs a SessionStorage instance and initializes SharedPreferences and its editor. */ public SessionStorage() { this.pref = ApplicationLoader.getAppContext().getSharedPreferences( SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE ); editor = pref.edit(); editor.apply(); } /** * Clears all entries in the SharedPreferences. */ public void clearAll(){ pref.edit().clear().apply(); } /** * Gets a String value from the SharedPreferences with the specified key. * * @param key The key for the String value. * @return The String value associated with the key, or {@code null} if not found. */ public String getString(String key) { return pref.getString(key, null); } /** * Gets a String value from the SharedPreferences with the specified key, providing a default value if not found. * * @param key The key for the String value. * @param defValue The default value to return if the key is not found. * @return The String value associated with the key, or the default value if not found. */ public String getString(String key , String defValue) { return pref.getString(key, defValue); } /** * Sets a String value in the SharedPreferences with the specified key. * * @param key The key for the String value. * @param value The String value to set. */ public void setString(String key, String value) { editor.putString(key, value); editor.apply(); editor.commit(); } /** * Gets an integer value from the SharedPreferences with the specified key. * * @param key The key for the integer value. * @return The integer value associated with the key, or 0 if not found. */ public int getInteger(String key) { return pref.getInt(key, 0); } /** * Gets an integer value from the SharedPreferences with the specified key, providing a default value if not found. * * @param key The key for the integer value. * @param defValue The default value to return if the key is not found. * @return The integer value associated with the key, or the default value if not found. */ public int getInteger(String key , int defValue) { return pref.getInt(key, defValue); } /** * Sets an integer value in the SharedPreferences with the specified key. * * @param key The key for the integer value. * @param value The integer value to set. */ public void setInteger(String key, int value) { editor.putInt(key, value); editor.apply(); editor.commit(); } /** * Deserializes a JSON string stored in SharedPreferences into an object of the specified class. * * @param key The key for the JSON string. * @param clazz The class type to deserialize the JSON into. * @param <T> The type of the class. * @return An object of the specified class, or a default object if the JSON is not found. */ public <T> T deserialize(String key, Class<T> clazz) { String json = this.getString(key);
package com.playsho.android.db; /** * A class for managing session storage using SharedPreferences. */ public class SessionStorage { private final SharedPreferences pref; private final SharedPreferences.Editor editor; // Name of the shared preference file private final String SHARED_PREFERENCE_NAME = "main_sp"; /** * Constructs a SessionStorage instance and initializes SharedPreferences and its editor. */ public SessionStorage() { this.pref = ApplicationLoader.getAppContext().getSharedPreferences( SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE ); editor = pref.edit(); editor.apply(); } /** * Clears all entries in the SharedPreferences. */ public void clearAll(){ pref.edit().clear().apply(); } /** * Gets a String value from the SharedPreferences with the specified key. * * @param key The key for the String value. * @return The String value associated with the key, or {@code null} if not found. */ public String getString(String key) { return pref.getString(key, null); } /** * Gets a String value from the SharedPreferences with the specified key, providing a default value if not found. * * @param key The key for the String value. * @param defValue The default value to return if the key is not found. * @return The String value associated with the key, or the default value if not found. */ public String getString(String key , String defValue) { return pref.getString(key, defValue); } /** * Sets a String value in the SharedPreferences with the specified key. * * @param key The key for the String value. * @param value The String value to set. */ public void setString(String key, String value) { editor.putString(key, value); editor.apply(); editor.commit(); } /** * Gets an integer value from the SharedPreferences with the specified key. * * @param key The key for the integer value. * @return The integer value associated with the key, or 0 if not found. */ public int getInteger(String key) { return pref.getInt(key, 0); } /** * Gets an integer value from the SharedPreferences with the specified key, providing a default value if not found. * * @param key The key for the integer value. * @param defValue The default value to return if the key is not found. * @return The integer value associated with the key, or the default value if not found. */ public int getInteger(String key , int defValue) { return pref.getInt(key, defValue); } /** * Sets an integer value in the SharedPreferences with the specified key. * * @param key The key for the integer value. * @param value The integer value to set. */ public void setInteger(String key, int value) { editor.putInt(key, value); editor.apply(); editor.commit(); } /** * Deserializes a JSON string stored in SharedPreferences into an object of the specified class. * * @param key The key for the JSON string. * @param clazz The class type to deserialize the JSON into. * @param <T> The type of the class. * @return An object of the specified class, or a default object if the JSON is not found. */ public <T> T deserialize(String key, Class<T> clazz) { String json = this.getString(key);
if (Validator.isNullOrEmpty(json)) {
1
2023-12-26 08:14:29+00:00
4k
lunasaw/voglander
voglander-web/src/main/java/io/github/lunasaw/voglander/web/interceptor/impl/SameUrlDataInterceptor.java
[ { "identifier": "CacheConstants", "path": "voglander-common/src/main/java/io/github/lunasaw/voglander/common/constant/CacheConstants.java", "snippet": "public class CacheConstants\n{\n /**\n * 登录用户 redis key\n */\n public static final String LOGIN_TOKEN_KEY = \"login_tokens:\";\n\n /**\...
import com.alibaba.fastjson2.JSON; import io.github.lunasaw.voglander.common.anno.RepeatSubmit; import io.github.lunasaw.voglander.common.constant.CacheConstants; import io.github.lunasaw.voglander.repository.redis.RedisCache; import io.github.lunasaw.voglander.web.filter.RepeatedlyRequestWrapper; import io.github.lunasaw.voglander.web.tools.http.HttpHelper; import io.github.lunasaw.voglander.web.interceptor.RepeatSubmitInterceptor; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit;
3,446
package io.github.lunasaw.voglander.web.interceptor.impl; /** * 判断请求url和数据是否和上一次相同, * 如果和上次相同,则是重复提交表单。 有效时间为10秒内。 * * @author luna */ @Component public class SameUrlDataInterceptor extends RepeatSubmitInterceptor { public final String REPEAT_PARAMS = "repeatParams"; public final String REPEAT_TIME = "repeatTime"; // 令牌自定义标识 @Value("${token.header}") private String header; @Autowired
package io.github.lunasaw.voglander.web.interceptor.impl; /** * 判断请求url和数据是否和上一次相同, * 如果和上次相同,则是重复提交表单。 有效时间为10秒内。 * * @author luna */ @Component public class SameUrlDataInterceptor extends RepeatSubmitInterceptor { public final String REPEAT_PARAMS = "repeatParams"; public final String REPEAT_TIME = "repeatTime"; // 令牌自定义标识 @Value("${token.header}") private String header; @Autowired
private RedisCache redisCache;
1
2023-12-27 07:28:18+00:00
4k
GrailStack/grail-codegen
src/main/java/com/itgrail/grail/codegen/components/db/DbComponentPlugin.java
[ { "identifier": "DbException", "path": "src/main/java/com/itgrail/grail/codegen/components/db/exceptions/DbException.java", "snippet": "public class DbException extends RuntimeException {\n\n public DbException() {\n super(\"DB操作失败\");\n }\n\n public DbException(String msg) {\n su...
import com.alibaba.fastjson.JSONObject; import com.itgrail.grail.codegen.components.db.exceptions.DbException; import com.itgrail.grail.codegen.core.plugin.ComponentPlugin; import com.itgrail.grail.codegen.utils.FileUtil; import com.itgrail.grail.codegen.utils.ResourceUtil; import com.itgrail.grail.codegen.components.db.model.Table; import com.itgrail.grail.codegen.template.datamodel.CodeGenDataModel; import com.itgrail.grail.codegen.template.engine.FreemarkerTemplateEngine; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.List;
2,444
package com.itgrail.grail.codegen.components.db; /** * @author xujin * created at 2019/6/4 21:32 **/ @Component @Slf4j public class DbComponentPlugin implements ComponentPlugin { private static final String doFile = "${db.table.doName}.java.ftl"; private static final String daoFile = "${db.table.daoName}.java.ftl"; @Override
package com.itgrail.grail.codegen.components.db; /** * @author xujin * created at 2019/6/4 21:32 **/ @Component @Slf4j public class DbComponentPlugin implements ComponentPlugin { private static final String doFile = "${db.table.doName}.java.ftl"; private static final String daoFile = "${db.table.daoName}.java.ftl"; @Override
public boolean canHandleDir(Resource dir, CodeGenDataModel model) {
5
2023-12-30 15:32:55+00:00
4k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/data/statistics/DefaultMultiValueCategoryDatasetTest.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.assertTrue; import static org.junit.Assert.assertFalse; import java.util.ArrayList; import java.util.List; import org.jfree.chart.TestUtilities; import org.jfree.data.UnknownKeyException; import org.junit.Test;
1,694
/* =========================================================== * 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.] * * ----------------------------------------- * DefaultMultiValueCategoryDatasetTest.java * ----------------------------------------- * (C) Copyright 2007-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 28-Sep-2007 : Version 1 (DG); * */ package org.jfree.data.statistics; /** * Tests for the {@link DefaultMultiValueCategoryDataset} class. */ public class DefaultMultiValueCategoryDatasetTest { /** * Some checks for the getValue() method. */ @Test public void testGetValue() { DefaultMultiValueCategoryDataset d = new DefaultMultiValueCategoryDataset(); List values = new ArrayList(); values.add(new Integer(1)); values.add(new Integer(2)); d.add(values, "R1", "C1"); assertEquals(new Double(1.5), d.getValue("R1", "C1")); boolean pass = false; try { d.getValue("XX", "C1"); } catch (UnknownKeyException e) { pass = true; } assertTrue(pass); pass = false; try { d.getValue("R1", "XX"); } catch (UnknownKeyException e) { pass = true; } assertTrue(pass); } /** * A simple check for the getValue(int, int) method. */ @Test public void testGetValue2() { DefaultMultiValueCategoryDataset d = new DefaultMultiValueCategoryDataset(); boolean pass = false; try { /* Number n =*/ d.getValue(0, 0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some tests for the getRowCount() method. */ @Test public void testGetRowCount() { DefaultMultiValueCategoryDataset d = new DefaultMultiValueCategoryDataset(); assertTrue(d.getRowCount() == 0); List values = new ArrayList(); d.add(values, "R1", "C1"); assertTrue(d.getRowCount() == 1); d.add(values, "R2", "C1"); assertTrue(d.getRowCount() == 2); d.add(values, "R2", "C1"); assertTrue(d.getRowCount() == 2); } /** * Some tests for the getColumnCount() method. */ @Test public void testGetColumnCount() { DefaultMultiValueCategoryDataset d = new DefaultMultiValueCategoryDataset(); assertTrue(d.getColumnCount() == 0); List values = new ArrayList(); d.add(values, "R1", "C1"); assertTrue(d.getColumnCount() == 1); d.add(values, "R1", "C2"); assertTrue(d.getColumnCount() == 2); d.add(values, "R1", "C2"); assertTrue(d.getColumnCount() == 2); } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultMultiValueCategoryDataset d1 = new DefaultMultiValueCategoryDataset(); DefaultMultiValueCategoryDataset d2 = new DefaultMultiValueCategoryDataset(); assertTrue(d1.equals(d2)); assertTrue(d2.equals(d1)); List values = new ArrayList(); d1.add(values, "R1", "C1"); assertFalse(d1.equals(d2)); d2.add(values, "R1", "C1"); assertTrue(d1.equals(d2)); values.add(new Integer(99)); d1.add(values, "R1", "C1"); assertFalse(d1.equals(d2)); d2.add(values, "R1", "C1"); assertTrue(d1.equals(d2)); values.add(new Integer(99)); d1.add(values, "R1", "C2"); assertFalse(d1.equals(d2)); d2.add(values, "R1", "C2"); assertTrue(d1.equals(d2)); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { DefaultMultiValueCategoryDataset d1 = new DefaultMultiValueCategoryDataset(); DefaultMultiValueCategoryDataset d2 = (DefaultMultiValueCategoryDataset)
/* =========================================================== * 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.] * * ----------------------------------------- * DefaultMultiValueCategoryDatasetTest.java * ----------------------------------------- * (C) Copyright 2007-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 28-Sep-2007 : Version 1 (DG); * */ package org.jfree.data.statistics; /** * Tests for the {@link DefaultMultiValueCategoryDataset} class. */ public class DefaultMultiValueCategoryDatasetTest { /** * Some checks for the getValue() method. */ @Test public void testGetValue() { DefaultMultiValueCategoryDataset d = new DefaultMultiValueCategoryDataset(); List values = new ArrayList(); values.add(new Integer(1)); values.add(new Integer(2)); d.add(values, "R1", "C1"); assertEquals(new Double(1.5), d.getValue("R1", "C1")); boolean pass = false; try { d.getValue("XX", "C1"); } catch (UnknownKeyException e) { pass = true; } assertTrue(pass); pass = false; try { d.getValue("R1", "XX"); } catch (UnknownKeyException e) { pass = true; } assertTrue(pass); } /** * A simple check for the getValue(int, int) method. */ @Test public void testGetValue2() { DefaultMultiValueCategoryDataset d = new DefaultMultiValueCategoryDataset(); boolean pass = false; try { /* Number n =*/ d.getValue(0, 0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some tests for the getRowCount() method. */ @Test public void testGetRowCount() { DefaultMultiValueCategoryDataset d = new DefaultMultiValueCategoryDataset(); assertTrue(d.getRowCount() == 0); List values = new ArrayList(); d.add(values, "R1", "C1"); assertTrue(d.getRowCount() == 1); d.add(values, "R2", "C1"); assertTrue(d.getRowCount() == 2); d.add(values, "R2", "C1"); assertTrue(d.getRowCount() == 2); } /** * Some tests for the getColumnCount() method. */ @Test public void testGetColumnCount() { DefaultMultiValueCategoryDataset d = new DefaultMultiValueCategoryDataset(); assertTrue(d.getColumnCount() == 0); List values = new ArrayList(); d.add(values, "R1", "C1"); assertTrue(d.getColumnCount() == 1); d.add(values, "R1", "C2"); assertTrue(d.getColumnCount() == 2); d.add(values, "R1", "C2"); assertTrue(d.getColumnCount() == 2); } /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultMultiValueCategoryDataset d1 = new DefaultMultiValueCategoryDataset(); DefaultMultiValueCategoryDataset d2 = new DefaultMultiValueCategoryDataset(); assertTrue(d1.equals(d2)); assertTrue(d2.equals(d1)); List values = new ArrayList(); d1.add(values, "R1", "C1"); assertFalse(d1.equals(d2)); d2.add(values, "R1", "C1"); assertTrue(d1.equals(d2)); values.add(new Integer(99)); d1.add(values, "R1", "C1"); assertFalse(d1.equals(d2)); d2.add(values, "R1", "C1"); assertTrue(d1.equals(d2)); values.add(new Integer(99)); d1.add(values, "R1", "C2"); assertFalse(d1.equals(d2)); d2.add(values, "R1", "C2"); assertTrue(d1.equals(d2)); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { DefaultMultiValueCategoryDataset d1 = new DefaultMultiValueCategoryDataset(); DefaultMultiValueCategoryDataset d2 = (DefaultMultiValueCategoryDataset)
TestUtilities.serialised(d1);
0
2023-12-24 12:36:47+00:00
4k
viceice/verbrauchsapp
app/src/main/java/de/anipe/verbrauchsapp/fragments/GDriveImportFragment.java
[ { "identifier": "ImportGDriveCar", "path": "app/src/main/java/de/anipe/verbrauchsapp/tasks/ImportGDriveCar.java", "snippet": "public class ImportGDriveCar extends AsyncTask<String, Void, Void> {\n private Activity mCon;\n private ProgressDialog myprogsdial;\n private int dataSets = -2;\n pri...
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import de.anipe.verbrauchsapp.tasks.ImportGDriveCar; import de.anipe.verbrauchsapp.tasks.UpdateGDriveCarList;
1,701
package de.anipe.verbrauchsapp.fragments; public class GDriveImportFragment extends ImportFragment { private Map<String, String> fileMapping; @Override public void onImport(String item) {
package de.anipe.verbrauchsapp.fragments; public class GDriveImportFragment extends ImportFragment { private Map<String, String> fileMapping; @Override public void onImport(String item) {
new ImportGDriveCar(getActivity()).execute(fileMapping.get(item));
0
2023-12-28 12:33:52+00:00
4k
PSButlerII/SqlScriptGen
src/main/java/com/recondev/userinteraction/UserInteraction.java
[ { "identifier": "Enums", "path": "src/main/java/com/recondev/helpers/Enums.java", "snippet": "public class Enums {\n\n public enum DatabaseType {\n POSTGRESQL(\"PostgreSQL\"),\n MYSQL(\"MySQL\"),\n MONGODB(\"MongoDB\");\n\n private final String type;\n\n DatabaseTyp...
import com.recondev.helpers.Enums; import com.recondev.interfaces.DatabaseConstraintType; import java.util.*;
3,597
package com.recondev.userinteraction; public class UserInteraction { // private String getConstraintString(int constraintCount) { // // //TODO: Make this method more generic so it can be used for other databases // String constraintSQL = null; // for (int i = 0; i < constraintCount; i++) { // System.out.println("Choose constraint type:"); // // // print out the constraint types // for (int j = 0; j < Enums.PostgreSQLConstraintType.values().length; j++) { // System.out.println(j + ": " + Enums.PostgreSQLConstraintType.values()[j].getConstraintType()); // } // // int constraintTypeIndex = Integer.parseInt(scanner.nextLine()); // Enums.PostgreSQLConstraintType constraintType = Enums.PostgreSQLConstraintType.fromInt(constraintTypeIndex); // // System.out.println("Enter column name for constraint:"); // String columnName = scanner.nextLine(); // // String additionalInput = ""; // if (constraintType.requiresAdditionalInput()) { // if (constraintType == Enums.PostgreSQLConstraintType.FOREIGN_KEY) { // System.out.println("Enter table name for the constraint:"); // String tableName = scanner.nextLine(); // // System.out.println("Enter column name for the constraint:"); // String foreignKeyColumnName = scanner.nextLine(); // // additionalInput = tableName + "(" + foreignKeyColumnName + ")"; // } else if (constraintType == Enums.PostgreSQLConstraintType.CHECK) { // System.out.println("Enter check condition (e.g., column_name > 5):"); // additionalInput = scanner.nextLine(); // } // // // Assuming other constraint types might need a generic input // else if (constraintType == Enums.PostgreSQLConstraintType.UNIQUE || // constraintType == Enums.PostgreSQLConstraintType.PRIMARY_KEY /*|| // constraintType == Enums.PostgreSQLConstraintType.EXCLUSION*/) { // System.out.println("Enter additional input for the constraint:"); // additionalInput = scanner.nextLine(); // } // // Handle any other constraints that might need additional input // else { // System.out.println("Enter additional input for the constraint:"); // additionalInput = scanner.nextLine(); // } // } // constraintSQL = constraintType.getConstraintSQL(columnName, additionalInput); // } // return constraintSQL; // } private final Scanner scanner = new Scanner(System.in); public Enums.DatabaseType getDatabaseType() { System.out.println("Enter database type\n (1)PostgreSQL\n (2)MySQL\n (3)MongoDB)[**Currently only PostgreSQL and MySQL are supported**]"); int dbType; try { try { dbType = Integer.parseInt(scanner.nextLine()); } catch (NumberFormatException e) { System.out.println("Please enter a valid number"); return getDatabaseType(); } //get a map of the database types and their corresponding numbers Map<Integer, String> dbTypes = new HashMap<>(); int index = 1; for (Enums.DatabaseType type : Enums.DatabaseType.values()) { dbTypes.put(index, String.valueOf(type)); index++; } //if the user entered a valid number, return the corresponding database type if (dbTypes.containsKey(dbType)) { return Enums.DatabaseType.valueOf(dbTypes.get(dbType)); } } catch (NumberFormatException e) { System.out.println("Please enter a valid number"); return getDatabaseType(); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); return getDatabaseType(); } catch (Exception e) { System.out.println(e.getMessage()); return getDatabaseType(); } return null; } public String getTableName() { System.out.println("Enter table name:"); return scanner.nextLine(); } public Map<String, String> getColumns(Enums.DatabaseType dbType) { System.out.println("Enter number of columns:"); int columnCount; Map<String, String> columns; try { try { columnCount = Integer.parseInt(scanner.nextLine()); } catch (NumberFormatException e) { System.out.println("Please enter a valid number"); return getColumns(dbType); } columns = new HashMap<>(); for (int i = 0; i < columnCount; i++) { System.out.println("Enter column name for column " + (i + 1) + ":"); String columnName = scanner.nextLine(); System.out.println("Enter data type for column " + columnName + ":"); String dataType = promptForDataType(dbType); columns.put(columnName, dataType); } } catch (NumberFormatException e) { System.out.println("Please enter a valid number"); return getColumns(dbType); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); return getColumns(dbType); } catch (Exception e) { System.out.println(e.getMessage()); return getColumns(dbType); } return columns; } public List<String> addSQLConstraints(Enums.DatabaseType dbType) { List<String> constraints = new ArrayList<>(); System.out.println("Do you want to add constraints? (yes/no)"); String addConstraints; String constraintSQL; try { try { addConstraints = scanner.nextLine(); } catch (NumberFormatException e) { System.out.println("Please enter yes or no"); return addSQLConstraints(dbType); } if (addConstraints.equalsIgnoreCase("yes") || addConstraints.equalsIgnoreCase("y")) { System.out.println("Enter number of constraints:"); int constraintCount = Integer.parseInt(scanner.nextLine()); //TODO: Make this method more generic so it can be used for other databases. Maybe pass in the database type? // constraintSQL = getConstraint(constraintCount,dbType); // constraints.add(constraintSQL); for (int i = 0; i < constraintCount; i++) { String constraint = getConstraint(dbType); constraints.add(constraint); } } else if (addConstraints.equalsIgnoreCase("no") || addConstraints.equalsIgnoreCase("n")) { System.out.println("No constraints added"); } else { System.out.println("Please enter yes or no"); return addSQLConstraints(dbType); } } catch (NumberFormatException e) { System.out.println("Please enter a valid number"); return addSQLConstraints(dbType); } catch (IllegalArgumentException e) { System.out.println("Input " + e.getMessage() + " is not valid" + "\nPlease enter a valid input"); return addSQLConstraints(dbType); } catch (Exception e) { System.out.println(e.getMessage()); return addSQLConstraints(dbType); } return constraints; } private String getConstraint(Enums.DatabaseType dbType) { //TODO: Make this method more generic so it can be used for other databases String constraintSQL = null; int constraintTypeIndex; String columnName; System.out.println("Choose constraint type:"); constraintTypeIndex = getConstraintValues(dbType); //Should this be a method that takes in the database type and returns the appropriate constraint types?
package com.recondev.userinteraction; public class UserInteraction { // private String getConstraintString(int constraintCount) { // // //TODO: Make this method more generic so it can be used for other databases // String constraintSQL = null; // for (int i = 0; i < constraintCount; i++) { // System.out.println("Choose constraint type:"); // // // print out the constraint types // for (int j = 0; j < Enums.PostgreSQLConstraintType.values().length; j++) { // System.out.println(j + ": " + Enums.PostgreSQLConstraintType.values()[j].getConstraintType()); // } // // int constraintTypeIndex = Integer.parseInt(scanner.nextLine()); // Enums.PostgreSQLConstraintType constraintType = Enums.PostgreSQLConstraintType.fromInt(constraintTypeIndex); // // System.out.println("Enter column name for constraint:"); // String columnName = scanner.nextLine(); // // String additionalInput = ""; // if (constraintType.requiresAdditionalInput()) { // if (constraintType == Enums.PostgreSQLConstraintType.FOREIGN_KEY) { // System.out.println("Enter table name for the constraint:"); // String tableName = scanner.nextLine(); // // System.out.println("Enter column name for the constraint:"); // String foreignKeyColumnName = scanner.nextLine(); // // additionalInput = tableName + "(" + foreignKeyColumnName + ")"; // } else if (constraintType == Enums.PostgreSQLConstraintType.CHECK) { // System.out.println("Enter check condition (e.g., column_name > 5):"); // additionalInput = scanner.nextLine(); // } // // // Assuming other constraint types might need a generic input // else if (constraintType == Enums.PostgreSQLConstraintType.UNIQUE || // constraintType == Enums.PostgreSQLConstraintType.PRIMARY_KEY /*|| // constraintType == Enums.PostgreSQLConstraintType.EXCLUSION*/) { // System.out.println("Enter additional input for the constraint:"); // additionalInput = scanner.nextLine(); // } // // Handle any other constraints that might need additional input // else { // System.out.println("Enter additional input for the constraint:"); // additionalInput = scanner.nextLine(); // } // } // constraintSQL = constraintType.getConstraintSQL(columnName, additionalInput); // } // return constraintSQL; // } private final Scanner scanner = new Scanner(System.in); public Enums.DatabaseType getDatabaseType() { System.out.println("Enter database type\n (1)PostgreSQL\n (2)MySQL\n (3)MongoDB)[**Currently only PostgreSQL and MySQL are supported**]"); int dbType; try { try { dbType = Integer.parseInt(scanner.nextLine()); } catch (NumberFormatException e) { System.out.println("Please enter a valid number"); return getDatabaseType(); } //get a map of the database types and their corresponding numbers Map<Integer, String> dbTypes = new HashMap<>(); int index = 1; for (Enums.DatabaseType type : Enums.DatabaseType.values()) { dbTypes.put(index, String.valueOf(type)); index++; } //if the user entered a valid number, return the corresponding database type if (dbTypes.containsKey(dbType)) { return Enums.DatabaseType.valueOf(dbTypes.get(dbType)); } } catch (NumberFormatException e) { System.out.println("Please enter a valid number"); return getDatabaseType(); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); return getDatabaseType(); } catch (Exception e) { System.out.println(e.getMessage()); return getDatabaseType(); } return null; } public String getTableName() { System.out.println("Enter table name:"); return scanner.nextLine(); } public Map<String, String> getColumns(Enums.DatabaseType dbType) { System.out.println("Enter number of columns:"); int columnCount; Map<String, String> columns; try { try { columnCount = Integer.parseInt(scanner.nextLine()); } catch (NumberFormatException e) { System.out.println("Please enter a valid number"); return getColumns(dbType); } columns = new HashMap<>(); for (int i = 0; i < columnCount; i++) { System.out.println("Enter column name for column " + (i + 1) + ":"); String columnName = scanner.nextLine(); System.out.println("Enter data type for column " + columnName + ":"); String dataType = promptForDataType(dbType); columns.put(columnName, dataType); } } catch (NumberFormatException e) { System.out.println("Please enter a valid number"); return getColumns(dbType); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); return getColumns(dbType); } catch (Exception e) { System.out.println(e.getMessage()); return getColumns(dbType); } return columns; } public List<String> addSQLConstraints(Enums.DatabaseType dbType) { List<String> constraints = new ArrayList<>(); System.out.println("Do you want to add constraints? (yes/no)"); String addConstraints; String constraintSQL; try { try { addConstraints = scanner.nextLine(); } catch (NumberFormatException e) { System.out.println("Please enter yes or no"); return addSQLConstraints(dbType); } if (addConstraints.equalsIgnoreCase("yes") || addConstraints.equalsIgnoreCase("y")) { System.out.println("Enter number of constraints:"); int constraintCount = Integer.parseInt(scanner.nextLine()); //TODO: Make this method more generic so it can be used for other databases. Maybe pass in the database type? // constraintSQL = getConstraint(constraintCount,dbType); // constraints.add(constraintSQL); for (int i = 0; i < constraintCount; i++) { String constraint = getConstraint(dbType); constraints.add(constraint); } } else if (addConstraints.equalsIgnoreCase("no") || addConstraints.equalsIgnoreCase("n")) { System.out.println("No constraints added"); } else { System.out.println("Please enter yes or no"); return addSQLConstraints(dbType); } } catch (NumberFormatException e) { System.out.println("Please enter a valid number"); return addSQLConstraints(dbType); } catch (IllegalArgumentException e) { System.out.println("Input " + e.getMessage() + " is not valid" + "\nPlease enter a valid input"); return addSQLConstraints(dbType); } catch (Exception e) { System.out.println(e.getMessage()); return addSQLConstraints(dbType); } return constraints; } private String getConstraint(Enums.DatabaseType dbType) { //TODO: Make this method more generic so it can be used for other databases String constraintSQL = null; int constraintTypeIndex; String columnName; System.out.println("Choose constraint type:"); constraintTypeIndex = getConstraintValues(dbType); //Should this be a method that takes in the database type and returns the appropriate constraint types?
DatabaseConstraintType constraintType = getSelectedConstraintType(dbType, constraintTypeIndex);
1
2023-12-29 01:53:43+00:00
4k
JoshiCodes/NewLabyAPI
src/main/java/de/joshicodes/newlabyapi/listener/ConfigListener.java
[ { "identifier": "NewLabyPlugin", "path": "src/main/java/de/joshicodes/newlabyapi/NewLabyPlugin.java", "snippet": "public final class NewLabyPlugin extends JavaPlugin {\n\n public static final Component PREFIX = MiniMessage.miniMessage().deserialize(\n \"<b><gradient:#227eb8:#53bbfb>NewLaby...
import de.joshicodes.newlabyapi.NewLabyPlugin; import de.joshicodes.newlabyapi.api.LabyModPermission; import de.joshicodes.newlabyapi.api.event.player.LabyModPlayerJoinEvent; import de.joshicodes.newlabyapi.api.mouse.MouseMenuActionList; import de.joshicodes.newlabyapi.api.mouse.MouseMenuActionType; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map;
2,339
package de.joshicodes.newlabyapi.listener; public class ConfigListener implements Listener { private final FileConfiguration config; public ConfigListener(@NotNull FileConfiguration config) { this.config = config; } @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) public void onLabyJoin(LabyModPlayerJoinEvent event) { if (config.getBoolean("permissions.use", false)) { HashMap<LabyModPermission, Boolean> permissions = new HashMap<>(); for (LabyModPermission permission : LabyModPermission.values()) { permissions.put(permission, config.getBoolean("permissions.list." + permission.name(), permission.isDefaultEnabled())); } event.getPlayer().sendPermissions(permissions); } if (config.getBoolean("serverBanner.send", false)) event.getPlayer().sendServerBanner(config.getString("serverBanner.url")); if (config.getBoolean("extendActionMenu.use", false)) { MouseMenuActionList list = new MouseMenuActionList(); for (Map<?, ?> map : config.getMapList("extendActionMenu.list")) {
package de.joshicodes.newlabyapi.listener; public class ConfigListener implements Listener { private final FileConfiguration config; public ConfigListener(@NotNull FileConfiguration config) { this.config = config; } @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) public void onLabyJoin(LabyModPlayerJoinEvent event) { if (config.getBoolean("permissions.use", false)) { HashMap<LabyModPermission, Boolean> permissions = new HashMap<>(); for (LabyModPermission permission : LabyModPermission.values()) { permissions.put(permission, config.getBoolean("permissions.list." + permission.name(), permission.isDefaultEnabled())); } event.getPlayer().sendPermissions(permissions); } if (config.getBoolean("serverBanner.send", false)) event.getPlayer().sendServerBanner(config.getString("serverBanner.url")); if (config.getBoolean("extendActionMenu.use", false)) { MouseMenuActionList list = new MouseMenuActionList(); for (Map<?, ?> map : config.getMapList("extendActionMenu.list")) {
NewLabyPlugin.debug("Found action menu entry!");
0
2023-12-24 15:00:08+00:00
4k
1752597830/admin-common
qf-admin/back/admin-init-main/src/main/java/com/qf/web/service/impl/SysMenuServiceImpl.java
[ { "identifier": "SecurityUtils", "path": "qf-admin/back/admin-init-main/src/main/java/com/qf/common/utils/SecurityUtils.java", "snippet": "public class SecurityUtils {\n /**\n * 通过SecurityContextHandler获取当前用户身份令牌\n */\n public static Authentication getAuthentication() {\n Authentica...
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.qf.common.utils.SecurityUtils; import com.qf.web.domain.entity.SysMenu; import com.qf.web.domain.entity.SysUser; import com.qf.web.domain.dto.MenuOptionsDto; import com.qf.web.domain.vo.MenuOptions; import com.qf.web.domain.vo.RouteVo; import com.qf.web.domain.vo.RouteVo.Meta; import com.qf.web.service.SysMenuService; import com.qf.web.mapper.SysMenuMapper; import com.qf.web.service.SysPermissionService; import jakarta.annotation.Resource; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors;
2,988
package com.qf.web.service.impl; /** * @author 清风 * @description 针对表【sys_menu(菜单管理)】的数据库操作Service实现 * @createDate 2023-12-15 17:25:35 */ @Service public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService { @Resource private SysMenuMapper sysMenuMapper; @Resource private SysPermissionService sysPermissionService; @Override public List<RouteVo> getRoutes() {
package com.qf.web.service.impl; /** * @author 清风 * @description 针对表【sys_menu(菜单管理)】的数据库操作Service实现 * @createDate 2023-12-15 17:25:35 */ @Service public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService { @Resource private SysMenuMapper sysMenuMapper; @Resource private SysPermissionService sysPermissionService; @Override public List<RouteVo> getRoutes() {
SysUser userInfo = SecurityUtils.getUserInfo();
2
2023-12-30 13:42:53+00:00
4k
JIGerss/Salus
salus-web/src/main/java/team/glhf/salus/controller/PlaceController.java
[ { "identifier": "CommentReq", "path": "salus-pojo/src/main/java/team/glhf/salus/dto/place/CommentReq.java", "snippet": "@Data\r\n@Builder\r\npublic class CommentReq implements Serializable {\r\n\r\n @Null(message = \"cannot use userId to access\")\r\n private String userId;\r\n\r\n @NotBlank(me...
import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import team.glhf.salus.annotation.JwtVerify; import team.glhf.salus.dto.place.CommentReq; import team.glhf.salus.dto.place.CreateReq; import team.glhf.salus.dto.place.CreateRes; import team.glhf.salus.dto.place.PointReq; import team.glhf.salus.result.Result; import team.glhf.salus.service.PlaceService;
1,960
package team.glhf.salus.controller; /** * Place controller for web application * * @author Felix * @since 2023/11/21 */ @RestController @RequestMapping("/place") public class PlaceController { private final PlaceService placeService; public PlaceController(PlaceService placeService) { this.placeService = placeService; } @PostMapping("/create")
package team.glhf.salus.controller; /** * Place controller for web application * * @author Felix * @since 2023/11/21 */ @RestController @RequestMapping("/place") public class PlaceController { private final PlaceService placeService; public PlaceController(PlaceService placeService) { this.placeService = placeService; } @PostMapping("/create")
public Result<CreateRes> createPlace(CreateReq createReq) {
2
2023-12-23 15:03:37+00:00
4k
swsm/proxynet
proxynet-client/src/main/java/com/swsm/proxynet/client/init/SpringInitRunner.java
[ { "identifier": "ProxyConfig", "path": "proxynet-client/src/main/java/com/swsm/proxynet/client/config/ProxyConfig.java", "snippet": "@Configuration\n@Data\npublic class ProxyConfig {\n\n @Value(\"${proxynet.client.id}\")\n private Integer clientId;\n\n @Value(\"${proxynet.client.serverIp}\")\n ...
import com.swsm.proxynet.client.config.ProxyConfig; import com.swsm.proxynet.client.handler.ClientServerChannelHandler; import com.swsm.proxynet.client.handler.ClientTargetChannelHandler; import com.swsm.proxynet.common.handler.ProxyNetMessageDecoder; import com.swsm.proxynet.common.handler.ProxyNetMessageEncoder; import com.swsm.proxynet.common.model.ProxyNetMessage; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.timeout.IdleStateHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import static com.swsm.proxynet.common.Constants.ALL_IDLE_SECOND_TIME; import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_LENGTH_FILED_LENGTH; import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_LENGTH_FILED_OFFSET; import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_MAX_SIZE; import static com.swsm.proxynet.common.Constants.READ_IDLE_SECOND_TIME; import static com.swsm.proxynet.common.Constants.WRITE_IDLE_SECOND_TIME;
3,483
package com.swsm.proxynet.client.init; /** * @author liujie * @date 2023-04-15 */ @Component @Slf4j public class SpringInitRunner implements CommandLineRunner { @Autowired private ProxyConfig proxyConfig; public static Bootstrap bootstrapForTarget; public static Bootstrap bootstrapForServer; @Override public void run(String... args) throws Exception { log.info("proxyclient spring启动完成,接下来启动 连接代理服务器的客户端"); log.info("启动 连接代理服务器的客户端..."); bootstrapForServer = new Bootstrap(); bootstrapForServer.group(new NioEventLoopGroup(4)) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(
package com.swsm.proxynet.client.init; /** * @author liujie * @date 2023-04-15 */ @Component @Slf4j public class SpringInitRunner implements CommandLineRunner { @Autowired private ProxyConfig proxyConfig; public static Bootstrap bootstrapForTarget; public static Bootstrap bootstrapForServer; @Override public void run(String... args) throws Exception { log.info("proxyclient spring启动完成,接下来启动 连接代理服务器的客户端"); log.info("启动 连接代理服务器的客户端..."); bootstrapForServer = new Bootstrap(); bootstrapForServer.group(new NioEventLoopGroup(4)) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(
new ProxyNetMessageDecoder(PROXY_MESSAGE_MAX_SIZE, PROXY_MESSAGE_LENGTH_FILED_OFFSET, PROXY_MESSAGE_LENGTH_FILED_LENGTH));
8
2023-12-25 03:25:38+00:00
4k
Trodev-IT/ScanHub
app/src/main/java/com/trodev/scanhub/fragments/UrlFragment.java
[ { "identifier": "EmailAdapter", "path": "app/src/main/java/com/trodev/scanhub/adapters/EmailAdapter.java", "snippet": "public class EmailAdapter extends RecyclerView.Adapter<EmailAdapter.MyViewHolder> {\n\n private Context context;\n private ArrayList<EmailModel> list;\n private String category...
import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.airbnb.lottie.LottieAnimationView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.trodev.scanhub.R; import com.trodev.scanhub.adapters.EmailAdapter; import com.trodev.scanhub.adapters.LocationAdapter; import com.trodev.scanhub.adapters.URLAdapter; import com.trodev.scanhub.models.LocationModel; import com.trodev.scanhub.models.URLModel; import java.util.ArrayList;
2,412
package com.trodev.scanhub.fragments; public class UrlFragment extends Fragment { private RecyclerView recyclerView; DatabaseReference reference; ArrayList<URLModel> list;
package com.trodev.scanhub.fragments; public class UrlFragment extends Fragment { private RecyclerView recyclerView; DatabaseReference reference; ArrayList<URLModel> list;
URLAdapter adapter;
2
2023-12-26 05:10:38+00:00
4k
DMSAranda/backend-usersapp
src/main/java/com/dms/backend/usersapp/backendusersapp/auth/SpringSecurityConfig.java
[ { "identifier": "JwtAuthenticationFilter", "path": "src/main/java/com/dms/backend/usersapp/backendusersapp/auth/filters/JwtAuthenticationFilter.java", "snippet": "public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter{\n\n private AuthenticationManager authenticationManager...
import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import com.dms.backend.usersapp.backendusersapp.auth.filters.JwtAuthenticationFilter; import com.dms.backend.usersapp.backendusersapp.auth.filters.JwtValidationFilter;
1,617
package com.dms.backend.usersapp.backendusersapp.auth; //import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; @Configuration public class SpringSecurityConfig { @Autowired private AuthenticationConfiguration authenticationConfiguration; @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean AuthenticationManager authenticationManager() throws Exception{ return authenticationConfiguration.getAuthenticationManager(); } @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http.authorizeHttpRequests(authRules -> authRules .requestMatchers(HttpMethod.GET, "/users", "/users/page/{page}").permitAll() .requestMatchers(HttpMethod.GET, "/users/{id}").hasAnyRole("USER", "ADMIN") .requestMatchers(HttpMethod.POST, "/users").hasRole( "ADMIN") .requestMatchers(HttpMethod.PUT, "/users/{id}").hasRole( "ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/{id}").hasRole( "ADMIN") .anyRequest().authenticated() ) .addFilter(new JwtAuthenticationFilter(authenticationConfiguration.getAuthenticationManager()))
package com.dms.backend.usersapp.backendusersapp.auth; //import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; @Configuration public class SpringSecurityConfig { @Autowired private AuthenticationConfiguration authenticationConfiguration; @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean AuthenticationManager authenticationManager() throws Exception{ return authenticationConfiguration.getAuthenticationManager(); } @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http.authorizeHttpRequests(authRules -> authRules .requestMatchers(HttpMethod.GET, "/users", "/users/page/{page}").permitAll() .requestMatchers(HttpMethod.GET, "/users/{id}").hasAnyRole("USER", "ADMIN") .requestMatchers(HttpMethod.POST, "/users").hasRole( "ADMIN") .requestMatchers(HttpMethod.PUT, "/users/{id}").hasRole( "ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/{id}").hasRole( "ADMIN") .anyRequest().authenticated() ) .addFilter(new JwtAuthenticationFilter(authenticationConfiguration.getAuthenticationManager()))
.addFilter(new JwtValidationFilter(authenticationConfiguration.getAuthenticationManager()))
1
2023-12-29 15:55:27+00:00
4k
singuuu/java-spring-api
src/main/java/com/singu/api/services/AuthenticationService.java
[ { "identifier": "Token", "path": "src/main/java/com/singu/api/domains/Token.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\npublic class Token {\n\n @Id\n @GeneratedValue\n public Integer id;\n\n @Column(unique = true)\n public String token;\n\n @E...
import com.fasterxml.jackson.databind.ObjectMapper; import com.singu.api.domains.Token; import com.singu.api.domains.TokenType; import com.singu.api.domains.User; import com.singu.api.domains.requests.AuthenticationRequest; import com.singu.api.domains.requests.RegisterRequest; import com.singu.api.domains.responses.AuthenticationResponse; import com.singu.api.repositories.TokenRepository; import com.singu.api.repositories.UserRepository; import com.singu.api.security.JwtService; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpHeaders; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.io.IOException;
1,613
package com.singu.api.services; @Service @RequiredArgsConstructor public class AuthenticationService { private final UserRepository repository;
package com.singu.api.services; @Service @RequiredArgsConstructor public class AuthenticationService { private final UserRepository repository;
private final TokenRepository tokenRepository;
6
2023-12-28 17:32:16+00:00
4k
vnlemanhthanh/sfg-spring-6-webapp
src/main/java/com/vnlemanhthanh/spring6webapp/bootstrap/BootstrapData.java
[ { "identifier": "Author", "path": "src/main/java/com/vnlemanhthanh/spring6webapp/domain/Author.java", "snippet": "@Entity\npublic class Author {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n private String firstName;\n private String lastName;\n\n @Many...
import com.vnlemanhthanh.spring6webapp.domain.Author; import com.vnlemanhthanh.spring6webapp.domain.Book; import com.vnlemanhthanh.spring6webapp.domain.Publisher; import com.vnlemanhthanh.spring6webapp.repositories.AuthorRepository; import com.vnlemanhthanh.spring6webapp.repositories.BookRepository; import com.vnlemanhthanh.spring6webapp.repositories.PublisherRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component;
1,858
/* * Copyright (c) 2023. vnlemanhthanh.com */ package com.vnlemanhthanh.spring6webapp.bootstrap; @Component public class BootstrapData implements CommandLineRunner { private final AuthorRepository authorRepository; private final BookRepository bookRepository;
/* * Copyright (c) 2023. vnlemanhthanh.com */ package com.vnlemanhthanh.spring6webapp.bootstrap; @Component public class BootstrapData implements CommandLineRunner { private final AuthorRepository authorRepository; private final BookRepository bookRepository;
private final PublisherRepository publisherRepository;
5
2023-12-25 07:31:22+00:00
4k
Deepennn/NetAPP
src/main/java/com/netapp/APP.java
[ { "identifier": "NetFactory", "path": "src/main/java/com/netapp/config/NetFactory.java", "snippet": "public class NetFactory {\n public static Net provide(){\n return new Net(NET_NAME, DeviceFactory.provide());\n }\n}" }, { "identifier": "Net", "path": "src/main/java/com/netapp/...
import com.netapp.config.NetFactory; import com.netapp.net.Net; import java.util.Scanner; import static com.netapp.config.DeviceConfig.*;
2,608
package com.netapp; public class APP { public static Net net; public static void setup(){ // 创建网络
package com.netapp; public class APP { public static Net net; public static void setup(){ // 创建网络
net = NetFactory.provide();
0
2023-12-23 13:03:07+00:00
4k
jordqubbe/Extras
src/main/java/dev/jordgubbe/extras/library/Item.java
[ { "identifier": "ColorUtils", "path": "src/main/java/dev/jordgubbe/extras/utils/ColorUtils.java", "snippet": "public class ColorUtils {\n\n /**\n *\n * I DO NOT OWN THIS.\n * IT IS TAKEN (AND EDITED) FROM KODY SIMPSONS SIMP-API\n * https://github.com/Cortex-MC/SimpAPI\n * <p>\n ...
import dev.jordgubbe.extras.utils.ColorUtils; import dev.jordgubbe.extras.utils.SkullCreator; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; import java.util.List;
3,503
package dev.jordgubbe.extras.library; public class Item { /** * Creates a new ItemStack * @param name - Name of the new item * @param mat - Material of the new item (Don't use skulls with textures here) * @param amount - Amount of the new item * @param lore - Lore (if any) of the new item * @return - The newly created ItemStack */ public static ItemStack createItem(String name, Material mat, int amount, List<String> lore) { ItemStack item = new ItemStack(mat, amount); ItemMeta meta = item.getItemMeta(); assert meta != null; meta.setDisplayName(ColorUtils.format(name)); meta.setLore(lore); item.setItemMeta(meta); return item; } /** * Creates a Skull ItemStack that can get a texture from minecraft-heads.com * @param name Name of the skull item * @param lore lore (if any) of said skull item * @param url Provide a URL in the form of a Mojang texture * @return The newly created Skull ItemStack */ public static ItemStack createSkull(String name, List<String> lore, String url) { String prefix = "http://textures.minecraft.net/texture/"; ItemStack item = new ItemStack(Material.PLAYER_HEAD); SkullMeta meta = (SkullMeta) item.getItemMeta(); assert meta != null; meta.setDisplayName(ColorUtils.format(name)); meta.setLore(lore); item.setItemMeta(meta);
package dev.jordgubbe.extras.library; public class Item { /** * Creates a new ItemStack * @param name - Name of the new item * @param mat - Material of the new item (Don't use skulls with textures here) * @param amount - Amount of the new item * @param lore - Lore (if any) of the new item * @return - The newly created ItemStack */ public static ItemStack createItem(String name, Material mat, int amount, List<String> lore) { ItemStack item = new ItemStack(mat, amount); ItemMeta meta = item.getItemMeta(); assert meta != null; meta.setDisplayName(ColorUtils.format(name)); meta.setLore(lore); item.setItemMeta(meta); return item; } /** * Creates a Skull ItemStack that can get a texture from minecraft-heads.com * @param name Name of the skull item * @param lore lore (if any) of said skull item * @param url Provide a URL in the form of a Mojang texture * @return The newly created Skull ItemStack */ public static ItemStack createSkull(String name, List<String> lore, String url) { String prefix = "http://textures.minecraft.net/texture/"; ItemStack item = new ItemStack(Material.PLAYER_HEAD); SkullMeta meta = (SkullMeta) item.getItemMeta(); assert meta != null; meta.setDisplayName(ColorUtils.format(name)); meta.setLore(lore); item.setItemMeta(meta);
return SkullCreator.itemWithUrl(item, prefix + url);
1
2023-12-27 06:37:11+00:00
4k
LogDeArgentina/server
src/main/java/me/drpuc/lda/service/impl/QsoServiceImpl.java
[ { "identifier": "CallsignValidator", "path": "src/main/java/me/drpuc/lda/config/CallsignValidator.java", "snippet": "public class CallsignValidator extends RegexValidator {\n public CallsignValidator(String regex) {\n super(regex);\n }\n}" }, { "identifier": "Qso", "path": "src/...
import lombok.RequiredArgsConstructor; import me.drpuc.lda.config.CallsignValidator; import me.drpuc.lda.dto.request.radio.CreateQsoDto; import me.drpuc.lda.dto.request.radio.StationDto; import me.drpuc.lda.entity.Qso; import me.drpuc.lda.entity.Station; import me.drpuc.lda.entity.User; import me.drpuc.lda.radio.QsoConfirmation; import me.drpuc.lda.radio.RadioStatus; import me.drpuc.lda.repository.QsoRepository; import me.drpuc.lda.repository.StationRepository; import me.drpuc.lda.service.QsoService; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.access.AccessDeniedException; import org.springframework.stereotype.Service; import java.time.temporal.ChronoUnit; import java.util.*;
1,605
package me.drpuc.lda.service.impl; @Service @RequiredArgsConstructor
package me.drpuc.lda.service.impl; @Service @RequiredArgsConstructor
public class QsoServiceImpl implements QsoService {
8
2023-12-24 16:58:17+00:00
4k
strokegmd/StrokeClient
stroke/client/clickgui/component/components/sub/Checkbox.java
[ { "identifier": "Setting", "path": "stroke/client/clickgui/Setting.java", "snippet": "public class Setting {\n\t\n\tprivate String name;\n\tprivate BaseModule parent;\n\tprivate String mode;\n\t\n\tprivate String sval;\n\tprivate ArrayList<String> options;\n\tprivate String title;\n\t\n\tprivate boolean...
import java.awt.Color; import org.lwjgl.opengl.GL11; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.stroke.client.clickgui.Setting; import net.stroke.client.clickgui.component.Component; import net.stroke.client.clickgui.component.components.Button; import net.stroke.client.util.ColorUtils;
2,431
package net.stroke.client.clickgui.component.components.sub; public class Checkbox extends Component { private boolean hovered;
package net.stroke.client.clickgui.component.components.sub; public class Checkbox extends Component { private boolean hovered;
private Setting op;
0
2023-12-31 10:56:59+00:00
4k
Supriya2301/EVotingSystem-SpringJPA
EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/services/VotingService.java
[ { "identifier": "Election", "path": "EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/entities/Election.java", "snippet": "@Entity\npublic class Election {\n\t@Id\n\t@GeneratedValue(strategy= GenerationType.AUTO)\n\tprivate long id;\n\t\n\t@Column(unique=true)\n\tprivate String name;\n\n\tpubl...
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.codingninjas.EVotingSystem.entities.Election; import com.codingninjas.EVotingSystem.entities.ElectionChoice; import com.codingninjas.EVotingSystem.entities.User; import com.codingninjas.EVotingSystem.entities.Vote; import com.codingninjas.EVotingSystem.repositories.ElectionChoiceRepository; import com.codingninjas.EVotingSystem.repositories.ElectionRepository; import com.codingninjas.EVotingSystem.repositories.UserRepository; import com.codingninjas.EVotingSystem.repositories.VoteRepository;
1,625
package com.codingninjas.EVotingSystem.services; @Service public class VotingService { @Autowired VoteRepository voteRepository; @Autowired UserRepository userRepository; @Autowired ElectionRepository electionRepository; @Autowired ElectionChoiceRepository electionChoiceRepository; public List<Vote> getAllVotes() { return voteRepository.findAll(); } public void addUser(User user) { userRepository.save(user); } public List<User> getAllUsers() { return userRepository.findAll(); } public void addVote(Vote vote) { voteRepository.save(vote); } public void addElection(Election election) { electionRepository.save(election); } public List<Election> getAllElections() { return electionRepository.findAll(); }
package com.codingninjas.EVotingSystem.services; @Service public class VotingService { @Autowired VoteRepository voteRepository; @Autowired UserRepository userRepository; @Autowired ElectionRepository electionRepository; @Autowired ElectionChoiceRepository electionChoiceRepository; public List<Vote> getAllVotes() { return voteRepository.findAll(); } public void addUser(User user) { userRepository.save(user); } public List<User> getAllUsers() { return userRepository.findAll(); } public void addVote(Vote vote) { voteRepository.save(vote); } public void addElection(Election election) { electionRepository.save(election); } public List<Election> getAllElections() { return electionRepository.findAll(); }
public void addElectionChoice(ElectionChoice electionChoice) {
1
2023-12-30 06:54:58+00:00
4k
adamalexandru4/pgmq-spring
src/main/java/io/tembo/pgmq/config/PGMQAutoConfiguration.java
[ { "identifier": "PGMQClient", "path": "src/main/java/io/tembo/pgmq/PGMQClient.java", "snippet": "public class PGMQClient {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(PGMQClient.class);\n\n private final JdbcOperations operations;\n private final PGMQConfigurationProperties...
import com.fasterxml.jackson.databind.ObjectMapper; import io.tembo.pgmq.PGMQClient; import io.tembo.pgmq.json.PGMQJsonProcessor; import io.tembo.pgmq.json.PGMQJsonProcessorJackson; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.core.JdbcOperations;
2,246
package io.tembo.pgmq.config; @AutoConfiguration(after = { JacksonAutoConfiguration.class, DataSourceAutoConfiguration.class }) @EnableConfigurationProperties(PGMQConfigurationProperties.class) public class PGMQAutoConfiguration { @Bean
package io.tembo.pgmq.config; @AutoConfiguration(after = { JacksonAutoConfiguration.class, DataSourceAutoConfiguration.class }) @EnableConfigurationProperties(PGMQConfigurationProperties.class) public class PGMQAutoConfiguration { @Bean
@ConditionalOnMissingBean(PGMQJsonProcessor.class)
1
2023-12-22 19:29:05+00:00
4k
piovas-lu/condominio
src/main/java/app/condominio/controller/CondominioController.java
[ { "identifier": "Condominio", "path": "src/main/java/app/condominio/domain/Condominio.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"condominios\")\r\npublic class Condominio implements Serializable, Comparable<Condominio> {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = Ge...
import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import app.condominio.domain.Condominio; import app.condominio.domain.enums.Estado; import app.condominio.service.CondominioService;
3,090
package app.condominio.controller; @Controller @RequestMapping("sindico/condominio") public class CondominioController { @Autowired private CondominioService condominioService; @ModelAttribute("ativo") public String[] ativo() { return new String[] { "condominio", "cadastro" }; } @ModelAttribute("estados") public Estado[] estados() { return Estado.values(); } @GetMapping("/cadastro") public ModelAndView getCondominioCadastro(ModelMap model) {
package app.condominio.controller; @Controller @RequestMapping("sindico/condominio") public class CondominioController { @Autowired private CondominioService condominioService; @ModelAttribute("ativo") public String[] ativo() { return new String[] { "condominio", "cadastro" }; } @ModelAttribute("estados") public Estado[] estados() { return Estado.values(); } @GetMapping("/cadastro") public ModelAndView getCondominioCadastro(ModelMap model) {
Condominio condominio = condominioService.ler();
0
2023-12-29 22:19:42+00:00
4k
Tomate0613/boids
src/main/java/dev/doublekekse/boids/mixin/AbstractSchoolingFishMixin.java
[ { "identifier": "BoidGoal", "path": "src/main/java/dev/doublekekse/boids/goals/BoidGoal.java", "snippet": "public class BoidGoal extends Goal {\n public static final Logger LOGGER = LogManager.getLogger();\n\n public final float separationInfluence;\n public final float separationRange;\n pu...
import dev.doublekekse.boids.goals.BoidGoal; import dev.doublekekse.boids.goals.LimitSpeedAndLookInVelocityDirectionGoal; import dev.doublekekse.boids.goals.StayInWaterGoal; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.animal.AbstractFish; import net.minecraft.world.entity.animal.AbstractSchoolingFish; import net.minecraft.world.level.Level; 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;
1,793
package dev.doublekekse.boids.mixin; @Mixin(AbstractSchoolingFish.class) public abstract class AbstractSchoolingFishMixin extends AbstractFish { public AbstractSchoolingFishMixin(EntityType<? extends AbstractFish> entityType, Level level) { super(entityType, level); } @Inject(method = "registerGoals", at = @At("HEAD"), cancellable = true) protected void registerGoals(CallbackInfo ci) { this.goalSelector.addGoal(5, new BoidGoal(this, 0.5f, 0.9f, 8 / 20f, 1 / 20f));
package dev.doublekekse.boids.mixin; @Mixin(AbstractSchoolingFish.class) public abstract class AbstractSchoolingFishMixin extends AbstractFish { public AbstractSchoolingFishMixin(EntityType<? extends AbstractFish> entityType, Level level) { super(entityType, level); } @Inject(method = "registerGoals", at = @At("HEAD"), cancellable = true) protected void registerGoals(CallbackInfo ci) { this.goalSelector.addGoal(5, new BoidGoal(this, 0.5f, 0.9f, 8 / 20f, 1 / 20f));
this.goalSelector.addGoal(3, new StayInWaterGoal(this));
2
2023-12-27 15:14:24+00:00
4k
HuXin0817/shop_api
manager-api/src/main/java/cn/lili/controller/message/ServiceNoticeManagerController.java
[ { "identifier": "ResultUtil", "path": "framework/src/main/java/cn/lili/common/enums/ResultUtil.java", "snippet": "public class ResultUtil<T> {\n\n /**\n * 抽象类,存放结果\n */\n private final ResultMessage<T> resultMessage;\n /**\n * 正常响应\n */\n private static final Integer SUCCESS ...
import cn.lili.common.enums.ResultUtil; import cn.lili.common.vo.PageVO; import cn.lili.common.vo.ResultMessage; import cn.lili.common.vo.SearchVO; import cn.lili.modules.system.entity.dos.ServiceNotice; import cn.lili.modules.system.service.ServiceNoticeService; import cn.lili.mybatis.util.PageUtil; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List;
3,331
package cn.lili.controller.message; /** * 管理端,服务订阅消息接口 * * @author Chopper * @since 2020/11/17 4:33 下午 */ @RestController @Api(tags = "管理端,服务订阅消息接口") @RequestMapping("/manager/message/serviceNotice") public class ServiceNoticeManagerController { @Autowired
package cn.lili.controller.message; /** * 管理端,服务订阅消息接口 * * @author Chopper * @since 2020/11/17 4:33 下午 */ @RestController @Api(tags = "管理端,服务订阅消息接口") @RequestMapping("/manager/message/serviceNotice") public class ServiceNoticeManagerController { @Autowired
private ServiceNoticeService serviceNoticeService;
5
2023-12-24 19:45:18+00:00
4k
SocialPanda3578/OnlineShop
shop/src/shop/Panel/CartPanel.java
[ { "identifier": "Main", "path": "shop/src/shop/Main.java", "snippet": "public class Main\r\n{\r\n public static Scanner sc=new Scanner(System.in);\r\n\r\n public static void main(String[] args) throws SQLException, InterruptedException {\r\n MainPanel mainPanel = new MainPanel();\r\n ...
import java.sql.SQLException; import shop.Main; import shop.User; import shop.Cart;
2,900
package shop.Panel; public class CartPanel extends MainPanel{ public void cartPanel(User user) throws SQLException {
package shop.Panel; public class CartPanel extends MainPanel{ public void cartPanel(User user) throws SQLException {
Cart cart = new Cart();
2
2023-12-28 04:26:15+00:00
4k
emtee40/cpuspy-droid
app/src/main/java/com/tortel/cpuspy/ui/StateFragmentAdapter.java
[ { "identifier": "CpuSpyApp", "path": "app/src/main/java/com/tortel/cpuspy/CpuSpyApp.java", "snippet": "public class CpuSpyApp extends Application {\n\n private static final String KERNEL_VERSION_PATH = \"/proc/version\";\n\n private static final String TAG = \"CpuSpyApp\";\n\n private static fi...
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.tortel.cpuspy.CpuSpyApp; import com.tortel.cpuspy.CpuStateMonitor;
1,699
package com.tortel.cpuspy.ui; public class StateFragmentAdapter extends FragmentStatePagerAdapter { private CpuSpyApp mApp;
package com.tortel.cpuspy.ui; public class StateFragmentAdapter extends FragmentStatePagerAdapter { private CpuSpyApp mApp;
private CpuStateMonitor mMonitor;
1
2023-12-30 02:50:51+00:00
4k
MuskStark/EasyECharts
src/main/java/com/github/muskstark/echart/attribute/Legend.java
[ { "identifier": "EChartsExceptionsEnum", "path": "src/main/java/com/github/muskstark/echart/enums/EChartsExceptionsEnum.java", "snippet": "@Getter\npublic enum EChartsExceptionsEnum {\n\n ECharts_Invalid_TypeError(\"方法传入的参数为不受支持的类型\")\n ;\n private String message;\n\n private EChartsExceptio...
import com.github.muskstark.echart.enums.EChartsExceptionsEnum; import com.github.muskstark.echart.exception.EChartsException; import com.github.muskstark.echart.style.line.LineStyle; import com.github.muskstark.echart.style.text.TextStyle; import lombok.Getter; import java.util.List;
1,941
package com.github.muskstark.echart.attribute; /** * Legend for charts */ @Getter public class Legend { private String type; private String id; private Boolean show; private Double zLevel; private Double z; private Object left; private Object top; private Object right; private Object bottom; private Object width; private Object height; private String orient; private String align; private Integer[] padding; private Double itemGap; private Double itemWidth; private Double itemHeight; // private ItemStyle itemStyle; private LineStyle lineStyle; private Object symbolRotate; private String formatter; private Boolean selectedMode; private String inactiveColor; private String inactiveBorderColor; private String inactiveBorderWidth; private Object selected; private TextStyle textStyle; private ToolTip tooltip; private String icon; private List<Object> data; private String backgroundColor; private String borderColor; private Double borderWidth; private Integer[] borderRadius; private Double shadowBlur; private String shadowColor; private Double shadowOffsetX; private Double shadowOffsetY; private Double scrollDataIndex; private Double pageButtonItemGap; private Double pageButtonGap; private String pageButtonPosition; private String pageFormatter; // private PageIcons pageIcons; private String pageIconColor; private String pageIconInactiveColor; private Integer[] pageIconSize; // private TextStyle pageTextStyle; private Boolean animation; private Double animationDurationUpdate; // private Object emphasis; private Boolean[] selector; // private SelectorLabel selectorLabel; private String selectorPosition; private Integer selectorItemGap; private Integer selectorButtonGap; public Legend type(String type){ this.type = type; return this; } public Legend id(String id){ this.id = id; return this; } public Legend show(Boolean show){ this.show = show; return this; } public Legend zLevel(Double zLevel){ this.zLevel = zLevel; return this; } public Legend z(Double z){ this.z = z; return this; } public Legend left(Object left){ if(left instanceof String || left instanceof Double){ this.left = left; }else {
package com.github.muskstark.echart.attribute; /** * Legend for charts */ @Getter public class Legend { private String type; private String id; private Boolean show; private Double zLevel; private Double z; private Object left; private Object top; private Object right; private Object bottom; private Object width; private Object height; private String orient; private String align; private Integer[] padding; private Double itemGap; private Double itemWidth; private Double itemHeight; // private ItemStyle itemStyle; private LineStyle lineStyle; private Object symbolRotate; private String formatter; private Boolean selectedMode; private String inactiveColor; private String inactiveBorderColor; private String inactiveBorderWidth; private Object selected; private TextStyle textStyle; private ToolTip tooltip; private String icon; private List<Object> data; private String backgroundColor; private String borderColor; private Double borderWidth; private Integer[] borderRadius; private Double shadowBlur; private String shadowColor; private Double shadowOffsetX; private Double shadowOffsetY; private Double scrollDataIndex; private Double pageButtonItemGap; private Double pageButtonGap; private String pageButtonPosition; private String pageFormatter; // private PageIcons pageIcons; private String pageIconColor; private String pageIconInactiveColor; private Integer[] pageIconSize; // private TextStyle pageTextStyle; private Boolean animation; private Double animationDurationUpdate; // private Object emphasis; private Boolean[] selector; // private SelectorLabel selectorLabel; private String selectorPosition; private Integer selectorItemGap; private Integer selectorButtonGap; public Legend type(String type){ this.type = type; return this; } public Legend id(String id){ this.id = id; return this; } public Legend show(Boolean show){ this.show = show; return this; } public Legend zLevel(Double zLevel){ this.zLevel = zLevel; return this; } public Legend z(Double z){ this.z = z; return this; } public Legend left(Object left){ if(left instanceof String || left instanceof Double){ this.left = left; }else {
throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);
1
2023-12-25 08:03:42+00:00
4k
thanosmoschou/SpringBootPractise
colors/src/main/java/com/example/colors/config/PrinterConfig.java
[ { "identifier": "BluePrinter", "path": "colors/src/main/java/com/example/colors/services/BluePrinter.java", "snippet": "public interface BluePrinter\r\n{\r\n\tpublic String print();\r\n}\r" }, { "identifier": "ColorPrinter", "path": "colors/src/main/java/com/example/colors/services/ColorPrin...
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.example.colors.services.BluePrinter; import com.example.colors.services.ColorPrinter; import com.example.colors.services.GreenPrinter; import com.example.colors.services.RedPrinter; import com.example.colors.services.impl.ColorPrinterImpl; import com.example.colors.services.impl.SpanishBluePrinter; import com.example.colors.services.impl.SpanishGreenPrinter; import com.example.colors.services.impl.SpanishRedPrinter;
1,841
package com.example.colors.config; /* In Spring Boot, a bean is a Java object managed by the Spring framework's IoC (Inversion of Control) container. It is a fundamental building block of a Spring application and represents a reusable component that can be wired together with other beans to create the application's functionality. @Bean is used to define individual beans explicitly in Spring. When you create a method annotated with @Bean within a Spring @Configuration class, Spring will register the return value of that method as a bean in the Spring application context. You can use this annotation to customize the instantiation and configuration of specific beans, and it allows you to have fine-grained control over the objects created by Spring. @Configuration is used to indicate that a class defines Spring bean configurations. When you annotate a class with @Configuration, it tells Spring that this class contains one or more @Bean definitions or other bean-related configurations. Spring will process the bean definitions inside the @Configuration class and add them to the application context. @EnableAutoConfiguration is used to enable Spring Boot's auto-configuration mechanism. When you annotate your main class (the one annotated with @SpringBootApplication) or any other configuration class with @EnableAutoConfiguration, Spring Boot will automatically attempt to configure the application based on the dependencies and the classpath. It will enable sensible defaults for various configurations, such as database connections, message queues, and web frameworks, among others. Essentially, it allows you to let Spring Boot do much of the configuration work for you, based on the dependencies present in your project. In summary, @Bean is used to explicitly define individual beans in a Spring application, @Configuration is used to define a class as a source of bean configurations, and @EnableAutoConfiguration is used to enable Spring Boot's automatic configuration feature, which simplifies the setup of your application by configuring beans based on classpath and dependencies. */ @Configuration public class PrinterConfig { /* * Each method will create a Bean to be managed by the Spring container * Now that I have these Beans I can inject them wherever they are needed */ @Bean public RedPrinter redPrinter() { //The implementation of this method will return the implementation of RedPrinter //Remember from theory that interface types can also be used for declaring some objects //but you cannot use them with the new keyword to create objects of that interface. //You can only create objects of classes that implement this interface but their type //can also be declared as the interface name //For example: //RedPrinter printer = new EnglishRedPrinter(); this is valid if EnglishRedPrinter implements RedPrinter interface //RedPrinter printer = new Printer(); this is not valid because you cannot use the interface name to create objects //return new EnglishRedPrinter(); //Now I can change the implementation here without having to change anything else on the project //I declared interfaces there and I created Beans as concrete classes and spring will inject them //to the interface declarations
package com.example.colors.config; /* In Spring Boot, a bean is a Java object managed by the Spring framework's IoC (Inversion of Control) container. It is a fundamental building block of a Spring application and represents a reusable component that can be wired together with other beans to create the application's functionality. @Bean is used to define individual beans explicitly in Spring. When you create a method annotated with @Bean within a Spring @Configuration class, Spring will register the return value of that method as a bean in the Spring application context. You can use this annotation to customize the instantiation and configuration of specific beans, and it allows you to have fine-grained control over the objects created by Spring. @Configuration is used to indicate that a class defines Spring bean configurations. When you annotate a class with @Configuration, it tells Spring that this class contains one or more @Bean definitions or other bean-related configurations. Spring will process the bean definitions inside the @Configuration class and add them to the application context. @EnableAutoConfiguration is used to enable Spring Boot's auto-configuration mechanism. When you annotate your main class (the one annotated with @SpringBootApplication) or any other configuration class with @EnableAutoConfiguration, Spring Boot will automatically attempt to configure the application based on the dependencies and the classpath. It will enable sensible defaults for various configurations, such as database connections, message queues, and web frameworks, among others. Essentially, it allows you to let Spring Boot do much of the configuration work for you, based on the dependencies present in your project. In summary, @Bean is used to explicitly define individual beans in a Spring application, @Configuration is used to define a class as a source of bean configurations, and @EnableAutoConfiguration is used to enable Spring Boot's automatic configuration feature, which simplifies the setup of your application by configuring beans based on classpath and dependencies. */ @Configuration public class PrinterConfig { /* * Each method will create a Bean to be managed by the Spring container * Now that I have these Beans I can inject them wherever they are needed */ @Bean public RedPrinter redPrinter() { //The implementation of this method will return the implementation of RedPrinter //Remember from theory that interface types can also be used for declaring some objects //but you cannot use them with the new keyword to create objects of that interface. //You can only create objects of classes that implement this interface but their type //can also be declared as the interface name //For example: //RedPrinter printer = new EnglishRedPrinter(); this is valid if EnglishRedPrinter implements RedPrinter interface //RedPrinter printer = new Printer(); this is not valid because you cannot use the interface name to create objects //return new EnglishRedPrinter(); //Now I can change the implementation here without having to change anything else on the project //I declared interfaces there and I created Beans as concrete classes and spring will inject them //to the interface declarations
return new SpanishRedPrinter();
7
2023-12-31 17:29:44+00:00
4k
dmanzhang/jsystem-master6112_autotest
standupAgainstWind/automationProj/automationProj/src/main/java/org/jsystem/automationProj/MultiSwitchCase.java
[ { "identifier": "MyTestEnvironment", "path": "standupAgainstWind/drive-switch/drive-switch/src/main/java/org/jsystem/automationProj/MyTestEnvironment.java", "snippet": "public class MyTestEnvironment extends SystemObjectImpl {\r\n private String environmentName;\r\n private int switchNumber;\r\n ...
import org.junit.Before; import org.junit.Test; import org.jsystem.automationProj.MyTestEnvironment; import org.jsystem.automationProj.MySwitchOpen; import jsystem.extensions.analyzers.text.FindText; import junit.framework.SystemTestCase4;
3,308
package org.jsystem.automationProj; public class MultiSwitchCase extends SystemTestCase4 { public static int MaxSwitchs=8;
package org.jsystem.automationProj; public class MultiSwitchCase extends SystemTestCase4 { public static int MaxSwitchs=8;
MyTestEnvironment myEnvironment;
0
2023-12-22 01:32:25+00:00
4k
xyzell/OOP_UAS
Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/DashboardManageReceptionist.java
[ { "identifier": "Account", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/pojo/Account.java", "snippet": "public class Account {\n private String idAccount;\n private String email;\n private String username;\n private String password;\n private String level;\n\n public Acc...
import com.itenas.oop.org.uashotel.pojo.Account; import com.itenas.oop.org.uashotel.pojo.Receptionist; import com.itenas.oop.org.uashotel.service.ReceptionistService; import com.itenas.oop.org.uashotel.service.impl.ReceptionistServiceLoginImpl; import com.itenas.oop.org.uashotel.service.impl.ReceptionistServiceImpl; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import javax.swing.Timer;
2,884
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package com.itenas.oop.org.uashotel.swing; //Fero Refadha Zaidan bagian logic //Nicholas G.I Simanjuntak bagian user interface / design /** * * @author Nicholas */ public class DashboardManageReceptionist extends javax.swing.JFrame { ReceptionistServiceLoginImpl receplogin;
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package com.itenas.oop.org.uashotel.swing; //Fero Refadha Zaidan bagian logic //Nicholas G.I Simanjuntak bagian user interface / design /** * * @author Nicholas */ public class DashboardManageReceptionist extends javax.swing.JFrame { ReceptionistServiceLoginImpl receplogin;
ReceptionistServiceImpl recepDetail;
4
2023-12-24 11:39:51+00:00
4k
LawMashira/Springboot-3-Security-Registration-and-Login-
Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/service/UserServiceImpl.java
[ { "identifier": "Role", "path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/entity/Role.java", "snippet": "@Entity\n@Setter\n@Getter\n@NoArgsConstructor\npublic class Role {\n /*\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n pr...
import com.student.online.admission.system.rd.year.entity.Role; import com.student.online.admission.system.rd.year.entity.User; import com.student.online.admission.system.rd.year.exception.UserAlreadyExistsException; import com.student.online.admission.system.rd.year.exception.UserNotFoundException; import com.student.online.admission.system.rd.year.repository.RoleRepository; import com.student.online.admission.system.rd.year.repository.UserRepository; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.List;
1,634
package com.student.online.admission.system.rd.year.service; @Service @RequiredArgsConstructor public class UserServiceImpl implements UserService{ /* private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; private final RoleRepository roleRepository; @Override public User registerUser(User user) throws UserAlreadyExistsException { if(userRepository.existsByEmail(user.getEmail())){ throw new UserAlreadyExistsException(user.getEmail() + "already exists ") ; } user.setPassword(passwordEncoder.encode(user.getPassword())); Role userRole = roleRepository.findByName("ROLE_USER").get(); user.setRoles(Collections.singletonList(userRole)); return userRepository.save(user); } @Override public List<User> getUsers() { return userRepository.findAll(); } @Transactional @Override public void deleteUser(String email) { User theUser = getUser(email); if(theUser!=null){ userRepository.deleteByEmail(email); } } @Override public User getUser(String email) throws UserNotFoundException { return userRepository.findByEmail(email).orElseThrow(()->new UserNotFoundException("User not found exception")); }*/ private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; private final RoleRepository roleRepository; @Override public User registerUser(User user) { if (userRepository.existsByEmail(user.getEmail())){ throw new UserAlreadyExistsException(user.getEmail() + " already exists"); } user.setPassword(passwordEncoder.encode(user.getPassword())); System.out.println(user.getPassword());
package com.student.online.admission.system.rd.year.service; @Service @RequiredArgsConstructor public class UserServiceImpl implements UserService{ /* private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; private final RoleRepository roleRepository; @Override public User registerUser(User user) throws UserAlreadyExistsException { if(userRepository.existsByEmail(user.getEmail())){ throw new UserAlreadyExistsException(user.getEmail() + "already exists ") ; } user.setPassword(passwordEncoder.encode(user.getPassword())); Role userRole = roleRepository.findByName("ROLE_USER").get(); user.setRoles(Collections.singletonList(userRole)); return userRepository.save(user); } @Override public List<User> getUsers() { return userRepository.findAll(); } @Transactional @Override public void deleteUser(String email) { User theUser = getUser(email); if(theUser!=null){ userRepository.deleteByEmail(email); } } @Override public User getUser(String email) throws UserNotFoundException { return userRepository.findByEmail(email).orElseThrow(()->new UserNotFoundException("User not found exception")); }*/ private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; private final RoleRepository roleRepository; @Override public User registerUser(User user) { if (userRepository.existsByEmail(user.getEmail())){ throw new UserAlreadyExistsException(user.getEmail() + " already exists"); } user.setPassword(passwordEncoder.encode(user.getPassword())); System.out.println(user.getPassword());
Role userRole = roleRepository.findByName("ROLE_USER").get();
0
2023-12-30 19:51:38+00:00
4k
Duucking/UniversalTeleport
android-client/app/src/main/java/com/duucking/universalteleport/service/AppService.java
[ { "identifier": "TeleportUtil", "path": "android-client/app/src/main/java/com/duucking/universalteleport/util/TeleportUtil.java", "snippet": "public class TeleportUtil {\n private static boolean isOnRecv = false;\n private static boolean isOnSend = false;\n private static int recvProgress = 0;\...
import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.util.Log; import android.service.quicksettings.TileService; import androidx.annotation.NonNull; import com.duucking.universalteleport.BuildConfig; import com.duucking.universalteleport.R; import com.duucking.universalteleport.util.TeleportUtil; import com.duucking.universalteleport.util.ClipboardUtil; import java.io.IOException; import java.net.ServerSocket;
3,537
package com.duucking.universalteleport.service; public class AppService extends Service { private final String CHANNEL_DEFAULT_IMPORTANCE = "8848"; private final int ONGOING_NOTIFICATION_ID = 114; private ServerSocket message_server_socket; private ServerSocket file_server_socket; private Thread getMessagethread; private Thread getFilethread; private final Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); if (msg.what == 1) { Log.e("UniversalTeleportTest", "handle处理消息" + msg.obj); try { if (msg.obj.equals("funtion:fileTrans")) { getFilethread = new Thread(new getFileThread()); getFilethread.start(); } else { ClipboardUtil.setClipboard(getBaseContext(), String.valueOf(msg.obj)); } } catch (Exception e) { e.printStackTrace(); } } } }; public AppService() { } @Override public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @SuppressLint("ForegroundServiceType") @Override public void onCreate() { super.onCreate(); Log.d("UniversalTeleportTest", "AppService init"); try { message_server_socket = new ServerSocket(8556); file_server_socket = new ServerSocket(8558, 1); } catch (IOException e) { throw new RuntimeException(e); } //Service init createNotification(); //Create thread to listen tcp message getMessagethread = new Thread(new getTCPThread()); getMessagethread.start(); TileService.requestListeningState(this, new ComponentName(BuildConfig.APPLICATION_ID, QuickActionService.class.getName())); } @Override public void onDestroy() { super.onDestroy(); try { message_server_socket.close(); file_server_socket.close(); } catch (IOException e) { throw new RuntimeException(e); } TileService.requestListeningState(this, new ComponentName(BuildConfig.APPLICATION_ID, QuickActionService.class.getName())); Log.e("UniversalTeleportTest", "AppService destroy"); } @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); stopSelf(); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.notification_channel_id); String description = getString(R.string.notification_channel_desc); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel FGS_channel = new NotificationChannel(CHANNEL_DEFAULT_IMPORTANCE, name, importance); FGS_channel.setDescription(description); NotificationChannel FUS_channel = new NotificationChannel("8849", "文件传输通知", NotificationManager.IMPORTANCE_HIGH); FUS_channel.setDescription("文件传输时会发出此通知"); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(FGS_channel); notificationManager.createNotificationChannel(FUS_channel); } } private void createNotification() { Intent notificationIntent = new Intent(this, R.class); createNotificationChannel(); PendingIntent pendingIntent; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { pendingIntent = PendingIntent.getActivity(this, ONGOING_NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_IMMUTABLE); } else { pendingIntent = PendingIntent.getActivity(this, ONGOING_NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE); } Notification notification = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { Log.e("AppService", "buildNotification"); notification = new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE) .setContentTitle(getString(R.string.notification_title_name)) .setContentText(getString(R.string.notification_title_content1)) .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentIntent(pendingIntent) // .setTicker(getText(R.string.ticker_text)) .build(); } startForeground(ONGOING_NOTIFICATION_ID, notification); } public class getTCPThread implements Runnable { @Override public void run() { try {
package com.duucking.universalteleport.service; public class AppService extends Service { private final String CHANNEL_DEFAULT_IMPORTANCE = "8848"; private final int ONGOING_NOTIFICATION_ID = 114; private ServerSocket message_server_socket; private ServerSocket file_server_socket; private Thread getMessagethread; private Thread getFilethread; private final Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); if (msg.what == 1) { Log.e("UniversalTeleportTest", "handle处理消息" + msg.obj); try { if (msg.obj.equals("funtion:fileTrans")) { getFilethread = new Thread(new getFileThread()); getFilethread.start(); } else { ClipboardUtil.setClipboard(getBaseContext(), String.valueOf(msg.obj)); } } catch (Exception e) { e.printStackTrace(); } } } }; public AppService() { } @Override public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @SuppressLint("ForegroundServiceType") @Override public void onCreate() { super.onCreate(); Log.d("UniversalTeleportTest", "AppService init"); try { message_server_socket = new ServerSocket(8556); file_server_socket = new ServerSocket(8558, 1); } catch (IOException e) { throw new RuntimeException(e); } //Service init createNotification(); //Create thread to listen tcp message getMessagethread = new Thread(new getTCPThread()); getMessagethread.start(); TileService.requestListeningState(this, new ComponentName(BuildConfig.APPLICATION_ID, QuickActionService.class.getName())); } @Override public void onDestroy() { super.onDestroy(); try { message_server_socket.close(); file_server_socket.close(); } catch (IOException e) { throw new RuntimeException(e); } TileService.requestListeningState(this, new ComponentName(BuildConfig.APPLICATION_ID, QuickActionService.class.getName())); Log.e("UniversalTeleportTest", "AppService destroy"); } @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); stopSelf(); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.notification_channel_id); String description = getString(R.string.notification_channel_desc); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel FGS_channel = new NotificationChannel(CHANNEL_DEFAULT_IMPORTANCE, name, importance); FGS_channel.setDescription(description); NotificationChannel FUS_channel = new NotificationChannel("8849", "文件传输通知", NotificationManager.IMPORTANCE_HIGH); FUS_channel.setDescription("文件传输时会发出此通知"); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(FGS_channel); notificationManager.createNotificationChannel(FUS_channel); } } private void createNotification() { Intent notificationIntent = new Intent(this, R.class); createNotificationChannel(); PendingIntent pendingIntent; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { pendingIntent = PendingIntent.getActivity(this, ONGOING_NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_IMMUTABLE); } else { pendingIntent = PendingIntent.getActivity(this, ONGOING_NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE); } Notification notification = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { Log.e("AppService", "buildNotification"); notification = new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE) .setContentTitle(getString(R.string.notification_title_name)) .setContentText(getString(R.string.notification_title_content1)) .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentIntent(pendingIntent) // .setTicker(getText(R.string.ticker_text)) .build(); } startForeground(ONGOING_NOTIFICATION_ID, notification); } public class getTCPThread implements Runnable { @Override public void run() { try {
TeleportUtil.getTCPMessage(handler, message_server_socket);
0
2023-12-24 11:03:05+00:00
4k
LeeKyeongYong/SBookStudy
src/main/java/com/multibook/bookorder/domain/product/order/service/OrderService.java
[ { "identifier": "CashLog", "path": "src/main/java/com/multibook/bookorder/domain/cash/cash/entity/CashLog.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class CashLog extends Bas...
import com.multibook.bookorder.domain.cash.cash.entity.CashLog; import com.multibook.bookorder.domain.global.exceptions.GlobalException; import com.multibook.bookorder.domain.member.member.entity.Member; import com.multibook.bookorder.domain.member.member.service.MemberService; import com.multibook.bookorder.domain.product.cart.entity.CartItem; import com.multibook.bookorder.domain.product.cart.service.CartService; import com.multibook.bookorder.domain.product.order.entity.Order; import com.multibook.bookorder.domain.product.order.repository.OrderRepository; import com.multibook.bookorder.domain.product.product.entity.Product; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional;
3,477
package com.multibook.bookorder.domain.product.order.service; @Service @Transactional(readOnly = true) @RequiredArgsConstructor public class OrderService {
package com.multibook.bookorder.domain.product.order.service; @Service @Transactional(readOnly = true) @RequiredArgsConstructor public class OrderService {
private final OrderRepository orderRepository;
7
2023-12-26 14:58:59+00:00
4k
SDeVuyst/pingys-waddles-1.20.1
src/main/java/com/sdevuyst/pingyswaddles/item/ModItems.java
[ { "identifier": "PingysWaddles", "path": "src/main/java/com/sdevuyst/pingyswaddles/PingysWaddles.java", "snippet": "@Mod(PingysWaddles.MOD_ID)\npublic class PingysWaddles\n{\n // Define mod id in a common place for everything to reference\n public static final String MOD_ID = \"pingyswaddles\";\n ...
import com.sdevuyst.pingyswaddles.PingysWaddles; import com.sdevuyst.pingyswaddles.entity.ModEntities; import com.sdevuyst.pingyswaddles.entity.custom.SurfboardEntity; import com.sdevuyst.pingyswaddles.item.custom.SurfboardItem; import net.minecraft.world.item.*; import net.minecraftforge.common.ForgeSpawnEggItem; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject;
1,870
package com.sdevuyst.pingyswaddles.item; public class ModItems { public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, PingysWaddles.MOD_ID); public static final RegistryObject<Item> EMPEROR_PENGUIN_SPAWN_EGG = ITEMS.register("emperor_penguin_spawn_egg", () -> new ForgeSpawnEggItem(ModEntities.EMPEROR_PENGUIN, 0xf9f6ee, 0xf0b722, new Item.Properties())); public static final RegistryObject<Item> OAK_SURFBOARD = ITEMS.register("oak_surfboard",
package com.sdevuyst.pingyswaddles.item; public class ModItems { public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, PingysWaddles.MOD_ID); public static final RegistryObject<Item> EMPEROR_PENGUIN_SPAWN_EGG = ITEMS.register("emperor_penguin_spawn_egg", () -> new ForgeSpawnEggItem(ModEntities.EMPEROR_PENGUIN, 0xf9f6ee, 0xf0b722, new Item.Properties())); public static final RegistryObject<Item> OAK_SURFBOARD = ITEMS.register("oak_surfboard",
() -> new SurfboardItem(false, SurfboardEntity.Type.OAK, new Item.Properties()));
2
2023-12-31 09:54:03+00:00
4k
AweiMC/DragonMounts3
common/src/main/java/net/dragonmounts3/tools/DM3Item.java
[ { "identifier": "DM3Mod", "path": "common/src/main/java/net/dragonmounts3/DM3Mod.java", "snippet": "public class DM3Mod {\n public static final String MOD_ID = \"dragonmounts\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n public static void init() {\n Drago...
import dev.architectury.registry.CreativeTabRegistry; import dev.architectury.registry.registries.DeferredRegister; import dev.architectury.registry.registries.RegistrySupplier; import net.dragonmounts3.DM3Mod; import net.dragonmounts3.tools.DM3ToolMaterial.DM3Hoe; import net.dragonmounts3.tools.DM3ToolMaterial.DM3Shovel; import net.dragonmounts3.tools.DM3ToolMaterial.DM3Sword; import net.dragonmounts3.tools.DM3ToolMaterial.DM3ToolMaterials; import net.dragonmounts3.util.DragonTypeManager; import net.dragonmounts3.util.ToolType; import net.minecraft.item.*; import net.minecraft.registry.RegistryKeys; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import java.util.function.Supplier;
1,803
package net.dragonmounts3.tools; public interface DM3Item { DeferredRegister<ItemGroup> ITEM_GROUPS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM_GROUP); // 创建一个 DeferredRegister 来注册物品 RegistrySupplier<ItemGroup> DM3_GROUP = ITEM_GROUPS.register(new Identifier("dragonmounts3.title.group"), () -> CreativeTabRegistry.create( Text.translatable("dragonmounts3.title.group"), () -> Items.DIAMOND.asItem().getDefaultStack() )); DeferredRegister<Item> ITEMS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM); static void ItemRegister() { ITEM_GROUPS.register(); ITEMS.register(); // 这里注册你的物品 registerTools(); } static Item.Settings ItemToGroup() { return new Item.Settings().arch$tab(DM3_GROUP); } static void register(String name, Supplier<Item> item) { ITEMS.register(new Identifier(DM3Mod.MOD_ID,(name)), item); } static void registerTools() { for (String dragonType : DragonTypeManager.getDragonTypes()) { String DG = "_dragon"; register(dragonType + DG + "_sword", () -> createDM3Tool(dragonType, ToolType.SWORD)); // 注册对应类型的武器 register(dragonType + DG + "_pickaxe", () -> createDM3Tool(dragonType, ToolType.PICKAXE)); // 注册对应类型的镐 register(dragonType + DG + "_shovel", () -> createDM3Tool(dragonType, ToolType.SHOVEL)); // 注册对应类型的锹 // 添加其他工具类型的注册 } } static Item createDM3Tool(String dragonType, ToolType toolType) { // 根据传递的工具类型和DragonType创建对应的工具,并返回 // 此处根据传递的 ToolType 参数决定创建的是哪种类型的工具 return switch (toolType) { case SWORD -> new DM3Sword(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/); case PICKAXE -> new PickaxeItem(getToolMaterialForDragonType(dragonType), -1, -2.4F, ItemToGroup());
package net.dragonmounts3.tools; public interface DM3Item { DeferredRegister<ItemGroup> ITEM_GROUPS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM_GROUP); // 创建一个 DeferredRegister 来注册物品 RegistrySupplier<ItemGroup> DM3_GROUP = ITEM_GROUPS.register(new Identifier("dragonmounts3.title.group"), () -> CreativeTabRegistry.create( Text.translatable("dragonmounts3.title.group"), () -> Items.DIAMOND.asItem().getDefaultStack() )); DeferredRegister<Item> ITEMS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM); static void ItemRegister() { ITEM_GROUPS.register(); ITEMS.register(); // 这里注册你的物品 registerTools(); } static Item.Settings ItemToGroup() { return new Item.Settings().arch$tab(DM3_GROUP); } static void register(String name, Supplier<Item> item) { ITEMS.register(new Identifier(DM3Mod.MOD_ID,(name)), item); } static void registerTools() { for (String dragonType : DragonTypeManager.getDragonTypes()) { String DG = "_dragon"; register(dragonType + DG + "_sword", () -> createDM3Tool(dragonType, ToolType.SWORD)); // 注册对应类型的武器 register(dragonType + DG + "_pickaxe", () -> createDM3Tool(dragonType, ToolType.PICKAXE)); // 注册对应类型的镐 register(dragonType + DG + "_shovel", () -> createDM3Tool(dragonType, ToolType.SHOVEL)); // 注册对应类型的锹 // 添加其他工具类型的注册 } } static Item createDM3Tool(String dragonType, ToolType toolType) { // 根据传递的工具类型和DragonType创建对应的工具,并返回 // 此处根据传递的 ToolType 参数决定创建的是哪种类型的工具 return switch (toolType) { case SWORD -> new DM3Sword(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/); case PICKAXE -> new PickaxeItem(getToolMaterialForDragonType(dragonType), -1, -2.4F, ItemToGroup());
case SHOVEL -> new DM3Shovel(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/);
2
2023-12-28 12:11:21+00:00
4k
MinsTail/essential
src/main/java/com/dotSoftix/EssentialClient/EssentialMain.java
[ { "identifier": "onGuiOpenEvent", "path": "src/main/java/com/dotSoftix/Menu/onGuiOpenEvent.java", "snippet": "public class onGuiOpenEvent {\n @SideOnly(Side.CLIENT)\n @SubscribeEvent\n public void onGuiOpenEvent(GuiOpenEvent e) {\n if (e.getGui() instanceof GuiMainMenu) {\n e....
import com.dotSoftix.Menu.onGuiOpenEvent; import com.dotSoftix.EssentialClient.keyBinds.keyBind; import com.dotSoftix.EssentialClient.modules.RENDER.RedanMode; import com.dotSoftix.EssentialClient.modules.ui; import net.minecraft.init.Blocks; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.Display; import net.minecraft.client.Minecraft; import net.minecraft.util.Session; import java.lang.reflect.Field;
2,298
package com.dotSoftix.EssentialClient; @Mod(modid = EssentialMain.MODID, name = EssentialMain.NAME, version = EssentialMain.VERSION) public class EssentialMain { public static final String MODID = "essential (dotsoftix)"; public static final String NAME = "essential"; public static final String VERSION = "1.92"; private static Logger logger; @EventHandler public void preInit(FMLPreInitializationEvent event) { Display.setTitle("Loading " + ClientMain.clientName); logger = event.getModLog(); } @EventHandler public void init(FMLInitializationEvent event) { ClientMain.clientStartup(); MinecraftForge.EVENT_BUS.register(new keyBind());
package com.dotSoftix.EssentialClient; @Mod(modid = EssentialMain.MODID, name = EssentialMain.NAME, version = EssentialMain.VERSION) public class EssentialMain { public static final String MODID = "essential (dotsoftix)"; public static final String NAME = "essential"; public static final String VERSION = "1.92"; private static Logger logger; @EventHandler public void preInit(FMLPreInitializationEvent event) { Display.setTitle("Loading " + ClientMain.clientName); logger = event.getModLog(); } @EventHandler public void init(FMLInitializationEvent event) { ClientMain.clientStartup(); MinecraftForge.EVENT_BUS.register(new keyBind());
MinecraftForge.EVENT_BUS.register(new ui());
3
2023-12-28 15:15:14+00:00
4k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/poolServiceImpl.java
[ { "identifier": "poolToken", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/poolToken.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class poolToken {\n /**\n * pool_token 专属名(文件唯一)\n */\n private String poolName;\n\n /**\n * pool_token ...
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.tokensTool.pandoraNext.pojo.poolToken; import com.tokensTool.pandoraNext.pojo.systemSetting; import com.tokensTool.pandoraNext.pojo.token; import com.tokensTool.pandoraNext.service.poolService; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.regex.Pattern;
2,098
package com.tokensTool.pandoraNext.service.impl; /** * @author Yangyang * @create 2023-12-10 11:59 */ @Service @Slf4j
package com.tokensTool.pandoraNext.service.impl; /** * @author Yangyang * @create 2023-12-10 11:59 */ @Service @Slf4j
public class poolServiceImpl implements poolService {
3
2023-11-17 11:37:37+00:00
4k
quarkiverse/quarkus-langchain4j
openai/openai-vanilla/deployment/src/test/java/org/acme/examples/aiservices/DeclarativeAiServicesTest.java
[ { "identifier": "DEFAULT_TOKEN", "path": "openai/openai-vanilla/deployment/src/test/java/io/quarkiverse/langchain4j/openai/test/WiremockUtils.java", "snippet": "public static final String DEFAULT_TOKEN = \"whatever\";" }, { "identifier": "assertMultipleRequestMessage", "path": "openai/openai...
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static dev.langchain4j.data.message.ChatMessageDeserializer.messagesFromJson; import static dev.langchain4j.data.message.ChatMessageSerializer.messagesToJson; import static dev.langchain4j.data.message.ChatMessageType.AI; import static dev.langchain4j.data.message.ChatMessageType.USER; import static io.quarkiverse.langchain4j.openai.test.WiremockUtils.DEFAULT_TOKEN; import static org.acme.examples.aiservices.MessageAssertUtils.assertMultipleRequestMessage; import static org.acme.examples.aiservices.MessageAssertUtils.assertSingleRequestMessage; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import jakarta.enterprise.context.control.ActivateRequestContext; import jakarta.inject.Inject; import jakarta.inject.Singleton; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.stubbing.Scenario; import com.github.tomakehurst.wiremock.stubbing.ServeEvent; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import dev.langchain4j.agent.tool.Tool; import dev.langchain4j.data.message.ChatMessage; import dev.langchain4j.memory.chat.ChatMemoryProvider; import dev.langchain4j.memory.chat.MessageWindowChatMemory; import dev.langchain4j.service.MemoryId; import dev.langchain4j.service.UserMessage; import dev.langchain4j.store.memory.chat.ChatMemoryStore; import io.quarkiverse.langchain4j.RegisterAiService; import io.quarkiverse.langchain4j.openai.test.WiremockUtils; import io.quarkus.arc.Arc; import io.quarkus.test.QuarkusUnitTest;
3,246
@Singleton ChatMemoryProvider chatMemory(ChatMemoryStore store) { return memoryId -> MessageWindowChatMemory.builder() .id(memoryId) .maxMessages(10) .chatMemoryStore(store) .build(); } } @Singleton public static class CustomChatMemoryStore implements ChatMemoryStore { // emulating persistent storage private final Map</* memoryId */ Object, String> persistentStorage = new HashMap<>(); @Override public List<ChatMessage> getMessages(Object memoryId) { return messagesFromJson(persistentStorage.get(memoryId)); } @Override public void updateMessages(Object memoryId, List<ChatMessage> messages) { persistentStorage.put(memoryId, messagesToJson(messages)); } @Override public void deleteMessages(Object memoryId) { persistentStorage.remove(memoryId); } } @RegisterAiService(tools = Calculator.class) interface AssistantWithCalculator extends AssistantBase { } @Inject AssistantWithCalculator assistantWithCalculator; @Test @ActivateRequestContext void should_execute_tool_then_answer() throws IOException { var firstResponse = """ { "id": "chatcmpl-8D88Dag1gAKnOPP9Ed4bos7vSpaNz", "object": "chat.completion", "created": 1698140213, "model": "gpt-3.5-turbo-0613", "choices": [ { "index": 0, "message": { "role": "assistant", "content": null, "function_call": { "name": "squareRoot", "arguments": "{\\n \\"number\\": 485906798473894056\\n}" } }, "finish_reason": "function_call" } ], "usage": { "prompt_tokens": 65, "completion_tokens": 20, "total_tokens": 85 } } """; var secondResponse = """ { "id": "chatcmpl-8D88FIAUWSpwLaShFr0w8G1SWuVdl", "object": "chat.completion", "created": 1698140215, "model": "gpt-3.5-turbo-0613", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The square root of 485,906,798,473,894,056 in scientific notation is approximately 6.97070153193991E8." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 102, "completion_tokens": 33, "total_tokens": 135 } } """; wireMockServer.stubFor( WiremockUtils.chatCompletionMapping(DEFAULT_TOKEN) .inScenario(scenario) .whenScenarioStateIs(Scenario.STARTED) .willReturn(WiremockUtils.CHAT_RESPONSE_WITHOUT_BODY.withBody(firstResponse))); wireMockServer.stubFor( WiremockUtils.chatCompletionMapping(DEFAULT_TOKEN) .inScenario(scenario) .whenScenarioStateIs(secondState) .willReturn(WiremockUtils.CHAT_RESPONSE_WITHOUT_BODY.withBody(secondResponse))); wireMockServer.setScenarioState(scenario, Scenario.STARTED); String userMessage = "What is the square root of 485906798473894056 in scientific notation?"; String answer = assistantWithCalculator.chat(userMessage); assertThat(answer).isEqualTo( "The square root of 485,906,798,473,894,056 in scientific notation is approximately 6.97070153193991E8."); assertThat(wireMockServer.getAllServeEvents()).hasSize(2); assertSingleRequestMessage(getRequestAsMap(getRequestBody(wireMockServer.getAllServeEvents().get(1))), "What is the square root of 485906798473894056 in scientific notation?");
package org.acme.examples.aiservices; public class DeclarativeAiServicesTest { private static final int WIREMOCK_PORT = 8089; @RegisterExtension static final QuarkusUnitTest unitTest = new QuarkusUnitTest() .setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class).addClasses(WiremockUtils.class, MessageAssertUtils.class)) .overrideRuntimeConfigKey("quarkus.langchain4j.openai.api-key", "whatever") .overrideRuntimeConfigKey("quarkus.langchain4j.openai.base-url", "http://localhost:" + WIREMOCK_PORT + "/v1"); private static final TypeReference<Map<String, Object>> MAP_TYPE_REF = new TypeReference<>() { }; static WireMockServer wireMockServer; static ObjectMapper mapper; @BeforeAll static void beforeAll() { wireMockServer = new WireMockServer(options().port(WIREMOCK_PORT)); wireMockServer.start(); mapper = new ObjectMapper(); } @AfterAll static void afterAll() { wireMockServer.stop(); } @BeforeEach void setup() { wireMockServer.resetAll(); wireMockServer.stubFor(WiremockUtils.defaultChatCompletionsStub()); } interface AssistantBase { String chat(String message); } @RegisterAiService interface Assistant extends AssistantBase { String chat2(String message); } @Inject Assistant assistant; @Test @ActivateRequestContext public void test_simple_instruction_with_single_argument_and_no_annotations_from_super() throws IOException { String result = assistant.chat("Tell me a joke about developers"); assertThat(result).isNotBlank(); assertSingleRequestMessage(getRequestAsMap(), "Tell me a joke about developers"); } @Test @ActivateRequestContext public void test_simple_instruction_with_single_argument_and_no_annotations_from_iface() throws IOException { String result = assistant.chat2("Tell me a joke about developers"); assertThat(result).isNotBlank(); assertSingleRequestMessage(getRequestAsMap(), "Tell me a joke about developers"); } enum Sentiment { POSITIVE, NEUTRAL, NEGATIVE } @RegisterAiService interface SentimentAnalyzer { @UserMessage("Analyze sentiment of {it}") Sentiment analyzeSentimentOf(String text); } @Inject SentimentAnalyzer sentimentAnalyzer; @Test @ActivateRequestContext void test_extract_enum() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "POSITIVE")); Sentiment sentiment = sentimentAnalyzer .analyzeSentimentOf("This LaptopPro X15 is wicked fast and that 4K screen is a dream."); assertThat(sentiment).isEqualTo(Sentiment.POSITIVE); assertSingleRequestMessage(getRequestAsMap(), "Analyze sentiment of This LaptopPro X15 is wicked fast and that 4K screen is a dream.\nYou must answer strictly in the following format: one of [POSITIVE, NEUTRAL, NEGATIVE]"); } @Singleton static class Calculator { private final Runnable after; Calculator(CalculatorAfter after) { this.after = after; } @Tool("calculates the square root of the provided number") double squareRoot(double number) { var result = Math.sqrt(number); after.run(); return result; } } private static final String scenario = "tools"; private static final String secondState = "second"; @Singleton public static class CalculatorAfter implements Runnable { @Override public void run() { wireMockServer.setScenarioState(scenario, secondState); } } public static class ChatMemoryProviderProducer { @Singleton ChatMemoryProvider chatMemory(ChatMemoryStore store) { return memoryId -> MessageWindowChatMemory.builder() .id(memoryId) .maxMessages(10) .chatMemoryStore(store) .build(); } } @Singleton public static class CustomChatMemoryStore implements ChatMemoryStore { // emulating persistent storage private final Map</* memoryId */ Object, String> persistentStorage = new HashMap<>(); @Override public List<ChatMessage> getMessages(Object memoryId) { return messagesFromJson(persistentStorage.get(memoryId)); } @Override public void updateMessages(Object memoryId, List<ChatMessage> messages) { persistentStorage.put(memoryId, messagesToJson(messages)); } @Override public void deleteMessages(Object memoryId) { persistentStorage.remove(memoryId); } } @RegisterAiService(tools = Calculator.class) interface AssistantWithCalculator extends AssistantBase { } @Inject AssistantWithCalculator assistantWithCalculator; @Test @ActivateRequestContext void should_execute_tool_then_answer() throws IOException { var firstResponse = """ { "id": "chatcmpl-8D88Dag1gAKnOPP9Ed4bos7vSpaNz", "object": "chat.completion", "created": 1698140213, "model": "gpt-3.5-turbo-0613", "choices": [ { "index": 0, "message": { "role": "assistant", "content": null, "function_call": { "name": "squareRoot", "arguments": "{\\n \\"number\\": 485906798473894056\\n}" } }, "finish_reason": "function_call" } ], "usage": { "prompt_tokens": 65, "completion_tokens": 20, "total_tokens": 85 } } """; var secondResponse = """ { "id": "chatcmpl-8D88FIAUWSpwLaShFr0w8G1SWuVdl", "object": "chat.completion", "created": 1698140215, "model": "gpt-3.5-turbo-0613", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The square root of 485,906,798,473,894,056 in scientific notation is approximately 6.97070153193991E8." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 102, "completion_tokens": 33, "total_tokens": 135 } } """; wireMockServer.stubFor( WiremockUtils.chatCompletionMapping(DEFAULT_TOKEN) .inScenario(scenario) .whenScenarioStateIs(Scenario.STARTED) .willReturn(WiremockUtils.CHAT_RESPONSE_WITHOUT_BODY.withBody(firstResponse))); wireMockServer.stubFor( WiremockUtils.chatCompletionMapping(DEFAULT_TOKEN) .inScenario(scenario) .whenScenarioStateIs(secondState) .willReturn(WiremockUtils.CHAT_RESPONSE_WITHOUT_BODY.withBody(secondResponse))); wireMockServer.setScenarioState(scenario, Scenario.STARTED); String userMessage = "What is the square root of 485906798473894056 in scientific notation?"; String answer = assistantWithCalculator.chat(userMessage); assertThat(answer).isEqualTo( "The square root of 485,906,798,473,894,056 in scientific notation is approximately 6.97070153193991E8."); assertThat(wireMockServer.getAllServeEvents()).hasSize(2); assertSingleRequestMessage(getRequestAsMap(getRequestBody(wireMockServer.getAllServeEvents().get(1))), "What is the square root of 485906798473894056 in scientific notation?");
assertMultipleRequestMessage(getRequestAsMap(getRequestBody(wireMockServer.getAllServeEvents().get(0))),
1
2023-11-13 09:10:27+00:00
4k
qiusunshine/xiu
clinglibrary/src/main/java/org/fourthline/cling/protocol/async/SendingSearch.java
[ { "identifier": "UpnpService", "path": "clinglibrary/src/main/java/org/fourthline/cling/UpnpService.java", "snippet": "public interface UpnpService {\n\n public UpnpServiceConfiguration getConfiguration();\n\n public ControlPoint getControlPoint();\n\n public ProtocolFactory getProtocolFactory(...
import org.fourthline.cling.UpnpService; import org.fourthline.cling.model.message.discovery.OutgoingSearchRequest; import org.fourthline.cling.model.message.header.MXHeader; import org.fourthline.cling.model.message.header.STAllHeader; import org.fourthline.cling.model.message.header.UpnpHeader; import org.fourthline.cling.protocol.SendingAsync; import org.fourthline.cling.transport.RouterException; import java.util.logging.Logger;
3,089
/* * 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.protocol.async; /** * Sending search request messages using the supplied search type. * <p> * Sends all search messages 5 times, waits 0 to 500 * milliseconds between each sending procedure. * </p> * * @author Christian Bauer */ public class SendingSearch extends SendingAsync { final private static Logger log = Logger.getLogger(SendingSearch.class.getName()); private final UpnpHeader searchTarget; private final int mxSeconds; /** * Defaults to {@link org.fourthline.cling.model.message.header.STAllHeader} and an MX of 3 seconds. */
/* * 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.protocol.async; /** * Sending search request messages using the supplied search type. * <p> * Sends all search messages 5 times, waits 0 to 500 * milliseconds between each sending procedure. * </p> * * @author Christian Bauer */ public class SendingSearch extends SendingAsync { final private static Logger log = Logger.getLogger(SendingSearch.class.getName()); private final UpnpHeader searchTarget; private final int mxSeconds; /** * Defaults to {@link org.fourthline.cling.model.message.header.STAllHeader} and an MX of 3 seconds. */
public SendingSearch(UpnpService upnpService) {
0
2023-11-10 14:28:40+00:00
4k
noear/folkmq
folkmq-broker/src/main/java/org/noear/folkmq/broker/mq/BrokerListenerFolkmq.java
[ { "identifier": "IMqMessage", "path": "folkmq/src/main/java/org/noear/folkmq/client/IMqMessage.java", "snippet": "public interface IMqMessage {\n /**\n * 事务ID\n */\n String getTid();\n\n /**\n * 内容\n */\n String getContent();\n\n /**\n * 计划时间\n */\n Date getSche...
import org.noear.folkmq.client.IMqMessage; import org.noear.folkmq.common.MqConstants; import org.noear.folkmq.common.MqUtils; import org.noear.snack.ONode; import org.noear.socketd.broker.BrokerListener; import org.noear.socketd.transport.core.Entity; import org.noear.socketd.transport.core.Message; import org.noear.socketd.transport.core.Session; import org.noear.socketd.transport.core.entity.StringEntity; import org.noear.socketd.utils.StrUtils; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap;
3,119
log.info("Player channel opened, sessionId={}, ip={}", session.sessionId(), session.remoteAddress()); } @Override public void onClose(Session session) { super.onClose(session); log.info("Player channel closed, sessionId={}", session.sessionId()); Collection<String> atList = session.attrMap().keySet(); if (atList.size() > 0) { for (String at : atList) { //注销玩家 removePlayer(at, session); } } } @Override public void onMessage(Session requester, Message message) throws IOException { if (MqConstants.MQ_EVENT_SUBSCRIBE.equals(message.event())) { onSubscribe(requester, message); } else if (MqConstants.MQ_EVENT_UNSUBSCRIBE.equals(message.event())) { //取消订阅,注销玩家 String topic = message.meta(MqConstants.MQ_META_TOPIC); String consumerGroup = message.meta(MqConstants.MQ_META_CONSUMER_GROUP); String queueName = topic + MqConstants.SEPARATOR_TOPIC_CONSUMER_GROUP + consumerGroup; removePlayer(queueName, requester); } else if (MqConstants.MQ_EVENT_DISTRIBUTE.equals(message.event())) { String atName = message.atName(); //单发模式(给同名的某个玩家,轮询负截均衡) Session responder = getPlayerOne(atName); if (responder != null && responder.isValid()) { //转发消息 try { forwardToSession(requester, message, responder); } catch (Throwable e) { acknowledgeAsNo(requester, message); } } else { acknowledgeAsNo(requester, message); } //结束处理 return; } else if (MqConstants.MQ_EVENT_JOIN.equals(message.event())) { //同步订阅 if (subscribeMap.size() > 0) { String json = ONode.stringify(subscribeMap); Entity entity = new StringEntity(json).metaPut(MqConstants.MQ_META_BATCH, "1"); requester.sendAndRequest(MqConstants.MQ_EVENT_SUBSCRIBE, entity, 30_000).await(); } //注册服务 String name = requester.name(); if (StrUtils.isNotEmpty(name)) { addPlayer(name, requester); } log.info("Player channel joined, sessionId={}, ip={}", requester.sessionId(), requester.remoteAddress()); //结束处理 return; } if (message.event().startsWith(MqConstants.ADMIN_PREFIX)) { log.warn("Player channel admin events are not allowed, sessionId={}, ip={}", requester.sessionId(), requester.remoteAddress()); return; } super.onMessage(requester, message); } private void onSubscribe(Session requester, Message message) { String is_batch = message.meta(MqConstants.MQ_META_BATCH); if ("1".equals(is_batch)) { ONode oNode = ONode.loadStr(message.dataAsString()); Map<String, Collection<String>> subscribeData = oNode.toObject(); if (subscribeData != null) { for (Map.Entry<String, Collection<String>> kv : subscribeData.entrySet()) { for (String queueName : kv.getValue()) { //执行订阅 subscribeDo(requester, kv.getKey(), queueName); } } } } else { //订阅,注册玩家 String topic = message.meta(MqConstants.MQ_META_TOPIC); String consumerGroup = message.meta(MqConstants.MQ_META_CONSUMER_GROUP); String queueName = topic + MqConstants.SEPARATOR_TOPIC_CONSUMER_GROUP + consumerGroup; subscribeDo(requester, topic, queueName); } } public void subscribeDo(Session requester, String topic, String queueName) { if (requester != null) { requester.attrPut(queueName, "1"); addPlayer(queueName, requester); } synchronized (SUBSCRIBE_LOCK) { //以身份进行订阅(topic=>[topicConsumerGroup]) Set<String> topicConsumerSet = subscribeMap.computeIfAbsent(topic, n -> Collections.newSetFromMap(new ConcurrentHashMap<>())); topicConsumerSet.add(queueName); } } public boolean publishDo(String topic, IMqMessage message) throws IOException {
package org.noear.folkmq.broker.mq; /** * FolkMq 经纪人监听 * * @author noear * @since 1.0 */ public class BrokerListenerFolkmq extends BrokerListener { //访问账号 private Map<String, String> accessMap = new HashMap<>(); //订阅关系表(topic=>topicConsumerGroup[]) private Map<String, Set<String>> subscribeMap = new ConcurrentHashMap<>(); private Object SUBSCRIBE_LOCK = new Object(); public Map<String, Set<String>> getSubscribeMap() { return subscribeMap; } public void removeSubscribe(String topic, String queueName) { Set<String> tmp = subscribeMap.get(topic); if (tmp != null) { tmp.remove(queueName); } } /** * 配置访问账号 * * @param accessKey 访问者身份 * @param accessSecretKey 访问者密钥 */ public BrokerListenerFolkmq addAccess(String accessKey, String accessSecretKey) { accessMap.put(accessKey, accessSecretKey); return this; } /** * 配置访问账号 * * @param accessMap 访问账号集合 */ public BrokerListenerFolkmq addAccessAll(Map<String, String> accessMap) { if (accessMap != null) { this.accessMap.putAll(accessMap); } return this; } @Override public void onOpen(Session session) throws IOException { if (accessMap.size() > 0) { //如果有 ak/sk 配置,则进行鉴权 String accessKey = session.param(MqConstants.PARAM_ACCESS_KEY); String accessSecretKey = session.param(MqConstants.PARAM_ACCESS_SECRET_KEY); if (accessKey == null || accessSecretKey == null) { session.close(); return; } if (accessSecretKey.equals(accessMap.get(accessKey)) == false) { session.close(); return; } } if(MqConstants.BROKER_AT_SERVER.equals(session.name()) == false) { //如果不是 server,直接添加为 player super.onOpen(session); } log.info("Player channel opened, sessionId={}, ip={}", session.sessionId(), session.remoteAddress()); } @Override public void onClose(Session session) { super.onClose(session); log.info("Player channel closed, sessionId={}", session.sessionId()); Collection<String> atList = session.attrMap().keySet(); if (atList.size() > 0) { for (String at : atList) { //注销玩家 removePlayer(at, session); } } } @Override public void onMessage(Session requester, Message message) throws IOException { if (MqConstants.MQ_EVENT_SUBSCRIBE.equals(message.event())) { onSubscribe(requester, message); } else if (MqConstants.MQ_EVENT_UNSUBSCRIBE.equals(message.event())) { //取消订阅,注销玩家 String topic = message.meta(MqConstants.MQ_META_TOPIC); String consumerGroup = message.meta(MqConstants.MQ_META_CONSUMER_GROUP); String queueName = topic + MqConstants.SEPARATOR_TOPIC_CONSUMER_GROUP + consumerGroup; removePlayer(queueName, requester); } else if (MqConstants.MQ_EVENT_DISTRIBUTE.equals(message.event())) { String atName = message.atName(); //单发模式(给同名的某个玩家,轮询负截均衡) Session responder = getPlayerOne(atName); if (responder != null && responder.isValid()) { //转发消息 try { forwardToSession(requester, message, responder); } catch (Throwable e) { acknowledgeAsNo(requester, message); } } else { acknowledgeAsNo(requester, message); } //结束处理 return; } else if (MqConstants.MQ_EVENT_JOIN.equals(message.event())) { //同步订阅 if (subscribeMap.size() > 0) { String json = ONode.stringify(subscribeMap); Entity entity = new StringEntity(json).metaPut(MqConstants.MQ_META_BATCH, "1"); requester.sendAndRequest(MqConstants.MQ_EVENT_SUBSCRIBE, entity, 30_000).await(); } //注册服务 String name = requester.name(); if (StrUtils.isNotEmpty(name)) { addPlayer(name, requester); } log.info("Player channel joined, sessionId={}, ip={}", requester.sessionId(), requester.remoteAddress()); //结束处理 return; } if (message.event().startsWith(MqConstants.ADMIN_PREFIX)) { log.warn("Player channel admin events are not allowed, sessionId={}, ip={}", requester.sessionId(), requester.remoteAddress()); return; } super.onMessage(requester, message); } private void onSubscribe(Session requester, Message message) { String is_batch = message.meta(MqConstants.MQ_META_BATCH); if ("1".equals(is_batch)) { ONode oNode = ONode.loadStr(message.dataAsString()); Map<String, Collection<String>> subscribeData = oNode.toObject(); if (subscribeData != null) { for (Map.Entry<String, Collection<String>> kv : subscribeData.entrySet()) { for (String queueName : kv.getValue()) { //执行订阅 subscribeDo(requester, kv.getKey(), queueName); } } } } else { //订阅,注册玩家 String topic = message.meta(MqConstants.MQ_META_TOPIC); String consumerGroup = message.meta(MqConstants.MQ_META_CONSUMER_GROUP); String queueName = topic + MqConstants.SEPARATOR_TOPIC_CONSUMER_GROUP + consumerGroup; subscribeDo(requester, topic, queueName); } } public void subscribeDo(Session requester, String topic, String queueName) { if (requester != null) { requester.attrPut(queueName, "1"); addPlayer(queueName, requester); } synchronized (SUBSCRIBE_LOCK) { //以身份进行订阅(topic=>[topicConsumerGroup]) Set<String> topicConsumerSet = subscribeMap.computeIfAbsent(topic, n -> Collections.newSetFromMap(new ConcurrentHashMap<>())); topicConsumerSet.add(queueName); } } public boolean publishDo(String topic, IMqMessage message) throws IOException {
Message routingMessage = MqUtils.routingMessageBuild(topic, message);
2
2023-11-18 19:09:28+00:00
4k