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
wyjsonGo/GoRouter
GoRouter-Api/src/main/java/com/wyjson/router/GoRouter.java
[ { "identifier": "GoCallback", "path": "GoRouter-Api/src/main/java/com/wyjson/router/callback/GoCallback.java", "snippet": "public interface GoCallback {\n\n /**\n * 当找到目的地的回调\n *\n * @param card\n */\n void onFound(Card card);\n\n /**\n * 迷路后的回调。\n *\n * @param card\...
import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityOptionsCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Observer; import com.wyjson.router.callback.GoCallback; import com.wyjson.router.callback.InterceptorCallback; import com.wyjson.router.core.ApplicationModuleCenter; import com.wyjson.router.core.EventCenter; import com.wyjson.router.core.InterceptorCenter; import com.wyjson.router.core.InterceptorServiceImpl; import com.wyjson.router.core.RouteCenter; import com.wyjson.router.core.RouteModuleCenter; import com.wyjson.router.core.ServiceCenter; import com.wyjson.router.core.interfaces.IInterceptorService; import com.wyjson.router.exception.NoFoundRouteException; import com.wyjson.router.exception.ParamException; import com.wyjson.router.exception.RouterException; import com.wyjson.router.interfaces.IApplicationModule; import com.wyjson.router.interfaces.IDegradeService; import com.wyjson.router.interfaces.IInterceptor; import com.wyjson.router.interfaces.IPretreatmentService; import com.wyjson.router.interfaces.IService; import com.wyjson.router.logger.DefaultLogger; import com.wyjson.router.logger.ILogger; import com.wyjson.router.model.Card; import com.wyjson.router.module.interfaces.IRouteModuleGroup; import com.wyjson.router.thread.DefaultPoolExecutor; import com.wyjson.router.utils.TextUtils; import java.util.concurrent.ThreadPoolExecutor;
16,444
* 获取原始的URI * * @param activity */ public String getRawURI(Activity activity) { return RouteCenter.getRawURI(activity); } /** * 获取原始的URI * * @param fragment */ public String getRawURI(Fragment fragment) { return RouteCenter.getRawURI(fragment); } /** * 获取当前页面路径 * * @param activity */ public String getCurrentPath(Activity activity) { return RouteCenter.getCurrentPath(activity); } /** * 获取当前页面路径 * * @param fragment */ public String getCurrentPath(Fragment fragment) { return RouteCenter.getCurrentPath(fragment); } @Deprecated public void inject(Activity activity) { inject(activity, null, null, false); } @Deprecated public void inject(Activity activity, Intent intent) { inject(activity, intent, null, false); } @Deprecated public void inject(Activity activity, Bundle bundle) { inject(activity, null, bundle, false); } @Deprecated public void inject(Fragment fragment) { inject(fragment, null, null, false); } @Deprecated public void inject(Fragment fragment, Intent intent) { inject(fragment, intent, null, false); } @Deprecated public void inject(Fragment fragment, Bundle bundle) { inject(fragment, null, bundle, false); } @Deprecated public void injectCheck(Activity activity) throws ParamException { inject(activity, null, null, true); } @Deprecated public void injectCheck(Activity activity, Intent intent) throws ParamException { inject(activity, intent, null, true); } @Deprecated public void injectCheck(Activity activity, Bundle bundle) throws ParamException { inject(activity, null, bundle, true); } @Deprecated public void injectCheck(Fragment fragment) throws ParamException { inject(fragment, null, null, true); } @Deprecated public void injectCheck(Fragment fragment, Intent intent) throws ParamException { inject(fragment, intent, null, true); } @Deprecated public void injectCheck(Fragment fragment, Bundle bundle) throws ParamException { inject(fragment, null, bundle, true); } @Deprecated private <T> void inject(T target, Intent intent, Bundle bundle, boolean isCheck) throws ParamException { RouteCenter.inject(target, intent, bundle, isCheck); } @Nullable public Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) { card.setContext(context == null ? mApplication : context); card.setInterceptorException(null); logger.debug(null, "[go] " + card); IPretreatmentService pretreatmentService = getService(IPretreatmentService.class); if (pretreatmentService != null) { if (!pretreatmentService.onPretreatment(card.getContext(), card)) { // 预处理失败,导航取消 logger.debug(null, "[go] IPretreatmentService Failure!"); return null; } } else { logger.warning(null, "[go] This [IPretreatmentService] was not found!"); } try { RouteCenter.assembleRouteCard(card);
package com.wyjson.router; public final class GoRouter { private final Handler mHandler = new Handler(Looper.getMainLooper()); private volatile static ThreadPoolExecutor executor = DefaultPoolExecutor.getInstance(); public static ILogger logger = new DefaultLogger(); private volatile static boolean isDebug = false; private static Application mApplication; private GoRouter() { InterceptorCenter.clearInterceptors(); ServiceCenter.addService(InterceptorServiceImpl.class); } private static class InstanceHolder { private static final GoRouter mInstance = new GoRouter(); } public static GoRouter getInstance() { return InstanceHolder.mInstance; } /** * 自动加载模块路由 * * @param application */ public static synchronized void autoLoadRouteModule(Application application) { setApplication(application); logger.info(null, "[GoRouter] autoLoadRouteModule!"); RouteModuleCenter.load(application); } /** * 获取路由注册模式 * * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file] */ public boolean isRouteRegisterMode() { return RouteModuleCenter.isRegisterByPlugin(); } public static synchronized void openDebug() { isDebug = true; logger.showLog(isDebug); logger.info(null, "[openDebug]"); } public static void setApplication(Application application) { mApplication = application; } public static boolean isDebug() { return isDebug; } public static synchronized void printStackTrace() { logger.showStackTrace(true); logger.info(null, "[printStackTrace]"); } public static synchronized void setExecutor(ThreadPoolExecutor tpe) { executor = tpe; } public ThreadPoolExecutor getExecutor() { return executor; } public static void setLogger(ILogger userLogger) { if (userLogger != null) { logger = userLogger; } } /** * 获取模块application注册模式 * * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file] */ public boolean isAMRegisterMode() { return ApplicationModuleCenter.isRegisterByPlugin(); } public static void callAMOnCreate(Application application) { setApplication(application); ApplicationModuleCenter.callOnCreate(application); } public static void callAMOnTerminate() { ApplicationModuleCenter.callOnTerminate(); } public static void callAMOnConfigurationChanged(@NonNull Configuration newConfig) { ApplicationModuleCenter.callOnConfigurationChanged(newConfig); } public static void callAMOnLowMemory() { ApplicationModuleCenter.callOnLowMemory(); } public static void callAMOnTrimMemory(int level) { ApplicationModuleCenter.callOnTrimMemory(level); } /** * 动态注册模块application * * @param am */ public static void registerAM(Class<? extends IApplicationModule> am) { ApplicationModuleCenter.register(am); } /** * 实现相同接口的service会被覆盖(更新) * * @param service 实现类.class */ public void addService(Class<? extends IService> service) { ServiceCenter.addService(service); } /** * 实现相同接口的service会被覆盖(更新) * * @param service 实现类.class * @param alias 别名 */ public void addService(Class<? extends IService> service, String alias) { ServiceCenter.addService(service, alias); } /** * 获取service接口的实现 * * @param service 接口.class * @param <T> * @return */ @Nullable public <T> T getService(Class<? extends T> service) { return ServiceCenter.getService(service); } /** * 获取service接口的实现 * * @param service * @param alias 别名 * @param <T> * @return */ @Nullable public <T> T getService(Class<? extends T> service, String alias) { return ServiceCenter.getService(service, alias); } /** * 重复添加相同序号会catch * * @param ordinal * @param interceptor */ public void addInterceptor(int ordinal, Class<? extends IInterceptor> interceptor) { InterceptorCenter.addInterceptor(ordinal, interceptor, false); } /** * 重复添加相同序号会覆盖(更新) * * @param ordinal * @param interceptor */ public void setInterceptor(int ordinal, Class<? extends IInterceptor> interceptor) { InterceptorCenter.setInterceptor(ordinal, interceptor); } /** * 动态添加路由分组,按需加载路由 */ public void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { RouteCenter.addRouterGroup(group, routeModuleGroup); } private void runInMainThread(Runnable runnable) { if (Looper.getMainLooper().getThread() != Thread.currentThread()) { mHandler.post(runnable); } else { runnable.run(); } } public Card build(String path) { return build(path, null); } public Card build(String path, Bundle bundle) { return new Card(path, bundle); } public Card build(Uri uri) { return new Card(uri); } /** * 获取原始的URI * * @param activity */ public String getRawURI(Activity activity) { return RouteCenter.getRawURI(activity); } /** * 获取原始的URI * * @param fragment */ public String getRawURI(Fragment fragment) { return RouteCenter.getRawURI(fragment); } /** * 获取当前页面路径 * * @param activity */ public String getCurrentPath(Activity activity) { return RouteCenter.getCurrentPath(activity); } /** * 获取当前页面路径 * * @param fragment */ public String getCurrentPath(Fragment fragment) { return RouteCenter.getCurrentPath(fragment); } @Deprecated public void inject(Activity activity) { inject(activity, null, null, false); } @Deprecated public void inject(Activity activity, Intent intent) { inject(activity, intent, null, false); } @Deprecated public void inject(Activity activity, Bundle bundle) { inject(activity, null, bundle, false); } @Deprecated public void inject(Fragment fragment) { inject(fragment, null, null, false); } @Deprecated public void inject(Fragment fragment, Intent intent) { inject(fragment, intent, null, false); } @Deprecated public void inject(Fragment fragment, Bundle bundle) { inject(fragment, null, bundle, false); } @Deprecated public void injectCheck(Activity activity) throws ParamException { inject(activity, null, null, true); } @Deprecated public void injectCheck(Activity activity, Intent intent) throws ParamException { inject(activity, intent, null, true); } @Deprecated public void injectCheck(Activity activity, Bundle bundle) throws ParamException { inject(activity, null, bundle, true); } @Deprecated public void injectCheck(Fragment fragment) throws ParamException { inject(fragment, null, null, true); } @Deprecated public void injectCheck(Fragment fragment, Intent intent) throws ParamException { inject(fragment, intent, null, true); } @Deprecated public void injectCheck(Fragment fragment, Bundle bundle) throws ParamException { inject(fragment, null, bundle, true); } @Deprecated private <T> void inject(T target, Intent intent, Bundle bundle, boolean isCheck) throws ParamException { RouteCenter.inject(target, intent, bundle, isCheck); } @Nullable public Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) { card.setContext(context == null ? mApplication : context); card.setInterceptorException(null); logger.debug(null, "[go] " + card); IPretreatmentService pretreatmentService = getService(IPretreatmentService.class); if (pretreatmentService != null) { if (!pretreatmentService.onPretreatment(card.getContext(), card)) { // 预处理失败,导航取消 logger.debug(null, "[go] IPretreatmentService Failure!"); return null; } } else { logger.warning(null, "[go] This [IPretreatmentService] was not found!"); } try { RouteCenter.assembleRouteCard(card);
} catch (NoFoundRouteException e) {
10
2023-10-18 13:52:07+00:00
24k
trpc-group/trpc-java
trpc-core/src/test/java/com/tencent/trpc/core/cluster/def/DefClusterInvokerTest.java
[ { "identifier": "ConsumerInvokerProxy", "path": "trpc-core/src/main/java/com/tencent/trpc/core/cluster/def/DefClusterInvoker.java", "snippet": "public static class ConsumerInvokerProxy<T> {\n\n private ConsumerInvoker<T> invoker;\n\n private RpcClient client;\n\n ConsumerInvokerProxy(ConsumerIn...
import com.tencent.trpc.core.cluster.def.DefClusterInvoker.ConsumerInvokerProxy; import com.tencent.trpc.core.common.config.BackendConfig; import com.tencent.trpc.core.common.config.ConsumerConfig; import com.tencent.trpc.core.common.config.NamingOptions; import com.tencent.trpc.core.common.config.ProtocolConfig; import com.tencent.trpc.core.exception.TRpcException; import com.tencent.trpc.core.proxy.support.ByteBuddyProxyFactory; import com.tencent.trpc.core.rpc.CloseFuture; import com.tencent.trpc.core.rpc.ConsumerInvoker; import com.tencent.trpc.core.rpc.GenericClient; import com.tencent.trpc.core.rpc.Request; import com.tencent.trpc.core.rpc.Response; import com.tencent.trpc.core.rpc.RpcClient; import com.tencent.trpc.core.rpc.RpcInvocation; import com.tencent.trpc.core.rpc.def.DefRequest; import com.tencent.trpc.core.rpc.def.DefResponse; import com.tencent.trpc.core.selector.ServiceInstance; import com.tencent.trpc.core.utils.FutureUtils; import com.tencent.trpc.core.worker.WorkerPoolManager; import com.tencent.trpc.core.worker.handler.TrpcThreadExceptionHandler; import com.tencent.trpc.core.worker.spi.WorkerPool; import com.tencent.trpc.core.worker.support.thread.ThreadWorkerPool; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner;
19,796
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.core.cluster.def; @RunWith(PowerMockRunner.class) @PrepareForTest({WorkerPoolManager.class}) @PowerMockIgnore({"javax.management.*", "javax.security.*", "javax.ws.*"}) public class DefClusterInvokerTest { private DefClusterInvoker<GenericClient> defClusterInvoker; private ConsumerInvokerProxy<GenericClient> consumerInvokerProxy; /** * Create ConsumerConfig & create DefClusterInvoker & create ConsumerInvokerProxy */ @Before public void setUp() { ConsumerConfig<GenericClient> consumerConfig = getConsumerConfig(); this.defClusterInvoker = new DefClusterInvoker<>(consumerConfig); consumerInvokerProxy = new ConsumerInvokerProxy<>(new ConsumerInvoker<GenericClient>() { @Override public ConsumerConfig<GenericClient> getConfig() { return consumerConfig; } @Override public ProtocolConfig getProtocolConfig() { return null; } @Override public Class<GenericClient> getInterface() { return GenericClient.class; } @Override public CompletionStage<Response> invoke(Request request) { if (Objects.equals(request.getInvocation().getFunc(), "a")) {
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.core.cluster.def; @RunWith(PowerMockRunner.class) @PrepareForTest({WorkerPoolManager.class}) @PowerMockIgnore({"javax.management.*", "javax.security.*", "javax.ws.*"}) public class DefClusterInvokerTest { private DefClusterInvoker<GenericClient> defClusterInvoker; private ConsumerInvokerProxy<GenericClient> consumerInvokerProxy; /** * Create ConsumerConfig & create DefClusterInvoker & create ConsumerInvokerProxy */ @Before public void setUp() { ConsumerConfig<GenericClient> consumerConfig = getConsumerConfig(); this.defClusterInvoker = new DefClusterInvoker<>(consumerConfig); consumerInvokerProxy = new ConsumerInvokerProxy<>(new ConsumerInvoker<GenericClient>() { @Override public ConsumerConfig<GenericClient> getConfig() { return consumerConfig; } @Override public ProtocolConfig getProtocolConfig() { return null; } @Override public Class<GenericClient> getInterface() { return GenericClient.class; } @Override public CompletionStage<Response> invoke(Request request) { if (Objects.equals(request.getInvocation().getFunc(), "a")) {
return FutureUtils.newSuccessFuture(new DefResponse());
17
2023-10-19 10:54:11+00:00
24k
eclipse-jgit/jgit
org.eclipse.jgit.http.apache/src/org/eclipse/jgit/transport/http/apache/HttpClientConnection.java
[ { "identifier": "METHOD_GET", "path": "org.eclipse.jgit/src/org/eclipse/jgit/util/HttpSupport.java", "snippet": "public static final String METHOD_GET = \"GET\"; //$NON-NLS-1$" }, { "identifier": "METHOD_HEAD", "path": "org.eclipse.jgit/src/org/eclipse/jgit/util/HttpSupport.java", "snipp...
import static org.eclipse.jgit.util.HttpSupport.METHOD_GET; import static org.eclipse.jgit.util.HttpSupport.METHOD_HEAD; import static org.eclipse.jgit.util.HttpSupport.METHOD_POST; import static org.eclipse.jgit.util.HttpSupport.METHOD_PUT; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.Proxy; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.SystemDefaultCredentialsProvider; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; import org.eclipse.jgit.annotations.NonNull; import org.eclipse.jgit.transport.http.HttpConnection; import org.eclipse.jgit.transport.http.apache.internal.HttpApacheText; import org.eclipse.jgit.util.HttpSupport; import org.eclipse.jgit.util.TemporaryBuffer; import org.eclipse.jgit.util.TemporaryBuffer.LocalFile;
16,028
* @param buffer * the buffer */ public void setBuffer(TemporaryBuffer buffer) { this.entity = new TemporaryBufferEntity(buffer); } /** * Constructor for HttpClientConnection. * * @param urlStr * url string * @throws MalformedURLException * if url is malformed */ public HttpClientConnection(String urlStr) throws MalformedURLException { this(urlStr, null); } /** * Constructor for HttpClientConnection. * * @param urlStr * url string * @param proxy * proxy * @throws MalformedURLException * if url is malformed */ public HttpClientConnection(String urlStr, Proxy proxy) throws MalformedURLException { this(urlStr, proxy, null); } /** * Constructor for HttpClientConnection. * * @param urlStr * url string * @param proxy * proxy * @param cl * client * @throws MalformedURLException * if url is malformed */ public HttpClientConnection(String urlStr, Proxy proxy, HttpClient cl) throws MalformedURLException { this.client = cl; this.url = new URL(urlStr); this.proxy = proxy; } @Override public int getResponseCode() throws IOException { execute(); return resp.getStatusLine().getStatusCode(); } @Override public URL getURL() { return url; } @Override public String getResponseMessage() throws IOException { execute(); return resp.getStatusLine().getReasonPhrase(); } private void execute() throws IOException, ClientProtocolException { if (resp != null) { return; } if (entity == null) { resp = getClient().execute(req); return; } try { if (req instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) req; eReq.setEntity(entity); } resp = getClient().execute(req); } finally { entity.close(); entity = null; } } @Override public Map<String, List<String>> getHeaderFields() { Map<String, List<String>> ret = new HashMap<>(); for (Header hdr : resp.getAllHeaders()) { List<String> list = ret.get(hdr.getName()); if (list == null) { list = new LinkedList<>(); ret.put(hdr.getName(), list); } for (HeaderElement hdrElem : hdr.getElements()) { list.add(hdrElem.toString()); } } return ret; } @Override public void setRequestProperty(String name, String value) { req.addHeader(name, value); } @Override public void setRequestMethod(String method) throws ProtocolException { this.method = method; if (METHOD_GET.equalsIgnoreCase(method)) { req = new HttpGet(url.toString()); } else if (METHOD_HEAD.equalsIgnoreCase(method)) { req = new HttpHead(url.toString());
/* * Copyright (C) 2013, 2020 Christian Halstrick <christian.halstrick@sap.com> and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.transport.http.apache; /** * A {@link org.eclipse.jgit.transport.http.HttpConnection} which uses * {@link org.apache.http.client.HttpClient} * * @since 3.3 */ public class HttpClientConnection implements HttpConnection { HttpClient client; URL url; HttpUriRequest req; HttpResponse resp = null; String method = "GET"; //$NON-NLS-1$ private TemporaryBufferEntity entity; private boolean isUsingProxy = false; private Proxy proxy; private Integer timeout = null; private Integer readTimeout; private Boolean followRedirects; private HostnameVerifier hostnameverifier; private SSLContext ctx; private SSLConnectionSocketFactory socketFactory; private boolean usePooling = true; private HttpClient getClient() { if (client == null) { HttpClientBuilder clientBuilder = HttpClients.custom(); RequestConfig.Builder configBuilder = RequestConfig.custom(); if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) { isUsingProxy = true; InetSocketAddress adr = (InetSocketAddress) proxy.address(); clientBuilder.setProxy( new HttpHost(adr.getHostName(), adr.getPort())); } if (timeout != null) { configBuilder.setConnectTimeout(timeout.intValue()); } if (readTimeout != null) { configBuilder.setSocketTimeout(readTimeout.intValue()); } if (followRedirects != null) { configBuilder .setRedirectsEnabled(followRedirects.booleanValue()); } boolean pooled = true; SSLConnectionSocketFactory sslConnectionFactory; if (socketFactory != null) { pooled = usePooling; sslConnectionFactory = socketFactory; } else { // Legacy implementation. pooled = (hostnameverifier == null); sslConnectionFactory = getSSLSocketFactory(); } clientBuilder.setSSLSocketFactory(sslConnectionFactory); if (!pooled) { Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory> create() .register("https", sslConnectionFactory) .register("http", PlainConnectionSocketFactory.INSTANCE) .build(); clientBuilder.setConnectionManager( new BasicHttpClientConnectionManager(registry)); } clientBuilder.setDefaultRequestConfig(configBuilder.build()); clientBuilder.setDefaultCredentialsProvider( new SystemDefaultCredentialsProvider()); client = clientBuilder.build(); } return client; } void setSSLSocketFactory(@NonNull SSLConnectionSocketFactory factory, boolean isDefault) { socketFactory = factory; usePooling = isDefault; } private SSLConnectionSocketFactory getSSLSocketFactory() { HostnameVerifier verifier = hostnameverifier; SSLContext context; if (verifier == null) { // Use defaults context = SSLContexts.createSystemDefault(); verifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); } else { // Using a custom verifier. Attention: configure() must have been // called already, otherwise one gets a "context not initialized" // exception. In JGit this branch is reached only when hostname // verification is switched off, and JGit _does_ call configure() // before we get here. context = getSSLContext(); } return new SSLConnectionSocketFactory(context, verifier) { @Override protected void prepareSocket(SSLSocket socket) throws IOException { super.prepareSocket(socket); HttpSupport.configureTLS(socket); } }; } private SSLContext getSSLContext() { if (ctx == null) { try { ctx = SSLContext.getInstance("TLS"); //$NON-NLS-1$ } catch (NoSuchAlgorithmException e) { throw new IllegalStateException( HttpApacheText.get().unexpectedSSLContextException, e); } } return ctx; } /** * Sets the buffer from which to take the request body * * @param buffer * the buffer */ public void setBuffer(TemporaryBuffer buffer) { this.entity = new TemporaryBufferEntity(buffer); } /** * Constructor for HttpClientConnection. * * @param urlStr * url string * @throws MalformedURLException * if url is malformed */ public HttpClientConnection(String urlStr) throws MalformedURLException { this(urlStr, null); } /** * Constructor for HttpClientConnection. * * @param urlStr * url string * @param proxy * proxy * @throws MalformedURLException * if url is malformed */ public HttpClientConnection(String urlStr, Proxy proxy) throws MalformedURLException { this(urlStr, proxy, null); } /** * Constructor for HttpClientConnection. * * @param urlStr * url string * @param proxy * proxy * @param cl * client * @throws MalformedURLException * if url is malformed */ public HttpClientConnection(String urlStr, Proxy proxy, HttpClient cl) throws MalformedURLException { this.client = cl; this.url = new URL(urlStr); this.proxy = proxy; } @Override public int getResponseCode() throws IOException { execute(); return resp.getStatusLine().getStatusCode(); } @Override public URL getURL() { return url; } @Override public String getResponseMessage() throws IOException { execute(); return resp.getStatusLine().getReasonPhrase(); } private void execute() throws IOException, ClientProtocolException { if (resp != null) { return; } if (entity == null) { resp = getClient().execute(req); return; } try { if (req instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) req; eReq.setEntity(entity); } resp = getClient().execute(req); } finally { entity.close(); entity = null; } } @Override public Map<String, List<String>> getHeaderFields() { Map<String, List<String>> ret = new HashMap<>(); for (Header hdr : resp.getAllHeaders()) { List<String> list = ret.get(hdr.getName()); if (list == null) { list = new LinkedList<>(); ret.put(hdr.getName(), list); } for (HeaderElement hdrElem : hdr.getElements()) { list.add(hdrElem.toString()); } } return ret; } @Override public void setRequestProperty(String name, String value) { req.addHeader(name, value); } @Override public void setRequestMethod(String method) throws ProtocolException { this.method = method; if (METHOD_GET.equalsIgnoreCase(method)) { req = new HttpGet(url.toString()); } else if (METHOD_HEAD.equalsIgnoreCase(method)) { req = new HttpHead(url.toString());
} else if (METHOD_PUT.equalsIgnoreCase(method)) {
3
2023-10-20 15:09:17+00:00
24k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/ActivityRecyclerListFragment.java
[ { "identifier": "IfwUtil", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/IfwUtil.java", "snippet": "public class IfwUtil {\n private static final String TAG = \"IfwUtil\";\n private static final String SYSTEM_PROPERTY_EFS_ENABLED = \"persist.security.efs.enabled\";\n\n public static...
import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SwitchCompat; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.IfwUtil; import cn.wq.myandroidtoolspro.helper.Utils; import cn.wq.myandroidtoolspro.model.ComponentEntry; import cn.wq.myandroidtoolspro.model.ComponentModel; import cn.wq.myandroidtoolspro.recyclerview.adapter.AbstractComponentAdapter; import cn.wq.myandroidtoolspro.recyclerview.toolbar.MultiSectionWithToolbarRecyclerFragment; import cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectableViewHolder; import cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectionUtils;
21,429
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ActivityRecyclerListFragment extends MultiSectionWithToolbarRecyclerFragment{ private ActivityAdapter mAdapter; private String packageName; private String launchActivityName; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } public static ActivityRecyclerListFragment newInstance(Bundle bundle) { ActivityRecyclerListFragment f = new ActivityRecyclerListFragment(); f.setArguments(bundle); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle data = getArguments(); packageName = data.getString("packageName"); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setToolbarLogo(packageName); launchActivityName=getLaunchActivityName(); } private String getLaunchActivityName() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setPackage(packageName); ResolveInfo rInfo=mContext.getPackageManager().resolveActivity(intent, 0); if (rInfo != null) { return rInfo.activityInfo.name; } return null; } @Override protected AbstractComponentAdapter<ComponentEntry> generateAdapter() { mAdapter = new ActivityAdapter(mContext); return mAdapter; } @Override protected void reloadData(Integer... checkedItemPositions) { mAdapter.setData(loadData()); } @Override protected boolean isSupportIfw() { return true; } @Override protected boolean disableByIfw(Integer... positions) { return IfwUtil.saveComponentIfw(mContext, packageName, mIfwEntry, mAdapter, IfwUtil.COMPONENT_FLAG_ACTIVITY, useParentIfw, positions); } @Override protected List<ComponentEntry> loadData() { boolean isIfw = Utils.isPmByIfw(mContext); if (isIfw) { loadDataForIfw(packageName); } List<ComponentEntry> result = new ArrayList<>(); PackageManager pm = mContext.getPackageManager();
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ActivityRecyclerListFragment extends MultiSectionWithToolbarRecyclerFragment{ private ActivityAdapter mAdapter; private String packageName; private String launchActivityName; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } public static ActivityRecyclerListFragment newInstance(Bundle bundle) { ActivityRecyclerListFragment f = new ActivityRecyclerListFragment(); f.setArguments(bundle); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle data = getArguments(); packageName = data.getString("packageName"); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setToolbarLogo(packageName); launchActivityName=getLaunchActivityName(); } private String getLaunchActivityName() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setPackage(packageName); ResolveInfo rInfo=mContext.getPackageManager().resolveActivity(intent, 0); if (rInfo != null) { return rInfo.activityInfo.name; } return null; } @Override protected AbstractComponentAdapter<ComponentEntry> generateAdapter() { mAdapter = new ActivityAdapter(mContext); return mAdapter; } @Override protected void reloadData(Integer... checkedItemPositions) { mAdapter.setData(loadData()); } @Override protected boolean isSupportIfw() { return true; } @Override protected boolean disableByIfw(Integer... positions) { return IfwUtil.saveComponentIfw(mContext, packageName, mIfwEntry, mAdapter, IfwUtil.COMPONENT_FLAG_ACTIVITY, useParentIfw, positions); } @Override protected List<ComponentEntry> loadData() { boolean isIfw = Utils.isPmByIfw(mContext); if (isIfw) { loadDataForIfw(packageName); } List<ComponentEntry> result = new ArrayList<>(); PackageManager pm = mContext.getPackageManager();
List<ComponentModel> models = Utils.getComponentModels(mContext, packageName, 2);
3
2023-10-18 14:32:49+00:00
24k
A1anSong/jd_unidbg
unidbg-api/src/main/java/com/github/unidbg/arm/AbstractARMDebugger.java
[ { "identifier": "AssemblyCodeDumper", "path": "unidbg-api/src/main/java/com/github/unidbg/AssemblyCodeDumper.java", "snippet": "public class AssemblyCodeDumper implements CodeHook, TraceHook {\n\n private final Emulator<?> emulator;\n\n public AssemblyCodeDumper(Emulator<?> emulator, long begin, l...
import capstone.api.Instruction; import capstone.api.RegsAccess; import com.github.unidbg.AssemblyCodeDumper; import com.github.unidbg.Emulator; import com.github.unidbg.Family; import com.github.unidbg.Module; import com.github.unidbg.Symbol; import com.github.unidbg.TraceMemoryHook; import com.github.unidbg.Utils; import com.github.unidbg.arm.backend.Backend; import com.github.unidbg.arm.backend.BlockHook; import com.github.unidbg.arm.backend.ReadHook; import com.github.unidbg.arm.backend.UnHook; import com.github.unidbg.arm.backend.WriteHook; import com.github.unidbg.debugger.BreakPoint; import com.github.unidbg.debugger.BreakPointCallback; import com.github.unidbg.debugger.DebugListener; import com.github.unidbg.debugger.DebugRunnable; import com.github.unidbg.debugger.Debugger; import com.github.unidbg.debugger.FunctionCallListener; import com.github.unidbg.memory.MemRegion; import com.github.unidbg.memory.Memory; import com.github.unidbg.memory.MemoryMap; import com.github.unidbg.pointer.UnidbgPointer; import com.github.unidbg.thread.Task; import com.github.unidbg.unix.struct.StdString; import com.github.unidbg.unwind.Unwinder; import com.github.unidbg.utils.Inspector; import com.github.zhkl0228.demumble.DemanglerFactory; import com.github.zhkl0228.demumble.GccDemangler; import com.sun.jna.Pointer; import keystone.Keystone; import keystone.KeystoneEncoded; import keystone.exceptions.AssembleFailedKeystoneException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import unicorn.Arm64Const; import unicorn.ArmConst; import unicorn.UnicornConst; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern;
19,783
private TraceMemoryHook traceRead; private PrintStream traceReadRedirectStream; private TraceMemoryHook traceWrite; private PrintStream traceWriteRedirectStream; final boolean handleCommon(Backend backend, String line, long address, int size, long nextAddress, DebugRunnable<?> runnable) throws Exception { if ("exit".equals(line) || "quit".equals(line) || "q".equals(line)) { // continue return true; } if ("gc".equals(line)) { System.out.println("Run System.gc();"); System.gc(); return false; } if ("threads".equals(line)) { for (Task task : emulator.getThreadDispatcher().getTaskList()) { System.out.println(task.getId() + ": " + task); } return false; } if (runnable == null || callbackRunning) { if ("c".equals(line)) { // continue return true; } } else { if ("c".equals(line)) { try { callbackRunning = true; runnable.runWithArgs(null); cancelTrace(); return false; } finally { callbackRunning = false; } } } if ("n".equals(line)) { if (nextAddress == 0) { System.out.println("Next address failed."); return false; } else { addBreakPoint(nextAddress).setTemporary(true); return true; } } if (line.startsWith("st")) { // search stack int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchStack(data); return false; } } } if (line.startsWith("shw")) { // search writable heap int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchHeap(data, UnicornConst.UC_PROT_WRITE); return false; } } } if (line.startsWith("shr")) { // search readable heap int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchHeap(data, UnicornConst.UC_PROT_READ); return false; } } } if (line.startsWith("shx")) { // search executable heap int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchHeap(data, UnicornConst.UC_PROT_EXEC); return false; } } } if (emulator.getFamily() == Family.iOS && !emulator.isRunning() && line.startsWith("dump ")) { String className = line.substring(5).trim(); if (className.length() > 0) { dumpClass(className); return false; } } if (emulator.getFamily() == Family.iOS && !emulator.isRunning() && line.startsWith("gpb ")) { String className = line.substring(4).trim(); if (className.length() > 0) { dumpGPBProtobufMsg(className); return false; } } if (emulator.getFamily() == Family.iOS && !emulator.isRunning() && line.startsWith("search ")) { String keywords = line.substring(7).trim(); if (keywords.length() > 0) { searchClass(keywords); return false; } } final int traceSize = 0x10000; if (line.startsWith("traceRead")) { // start trace memory read Pattern pattern = Pattern.compile("traceRead\\s+(\\w+)\\s+(\\w+)"); Matcher matcher = pattern.matcher(line); if (traceRead != null) { traceRead.detach(); } traceRead = new TraceMemoryHook(true); long begin, end; if (matcher.find()) {
package com.github.unidbg.arm; public abstract class AbstractARMDebugger implements Debugger { private static final Log log = LogFactory.getLog(AbstractARMDebugger.class); private final Map<Long, BreakPoint> breakMap = new LinkedHashMap<>(); protected final Emulator<?> emulator; protected AbstractARMDebugger(Emulator<?> emulator) { this.emulator = emulator; } private final List<UnHook> unHookList = new ArrayList<>(); @Override public void onAttach(UnHook unHook) { unHookList.add(unHook); } @Override public void detach() { for (Iterator<UnHook> iterator = unHookList.iterator(); iterator.hasNext(); ) { iterator.next().unhook(); iterator.remove(); } } @Override public final BreakPoint addBreakPoint(Module module, String symbol) { Symbol sym = module.findSymbolByName(symbol, false); if (sym == null) { throw new IllegalStateException("find symbol failed: " + symbol); } return addBreakPoint(module, sym.getValue()); } @Override public final BreakPoint addBreakPoint(Module module, String symbol, BreakPointCallback callback) { Symbol sym = module.findSymbolByName(symbol, false); if (sym == null) { throw new IllegalStateException("find symbol failed: " + symbol); } return addBreakPoint(module, sym.getValue(), callback); } @Override public final BreakPoint addBreakPoint(Module module, long offset) { long address = module == null ? offset : module.base + offset; return addBreakPoint(address); } @Override public final BreakPoint addBreakPoint(Module module, long offset, BreakPointCallback callback) { long address = module == null ? offset : module.base + offset; return addBreakPoint(address, callback); } @Override public BreakPoint addBreakPoint(long address) { return addBreakPoint(address, null); } @Override public BreakPoint addBreakPoint(long address, BreakPointCallback callback) { boolean thumb = (address & 1) != 0; address &= (~1); if (log.isDebugEnabled()) { log.debug("addBreakPoint address=0x" + Long.toHexString(address)); } BreakPoint breakPoint = emulator.getBackend().addBreakPoint(address, callback, thumb); breakMap.put(address, breakPoint); return breakPoint; } @Override public void traceFunctionCall(FunctionCallListener listener) { traceFunctionCall(null, listener); } @Override public void traceFunctionCall(Module module, FunctionCallListener listener) { throw new UnsupportedOperationException(); } protected abstract Keystone createKeystone(boolean isThumb); public final boolean removeBreakPoint(long address) { address &= (~1); if (breakMap.containsKey(address)) { breakMap.remove(address); return emulator.getBackend().removeBreakPoint(address); } else { return false; } } private DebugListener listener; @Override public void setDebugListener(DebugListener listener) { this.listener = listener; } @Override public void onBreak(Backend backend, long address, int size, Object user) { BreakPoint breakPoint = breakMap.get(address); if (breakPoint != null && breakPoint.isTemporary()) { removeBreakPoint(address); } BreakPointCallback callback; if (breakPoint != null && (callback = breakPoint.getCallback()) != null && callback.onHit(emulator, address)) { return; } try { if (listener == null || listener.canDebug(emulator, new CodeHistory(address, size, ARM.isThumb(backend)))) { cancelTrace(); debugging = true; loop(emulator, address, size, null); } } catch (Exception e) { log.warn("process loop failed", e); } finally { debugging = false; } } private void cancelTrace() { if (traceHook != null) { traceHook.detach(); traceHook = null; } if (traceHookRedirectStream != null) { com.alibaba.fastjson.util.IOUtils.close(traceHookRedirectStream); traceHookRedirectStream = null; } if (traceRead != null) { traceRead.detach(); traceRead = null; } if (traceReadRedirectStream != null) { com.alibaba.fastjson.util.IOUtils.close(traceReadRedirectStream); traceReadRedirectStream = null; } if (traceWrite != null) { traceWrite.detach(); traceWrite = null; } if (traceWriteRedirectStream != null) { com.alibaba.fastjson.util.IOUtils.close(traceWriteRedirectStream); traceWriteRedirectStream = null; } } private boolean debugging; @Override public boolean isDebugging() { return debugging; } private boolean blockHooked; private boolean breakNextBlock; @Override public void hookBlock(Backend backend, long address, int size, Object user) { if (breakNextBlock) { onBreak(backend, address, size, user); breakNextBlock = false; } } @Override public final void hook(Backend backend, long address, int size, Object user) { Emulator<?> emulator = (Emulator<?>) user; try { if (breakMnemonic != null) { CodeHistory history = new CodeHistory(address, size, ARM.isThumb(backend)); Instruction[] instructions = history.disassemble(emulator); if (instructions.length > 0 && breakMnemonic.equals(instructions[0].getMnemonic())) { breakMnemonic = null; backend.setFastDebug(true); cancelTrace(); debugging = true; loop(emulator, address, size, null); } } } catch (Exception e) { log.warn("process hook failed", e); } finally { debugging = false; } } @Override public void debug() { Backend backend = emulator.getBackend(); long address; if (emulator.is32Bit()) { address = backend.reg_read(ArmConst.UC_ARM_REG_PC).intValue() & 0xffffffffL; } else { address = backend.reg_read(Arm64Const.UC_ARM64_REG_PC).longValue(); } try { cancelTrace(); debugging = true; loop(emulator, address, 4, null); } catch (Exception e) { log.warn("debug failed", e); } finally { debugging = false; } } protected final void setSingleStep(int singleStep) { emulator.getBackend().setSingleStep(singleStep); } private String breakMnemonic; protected abstract void loop(Emulator<?> emulator, long address, int size, DebugRunnable<?> runnable) throws Exception; protected boolean callbackRunning; @Override public <T> T run(DebugRunnable<T> runnable) throws Exception { if (runnable == null) { throw new NullPointerException(); } T ret; try { callbackRunning = true; ret = runnable.runWithArgs(null); } finally { callbackRunning = false; } try { cancelTrace(); debugging = true; loop(emulator, -1, 0, runnable); } finally { debugging = false; } return ret; } protected enum StringType { nullTerminated, std_string } final void dumpMemory(Pointer pointer, int _length, String label, StringType stringType) { if (stringType != null) { if (stringType == StringType.nullTerminated) { long addr = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean foundTerminated = false; while (true) { byte[] data = pointer.getByteArray(addr, 0x10); int length = data.length; for (int i = 0; i < data.length; i++) { if (data[i] == 0) { length = i; break; } } baos.write(data, 0, length); addr += length; if (length < data.length) { // reach zero foundTerminated = true; break; } if (baos.size() > 0x10000) { // 64k break; } } if (foundTerminated) { Inspector.inspect(baos.toByteArray(), baos.size() >= 1024 ? (label + ", hex=" + Hex.encodeHexString(baos.toByteArray())) : (label + ", str=" + new String(baos.toByteArray(), StandardCharsets.UTF_8))); } else { Inspector.inspect(pointer.getByteArray(0, _length), label + ", find NULL-terminated failed"); } } else if (stringType == StringType.std_string) { StdString string = StdString.createStdString(emulator, pointer); long size = string.getDataSize(); byte[] data = string.getData(emulator); Inspector.inspect(data, size >= 1024 ? (label + ", hex=" + Hex.encodeHexString(data) + ", std=" + new String(data, StandardCharsets.UTF_8)) : label); } else { throw new UnsupportedOperationException("stringType=" + stringType); } } else { StringBuilder sb = new StringBuilder(label); byte[] data = pointer.getByteArray(0, _length); if (_length == 4) { ByteBuffer buffer = ByteBuffer.wrap(data); buffer.order(ByteOrder.LITTLE_ENDIAN); int value = buffer.getInt(); sb.append(", value=0x").append(Integer.toHexString(value)); } else if (_length == 8) { ByteBuffer buffer = ByteBuffer.wrap(data); buffer.order(ByteOrder.LITTLE_ENDIAN); long value = buffer.getLong(); sb.append(", value=0x").append(Long.toHexString(value)); } else if (_length == 16) { byte[] tmp = Arrays.copyOf(data, 16); for (int i = 0; i < 8; i++) { byte b = tmp[i]; tmp[i] = tmp[15 - i]; tmp[15 - i] = b; } byte[] bytes = new byte[tmp.length + 1]; System.arraycopy(tmp, 0, bytes, 1, tmp.length); // makePositive sb.append(", value=0x").append(new BigInteger(bytes).toString(16)); } if (data.length >= 1024) { sb.append(", hex=").append(Hex.encodeHexString(data)); } Inspector.inspect(data, sb.toString()); } } private void searchStack(byte[] data) { if (data == null || data.length < 1) { System.err.println("search stack failed as empty data"); return; } UnidbgPointer stack = emulator.getContext().getStackPointer(); Backend backend = emulator.getBackend(); Collection<Pointer> pointers = searchMemory(backend, stack.peer, emulator.getMemory().getStackBase(), data); System.out.println("Search stack from " + stack + " matches " + pointers.size() + " count"); for (Pointer pointer : pointers) { System.out.println("Stack matches: " + pointer); } } private void searchHeap(byte[] data, int prot) { if (data == null || data.length < 1) { System.err.println("search heap failed as empty data"); return; } List<Pointer> list = new ArrayList<>(); Backend backend = emulator.getBackend(); for (MemoryMap map : emulator.getMemory().getMemoryMap()) { if ((map.prot & prot) != 0) { Collection<Pointer> pointers = searchMemory(backend, map.base, map.base + map.size, data); list.addAll(pointers); } } System.out.println("Search heap matches " + list.size() + " count"); for (Pointer pointer : list) { System.out.println("Heap matches: " + pointer); } } private Collection<Pointer> searchMemory(Backend backend, long start, long end, byte[] data) { List<Pointer> pointers = new ArrayList<>(); for (long i = start, m = end - data.length; i < m; i++) { byte[] oneByte = backend.mem_read(i, 1); if (data[0] != oneByte[0]) { continue; } if (Arrays.equals(data, backend.mem_read(i, data.length))) { pointers.add(UnidbgPointer.pointer(emulator, i)); i += (data.length - 1); } } return pointers; } private AssemblyCodeDumper traceHook; private PrintStream traceHookRedirectStream; private TraceMemoryHook traceRead; private PrintStream traceReadRedirectStream; private TraceMemoryHook traceWrite; private PrintStream traceWriteRedirectStream; final boolean handleCommon(Backend backend, String line, long address, int size, long nextAddress, DebugRunnable<?> runnable) throws Exception { if ("exit".equals(line) || "quit".equals(line) || "q".equals(line)) { // continue return true; } if ("gc".equals(line)) { System.out.println("Run System.gc();"); System.gc(); return false; } if ("threads".equals(line)) { for (Task task : emulator.getThreadDispatcher().getTaskList()) { System.out.println(task.getId() + ": " + task); } return false; } if (runnable == null || callbackRunning) { if ("c".equals(line)) { // continue return true; } } else { if ("c".equals(line)) { try { callbackRunning = true; runnable.runWithArgs(null); cancelTrace(); return false; } finally { callbackRunning = false; } } } if ("n".equals(line)) { if (nextAddress == 0) { System.out.println("Next address failed."); return false; } else { addBreakPoint(nextAddress).setTemporary(true); return true; } } if (line.startsWith("st")) { // search stack int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchStack(data); return false; } } } if (line.startsWith("shw")) { // search writable heap int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchHeap(data, UnicornConst.UC_PROT_WRITE); return false; } } } if (line.startsWith("shr")) { // search readable heap int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchHeap(data, UnicornConst.UC_PROT_READ); return false; } } } if (line.startsWith("shx")) { // search executable heap int index = line.indexOf(' '); if (index != -1) { String hex = line.substring(index + 1).trim(); byte[] data = Hex.decodeHex(hex.toCharArray()); if (data.length > 0) { searchHeap(data, UnicornConst.UC_PROT_EXEC); return false; } } } if (emulator.getFamily() == Family.iOS && !emulator.isRunning() && line.startsWith("dump ")) { String className = line.substring(5).trim(); if (className.length() > 0) { dumpClass(className); return false; } } if (emulator.getFamily() == Family.iOS && !emulator.isRunning() && line.startsWith("gpb ")) { String className = line.substring(4).trim(); if (className.length() > 0) { dumpGPBProtobufMsg(className); return false; } } if (emulator.getFamily() == Family.iOS && !emulator.isRunning() && line.startsWith("search ")) { String keywords = line.substring(7).trim(); if (keywords.length() > 0) { searchClass(keywords); return false; } } final int traceSize = 0x10000; if (line.startsWith("traceRead")) { // start trace memory read Pattern pattern = Pattern.compile("traceRead\\s+(\\w+)\\s+(\\w+)"); Matcher matcher = pattern.matcher(line); if (traceRead != null) { traceRead.detach(); } traceRead = new TraceMemoryHook(true); long begin, end; if (matcher.find()) {
begin = Utils.parseNumber(matcher.group(1));
6
2023-10-17 06:13:28+00:00
24k
robaho/httpserver
src/test/java/jdk/test/lib/Utils.java
[ { "identifier": "assertTrue", "path": "src/test/java/jdk/test/lib/Asserts.java", "snippet": "public static void assertTrue(boolean value) {\n assertTrue(value, null);\n}" }, { "identifier": "ProcessTools", "path": "src/test/java/jdk/test/lib/process/ProcessTools.java", "snippet": "pub...
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.ServerSocket; import java.net.URL; import java.net.URLClassLoader; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.AclEntry; import java.nio.file.attribute.AclEntryType; import java.nio.file.attribute.AclFileAttributeView; import java.nio.file.attribute.FileAttribute; import java.nio.channels.SocketChannel; import java.nio.file.attribute.PosixFilePermissions; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HexFormat; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Set; import java.util.function.BooleanSupplier; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static jdk.test.lib.Asserts.assertTrue; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.process.OutputAnalyzer;
16,101
* @return The full command line for the ProcessBuilder. */ public static String getCommandLine(ProcessBuilder pb) { StringBuilder cmd = new StringBuilder(); for (String s : pb.command()) { cmd.append(s).append(" "); } return cmd.toString(); } /** * Returns the socket address of an endpoint that refuses connections. The * endpoint is an InetSocketAddress where the address is the loopback address * and the port is a system port (1-1023 range). * This method is a better choice than getFreePort for tests that need * an endpoint that refuses connections. */ public static InetSocketAddress refusingEndpoint() { InetAddress lb = InetAddress.getLoopbackAddress(); int port = 1; while (port < 1024) { InetSocketAddress sa = new InetSocketAddress(lb, port); try { SocketChannel.open(sa).close(); } catch (IOException ioe) { return sa; } port++; } throw new RuntimeException("Unable to find system port that is refusing connections"); } /** * Returns local addresses with symbolic and numeric scopes */ public static List<InetAddress> getAddressesWithSymbolicAndNumericScopes() { List<InetAddress> result = new LinkedList<>(); try { NetworkConfiguration conf = NetworkConfiguration.probe(); conf.ip4Addresses().forEach(result::add); // Java reports link local addresses with symbolic scope, // but on Windows java.net.NetworkInterface generates its own scope names // which are incompatible with native Windows routines. // So on Windows test only addresses with numeric scope. // On other platforms test both symbolic and numeric scopes. conf.ip6Addresses() // test only IPv6 loopback and link-local addresses (JDK-8224775) .filter(addr -> addr.isLinkLocalAddress() || addr.isLoopbackAddress()) .forEach(addr6 -> { try { result.add(Inet6Address.getByAddress(null, addr6.getAddress(), addr6.getScopeId())); } catch (UnknownHostException e) { // cannot happen! throw new RuntimeException("Unexpected", e); } if (!Platform.isWindows()) { result.add(addr6); } }); } catch (IOException e) { // cannot happen! throw new RuntimeException("Unexpected", e); } return result; } /** * Returns the free port on the loopback address. * * @return The port number * @throws IOException if an I/O error occurs when opening the socket */ public static int getFreePort() throws IOException { try (ServerSocket serverSocket = new ServerSocket(0, 5, InetAddress.getLoopbackAddress());) { return serverSocket.getLocalPort(); } } /** * Returns the free unreserved port on the local host. * * @param reservedPorts reserved ports * @return The port number or -1 if failed to find a free port */ public static int findUnreservedFreePort(int... reservedPorts) { int numTries = 0; while (numTries++ < MAX_SOCKET_TRIES) { int port = -1; try { port = getFreePort(); } catch (IOException e) { e.printStackTrace(); } if (port > 0 && !isReserved(port, reservedPorts)) { return port; } } return -1; } private static boolean isReserved(int port, int[] reservedPorts) { for (int p : reservedPorts) { if (p == port) { return true; } } return false; } /** * Returns the name of the local host. * * @return The host name * @throws UnknownHostException if IP address of a host could not be determined */ public static String getHostname() throws UnknownHostException { InetAddress inetAddress = InetAddress.getLocalHost(); String hostName = inetAddress.getHostName();
/* * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.test.lib; /** * Common library for various test helper functions. */ public final class Utils { /** * Returns the value of 'test.class.path' system property. */ public static final String TEST_CLASS_PATH = System.getProperty("test.class.path", "."); /** * Returns the sequence used by operating system to separate lines. */ public static final String NEW_LINE = System.getProperty("line.separator"); /** * Returns the value of 'test.vm.opts' system property. */ public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim(); /** * Returns the value of 'test.java.opts' system property. */ public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim(); /** * Returns the value of 'test.src' system property. */ public static final String TEST_SRC = System.getProperty("test.src", "").trim(); /** * Returns the value of 'test.root' system property. */ public static final String TEST_ROOT = System.getProperty("test.root", "").trim(); /* * Returns the value of 'test.jdk' system property */ public static final String TEST_JDK = System.getProperty("test.jdk"); /* * Returns the value of 'compile.jdk' system property */ public static final String COMPILE_JDK = System.getProperty("compile.jdk", TEST_JDK); /** * Returns the value of 'test.classes' system property */ public static final String TEST_CLASSES = System.getProperty("test.classes", "."); /** * Returns the value of 'test.name' system property */ public static final String TEST_NAME = System.getProperty("test.name", "."); /** * Returns the value of 'test.nativepath' system property */ public static final String TEST_NATIVE_PATH = System.getProperty("test.nativepath", "."); /** * Defines property name for seed value. */ public static final String SEED_PROPERTY_NAME = "jdk.test.lib.random.seed"; /** * Returns the value of 'file.separator' system property */ public static final String FILE_SEPARATOR = System.getProperty("file.separator"); /** * Random generator with predefined seed. */ private static volatile Random RANDOM_GENERATOR; /** * Maximum number of attempts to get free socket */ private static final int MAX_SOCKET_TRIES = 10; /** * Contains the seed value used for {@link java.util.Random} creation. */ public static final long SEED; static { var seed = Long.getLong(SEED_PROPERTY_NAME); if (seed != null) { // use explicitly set seed SEED = seed; } else { var v = Runtime.version(); // promotable builds have build number, and it's greater than 0 if (v.build().orElse(0) > 0) { // promotable build -> use 1st 8 bytes of md5($version) try { var md = MessageDigest.getInstance("MD5"); var bytes = v.toString() .getBytes(StandardCharsets.UTF_8); bytes = md.digest(bytes); SEED = ByteBuffer.wrap(bytes).getLong(); } catch (NoSuchAlgorithmException e) { throw new Error(e); } } else { // "personal" build -> use random seed SEED = new Random().nextLong(); } } } /** * Returns the value of 'test.timeout.factor' system property * converted to {@code double}. */ public static final double TIMEOUT_FACTOR; static { String toFactor = System.getProperty("test.timeout.factor", "1.0"); TIMEOUT_FACTOR = Double.parseDouble(toFactor); } /** * Returns the value of JTREG default test timeout in milliseconds * converted to {@code long}. */ public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120); private Utils() { // Private constructor to prevent class instantiation } /** * Returns the list of VM options with -J prefix. * * @return The list of VM options with -J prefix */ public static List<String> getForwardVmOptions() { String[] opts = safeSplitString(VM_OPTIONS); for (int i = 0; i < opts.length; i++) { opts[i] = "-J" + opts[i]; } return Arrays.asList(opts); } /** * Returns the default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts. * @return An array of options, or an empty array if no options. */ public static String[] getTestJavaOpts() { List<String> opts = new ArrayList<String>(); Collections.addAll(opts, safeSplitString(VM_OPTIONS)); Collections.addAll(opts, safeSplitString(JAVA_OPTIONS)); return opts.toArray(new String[0]); } /** * Combines given arguments with default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts * @return The combination of JTReg test java options and user args. */ public static String[] prependTestJavaOpts(String... userArgs) { List<String> opts = new ArrayList<String>(); Collections.addAll(opts, getTestJavaOpts()); Collections.addAll(opts, userArgs); return opts.toArray(new String[0]); } /** * Combines given arguments with default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts * @return The combination of JTReg test java options and user args. */ public static String[] appendTestJavaOpts(String... userArgs) { List<String> opts = new ArrayList<String>(); Collections.addAll(opts, userArgs); Collections.addAll(opts, getTestJavaOpts()); return opts.toArray(new String[0]); } /** * Combines given arguments with default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts * @return The combination of JTReg test java options and user args. */ public static String[] addTestJavaOpts(String... userArgs) { return prependTestJavaOpts(userArgs); } private static final Pattern useGcPattern = Pattern.compile( "(?:\\-XX\\:[\\+\\-]Use.+GC)"); /** * Removes any options specifying which GC to use, for example "-XX:+UseG1GC". * Removes any options matching: -XX:(+/-)Use*GC * Used when a test need to set its own GC version. Then any * GC specified by the framework must first be removed. * @return A copy of given opts with all GC options removed. */ public static List<String> removeGcOpts(List<String> opts) { List<String> optsWithoutGC = new ArrayList<String>(); for (String opt : opts) { if (useGcPattern.matcher(opt).matches()) { System.out.println("removeGcOpts: removed " + opt); } else { optsWithoutGC.add(opt); } } return optsWithoutGC; } /** * Returns the default JTReg arguments for a jvm running a test without * options that matches regular expressions in {@code filters}. * This is the combination of JTReg arguments test.vm.opts and test.java.opts. * @param filters Regular expressions used to filter out options. * @return An array of options, or an empty array if no options. */ public static String[] getFilteredTestJavaOpts(String... filters) { String options[] = getTestJavaOpts(); if (filters.length == 0) { return options; } List<String> filteredOptions = new ArrayList<String>(options.length); Pattern patterns[] = new Pattern[filters.length]; for (int i = 0; i < filters.length; i++) { patterns[i] = Pattern.compile(filters[i]); } for (String option : options) { boolean matched = false; for (int i = 0; i < patterns.length && !matched; i++) { Matcher matcher = patterns[i].matcher(option); matched = matcher.find(); } if (!matched) { filteredOptions.add(option); } } return filteredOptions.toArray(new String[filteredOptions.size()]); } /** * Splits a string by white space. * Works like String.split(), but returns an empty array * if the string is null or empty. */ private static String[] safeSplitString(String s) { if (s == null || s.trim().isEmpty()) { return new String[] {}; } return s.trim().split("\\s+"); } /** * @return The full command line for the ProcessBuilder. */ public static String getCommandLine(ProcessBuilder pb) { StringBuilder cmd = new StringBuilder(); for (String s : pb.command()) { cmd.append(s).append(" "); } return cmd.toString(); } /** * Returns the socket address of an endpoint that refuses connections. The * endpoint is an InetSocketAddress where the address is the loopback address * and the port is a system port (1-1023 range). * This method is a better choice than getFreePort for tests that need * an endpoint that refuses connections. */ public static InetSocketAddress refusingEndpoint() { InetAddress lb = InetAddress.getLoopbackAddress(); int port = 1; while (port < 1024) { InetSocketAddress sa = new InetSocketAddress(lb, port); try { SocketChannel.open(sa).close(); } catch (IOException ioe) { return sa; } port++; } throw new RuntimeException("Unable to find system port that is refusing connections"); } /** * Returns local addresses with symbolic and numeric scopes */ public static List<InetAddress> getAddressesWithSymbolicAndNumericScopes() { List<InetAddress> result = new LinkedList<>(); try { NetworkConfiguration conf = NetworkConfiguration.probe(); conf.ip4Addresses().forEach(result::add); // Java reports link local addresses with symbolic scope, // but on Windows java.net.NetworkInterface generates its own scope names // which are incompatible with native Windows routines. // So on Windows test only addresses with numeric scope. // On other platforms test both symbolic and numeric scopes. conf.ip6Addresses() // test only IPv6 loopback and link-local addresses (JDK-8224775) .filter(addr -> addr.isLinkLocalAddress() || addr.isLoopbackAddress()) .forEach(addr6 -> { try { result.add(Inet6Address.getByAddress(null, addr6.getAddress(), addr6.getScopeId())); } catch (UnknownHostException e) { // cannot happen! throw new RuntimeException("Unexpected", e); } if (!Platform.isWindows()) { result.add(addr6); } }); } catch (IOException e) { // cannot happen! throw new RuntimeException("Unexpected", e); } return result; } /** * Returns the free port on the loopback address. * * @return The port number * @throws IOException if an I/O error occurs when opening the socket */ public static int getFreePort() throws IOException { try (ServerSocket serverSocket = new ServerSocket(0, 5, InetAddress.getLoopbackAddress());) { return serverSocket.getLocalPort(); } } /** * Returns the free unreserved port on the local host. * * @param reservedPorts reserved ports * @return The port number or -1 if failed to find a free port */ public static int findUnreservedFreePort(int... reservedPorts) { int numTries = 0; while (numTries++ < MAX_SOCKET_TRIES) { int port = -1; try { port = getFreePort(); } catch (IOException e) { e.printStackTrace(); } if (port > 0 && !isReserved(port, reservedPorts)) { return port; } } return -1; } private static boolean isReserved(int port, int[] reservedPorts) { for (int p : reservedPorts) { if (p == port) { return true; } } return false; } /** * Returns the name of the local host. * * @return The host name * @throws UnknownHostException if IP address of a host could not be determined */ public static String getHostname() throws UnknownHostException { InetAddress inetAddress = InetAddress.getLocalHost(); String hostName = inetAddress.getHostName();
assertTrue((hostName != null && !hostName.isEmpty()),
0
2023-10-15 15:56:58+00:00
24k
team-moabam/moabam-BE
src/main/java/com/moabam/api/application/room/SearchService.java
[ { "identifier": "GlobalConstant", "path": "src/main/java/com/moabam/global/common/util/GlobalConstant.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class GlobalConstant {\n\n\tpublic static final String BLANK = \"\";\n\tpublic static final String DELIMITER = \"/\";\n\tpubli...
import static com.moabam.global.common.util.GlobalConstant.*; import static com.moabam.global.error.model.ErrorMessage.*; import static org.apache.commons.lang3.StringUtils.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.notification.NotificationService; import com.moabam.api.application.room.mapper.CertificationsMapper; import com.moabam.api.application.room.mapper.ParticipantMapper; import com.moabam.api.application.room.mapper.RoomMapper; import com.moabam.api.application.room.mapper.RoutineMapper; import com.moabam.api.domain.item.Inventory; import com.moabam.api.domain.item.repository.InventorySearchRepository; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.room.Certification; import com.moabam.api.domain.room.DailyMemberCertification; import com.moabam.api.domain.room.DailyRoomCertification; import com.moabam.api.domain.room.Participant; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.RoomType; import com.moabam.api.domain.room.Routine; import com.moabam.api.domain.room.repository.CertificationsSearchRepository; import com.moabam.api.domain.room.repository.ParticipantSearchRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.domain.room.repository.RoomSearchRepository; import com.moabam.api.domain.room.repository.RoutineRepository; import com.moabam.api.dto.room.CertificationImageResponse; import com.moabam.api.dto.room.CertificationImagesResponse; import com.moabam.api.dto.room.GetAllRoomResponse; import com.moabam.api.dto.room.GetAllRoomsResponse; import com.moabam.api.dto.room.ManageRoomResponse; import com.moabam.api.dto.room.MyRoomResponse; import com.moabam.api.dto.room.MyRoomsResponse; import com.moabam.api.dto.room.ParticipantResponse; import com.moabam.api.dto.room.RoomDetailsResponse; import com.moabam.api.dto.room.RoomHistoryResponse; import com.moabam.api.dto.room.RoomsHistoryResponse; import com.moabam.api.dto.room.RoutineResponse; import com.moabam.api.dto.room.TodayCertificateRankResponse; import com.moabam.api.dto.room.UnJoinedRoomCertificateRankResponse; import com.moabam.api.dto.room.UnJoinedRoomDetailsResponse; import com.moabam.global.common.util.ClockHolder; import com.moabam.global.error.exception.ForbiddenException; import com.moabam.global.error.exception.NotFoundException; import jakarta.annotation.Nullable; import lombok.RequiredArgsConstructor;
15,369
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class SearchService { private final RoomRepository roomRepository; private final RoomSearchRepository roomSearchRepository; private final RoutineRepository routineRepository; private final ParticipantSearchRepository participantSearchRepository; private final CertificationsSearchRepository certificationsSearchRepository; private final InventorySearchRepository inventorySearchRepository; private final CertificationService certificationService; private final MemberService memberService; private final NotificationService notificationService; private final ClockHolder clockHolder; public RoomDetailsResponse getRoomDetails(Long memberId, Long roomId, LocalDate date) { Participant participant = participantSearchRepository.findOne(memberId, roomId)
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class SearchService { private final RoomRepository roomRepository; private final RoomSearchRepository roomSearchRepository; private final RoutineRepository routineRepository; private final ParticipantSearchRepository participantSearchRepository; private final CertificationsSearchRepository certificationsSearchRepository; private final InventorySearchRepository inventorySearchRepository; private final CertificationService certificationService; private final MemberService memberService; private final NotificationService notificationService; private final ClockHolder clockHolder; public RoomDetailsResponse getRoomDetails(Long memberId, Long roomId, LocalDate date) { Participant participant = participantSearchRepository.findOne(memberId, roomId)
.orElseThrow(() -> new NotFoundException(PARTICIPANT_NOT_FOUND));
25
2023-10-20 06:15:43+00:00
24k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/dropdown/XmDropdownMenuSkin.java
[ { "identifier": "CallBack", "path": "BaseUI/src/main/java/com/xm2013/jfx/common/CallBack.java", "snippet": "public interface CallBack<T> {\n \n /**\n * Call.\n *\n * @param t the t\n */\n public void call(T t);\n}" }, { "identifier": "FxKit", "path": "BaseUI/src/main...
import com.xm2013.jfx.common.CallBack; import com.xm2013.jfx.common.FxKit; import com.xm2013.jfx.control.animate.ClickAnimate; import com.xm2013.jfx.control.animate.ClickRipperAnimate; import com.xm2013.jfx.control.animate.ClickShadowAnimate; import com.xm2013.jfx.control.base.BorderType; import com.xm2013.jfx.control.base.ClickAnimateType; import com.xm2013.jfx.control.base.HueType; import com.xm2013.jfx.control.base.SkinInfo; import com.xm2013.jfx.control.icon.XmIcon; import javafx.beans.value.ChangeListener; import javafx.collections.ListChangeListener; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.geometry.*; import javafx.scene.Node; import javafx.scene.control.SkinBase; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.input.PickResult; import javafx.scene.layout.*; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.scene.text.Text; import java.util.HashMap; import java.util.Map;
17,509
} textPane.requestFocus(); getTextClickAnimate().setPoint(e.getX(), e.getY()).play(); }; private EventHandler<MouseEvent> textPanePress = e-> { label.setScaleX(0.95); label.setScaleY(0.95); }; private EventHandler<MouseEvent> textPaneRelease = e-> { label.setScaleX(1); label.setScaleY(1); }; /** * focus监听 */ private ChangeListener<Boolean> focusTextListenter = (ob, ov, nv) -> { /* * status: 1 : 默认状态下的颜色 * status: 2: hover-out focus * status: 3 : hover-focus状态下的颜色 * status: 4 : out-hover focus状态的颜色 */ updateColor(nv?(textPane.isHover()?3:4):(textPane.isHover()?2:1), 1); updateColor(1, 2); }; /** * focus监听 */ private ChangeListener<Boolean> focusIconListenter = (ob, ov, nv) -> { /* * status: 1 : 默认状态下的颜色 * status: 2: hover-out focus * status: 3 : hover-focus状态下的颜色 * status: 4 : out-hover focus状态的颜色 */ updateColor(nv?(iconPane.isHover()?3:4):(iconPane.isHover()?2:1), 2); updateColor(1, 1); }; /** * hover属性变化监听 */ private ChangeListener<Boolean> hoverTextChangeListener = (ob, ov, nv) -> { /* * status: 1 : 默认状态下的颜色 * status: 2: hover-out focus * status: 3 : hover-focus状态下的颜色 * status: 4 : out-hover focus状态的颜色 */ if (nv) { if (textPane.isFocused()) { updateColor(3,1); } else { updateColor(2,1); } } else { if (textPane.isFocused()) { updateColor(4,1); } else { updateColor(1,1); } } if(iconPane.isFocused() && !textPane.isFocused()){ updateColor(4, 2); }else{ updateColor(1, 2); } }; /** * hover属性变化监听 */ private ChangeListener<Boolean> hoverIconChangeListener = (ob, ov, nv) -> { /* * status: 1 : 默认状态下的颜色 * status: 2: hover-out focus * status: 3 : hover-focus状态下的颜色 * status: 4 : out-hover focus状态的颜色 */ if (nv) { if (iconPane.isFocused()) { updateColor(3, 2); } else { updateColor(2, 2); } // System.out.println("trigger:"+control.getTriggerType()); if(TriggerType.HOVER.equals(control.getTriggerType())){ showPop(); } } else { if (iconPane.isFocused()) { updateColor(4, 2); } else { updateColor(1, 2); } } if(textPane.isFocused() && !iconPane.isFocused()){ updateColor(4, 1); }else{ updateColor(1, 1); } }; /* ------------------------------- methods ---------------------------- */ private ClickAnimate getTextClickAnimate(){ if(textClickAnimate == null){ ClickAnimateType type = control.getClickAnimateType(); if(ClickAnimateType.SHADOW.equals(type)){
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.dropdown; public class XmDropdownMenuSkin extends SkinBase<XmDropdownMenu> { public static final EventType<Event> ON_SHOWING = new EventType<Event>(Event.ANY, "DROPDOWN_MENU_SHOWING"); public static final EventType<Event> ON_HIDING = new EventType<Event>(Event.ANY, "DROPDOWN_MENU_HIDING"); private final Text label = new Text(); //显示文本 private HBox textPane = null; //文本容器 private HBox iconPane = null; //图标容器 //组件类 private XmDropdownMenu control; //组件外观信息缓存,用于动态切换组件时缓存改变之前的外观信息 private Map<Integer, SkinInfo> skins = new HashMap<Integer, SkinInfo>(); //下拉框显示的Y坐标值 // private DoubleProperty popupY = new SimpleDoubleProperty(0); private DropdownMenuPopup popup; private ClickAnimate textClickAnimate; private ClickAnimate iconClickAnimate; protected XmDropdownMenuSkin(XmDropdownMenu control) { super(control); this.control = control; //初始化组件 label.getStyleClass().add(".xm-dropdown-menu-label"); label.textProperty().bind(control.textProperty()); label.setTextOrigin(VPos.TOP); textPane = new HBox(label); textPane.setAlignment(Pos.CENTER); iconPane = new HBox(control.getIcon()); iconPane.setAlignment(Pos.CENTER); textPane.getStyleClass().add(".xm-dropdown-menu-icon"); textPane.setFocusTraversable(true); iconPane.setFocusTraversable(true); // textPane.paddingProperty().bind(control.paddingProperty()); // iconPane.paddingProperty().bind(control.paddingProperty()); this.getChildren().addAll(textPane, iconPane); //设置外观 updateSkin(); updateColor(1, 0); if (control.isShowing()) { showPop(); } //添加监听 / 事件 control.colorTypeProperty().addListener(skinChangeListener); control.sizeTypeProperty().addListener(skinChangeListener); control.roundTypeProperty().addListener(skinChangeListener); control.clickAnimateTypeProperty().addListener(skinChangeListener); control.hueTypeProperty().addListener(skinChangeListener); control.borderTypeProperty().addListener(skinChangeListener); control.useGroupProperty().addListener(skinChangeListener); textPane.focusedProperty().addListener(focusTextListenter); textPane.hoverProperty().addListener(hoverTextChangeListener); iconPane.focusedProperty().addListener(focusIconListenter); iconPane.hoverProperty().addListener(hoverIconChangeListener); textPane.addEventFilter(MouseEvent.MOUSE_CLICKED, textPaneClick); textPane.addEventFilter(MouseEvent.MOUSE_PRESSED, textPanePress); textPane.addEventFilter(MouseEvent.MOUSE_RELEASED, textPaneRelease); control.getItems().addListener(itemListChangeListener); this.control.getScene().getWindow().focusedProperty().addListener(windowFocusListener); this.control.getScene().addEventFilter(MouseEvent.MOUSE_CLICKED, windowClickFilter); // this.control.showingProperty().addListener(showListener); this.control.addEventFilter(ON_SHOWING, showHandler); this.control.addEventFilter(ON_HIDING, hideHandler); this.control.addEventFilter(KeyEvent.KEY_RELEASED, keyEventHandler); } /* --------------------- event / listener --------------------------- */ private ChangeListener<Boolean> popupShowListener =(ob, ov, nv) -> { control.showingProperty().set(nv); }; private ChangeListener<Object> skinChangeListener = (ob, ov, nv) -> { if(nv!=null){ if(popup!=null){ popup.dispose(); popup.showProperty().removeListener(popupShowListener); } popup = null; if(textClickAnimate!=null){ textClickAnimate.dispose(); textClickAnimate = null; } if(iconClickAnimate!=null){ iconClickAnimate.dispose(); iconClickAnimate = null; } updateIcon = false; iconPane.setPadding(Insets.EMPTY); skins.clear(); updateSkin(); updateColor(1, 0); } }; private final EventHandler<Event> showHandler = e->{ // System.out.println("show"); showPop(); }; private final EventHandler<Event> hideHandler = e-> { // System.out.println("hide"); hidePop(); }; /** * 点击主窗体的时候,隐藏下拉框 */ private final EventHandler<MouseEvent> windowClickFilter = e -> { //判断是不是点击iconPane boolean isIconPane = findIconPane((Node) e.getTarget()); if(isIconPane){ //这里是监听的windowListener,所有x,y坐标是window的位置,需要获取节点的位置并设置 Bounds nodeBounds = iconPane.localToScreen(iconPane.getBoundsInLocal()); double x = e.getScreenX() - nodeBounds.getMinX(); double y = e.getScreenY() - nodeBounds.getMinY(); getIconClickAnimate().setPoint(x, y).play(); iconPane.requestFocus(); if(TriggerType.CLICK.equals(control.getTriggerType())){ if(control.isShowing()){ hidePop(); }else{ showPop(); } } }else{ hidePop(); } }; /** * 当按下空格键或者enter键,出发类似于点击的时间 */ private final EventHandler<? super KeyEvent> keyEventHandler = e->{ if(e.getCode().equals(KeyCode.ENTER)|| e.getCode().equals(KeyCode.SPACE)){ if(textPane.isFocused()){ double x = textPane.prefWidth(-1)/2; double y = textPane.prefHeight(-1)/2; Point2D point = textPane.localToScreen(x, y); Event.fireEvent(textPane, new MouseEvent( MouseEvent.MOUSE_CLICKED, x, y, point.getX(), point.getY(), null, 1, false, false,false,false,false,false,false,false,false,false, new PickResult(textPane, new Point3D(x, y, 0d), 0) )); }else if(iconPane.isFocused()){ getIconClickAnimate() .setPoint(iconPane.prefWidth(-1)/2, iconPane.prefHeight(-1)/2) .play(); if(TriggerType.CLICK.equals(control.getTriggerType())){ if(control.isShowing()){ hidePop(); }else{ showPop(); } } } } }; private boolean findIconPane(Node node){ if(node == null) return false; return node.equals(iconPane) || findIconPane(node.getParent()); } /** * 窗体失去焦点的时候,隐藏下拉弹框 */ private final ChangeListener<Boolean> windowFocusListener = (ob, ov, nv) -> { if (!nv) { hidePop(); } }; /** * 下拉列表数据发生变化的时候,重构下拉列表 */ private final ListChangeListener<DropdownMenuItem> itemListChangeListener = new ListChangeListener<>() { @Override public void onChanged(Change<? extends DropdownMenuItem> c) { control.selectedItemProperty().unbind(); popup.dispose(); popup = null; } }; /** * 点击文本的时候,回调事件,并且获取焦点 */ private EventHandler<MouseEvent> textPaneClick = e -> { CallBack<MouseEvent> callback = control.getClickCallback(); if(callback != null){ callback.call(e); } textPane.requestFocus(); getTextClickAnimate().setPoint(e.getX(), e.getY()).play(); }; private EventHandler<MouseEvent> textPanePress = e-> { label.setScaleX(0.95); label.setScaleY(0.95); }; private EventHandler<MouseEvent> textPaneRelease = e-> { label.setScaleX(1); label.setScaleY(1); }; /** * focus监听 */ private ChangeListener<Boolean> focusTextListenter = (ob, ov, nv) -> { /* * status: 1 : 默认状态下的颜色 * status: 2: hover-out focus * status: 3 : hover-focus状态下的颜色 * status: 4 : out-hover focus状态的颜色 */ updateColor(nv?(textPane.isHover()?3:4):(textPane.isHover()?2:1), 1); updateColor(1, 2); }; /** * focus监听 */ private ChangeListener<Boolean> focusIconListenter = (ob, ov, nv) -> { /* * status: 1 : 默认状态下的颜色 * status: 2: hover-out focus * status: 3 : hover-focus状态下的颜色 * status: 4 : out-hover focus状态的颜色 */ updateColor(nv?(iconPane.isHover()?3:4):(iconPane.isHover()?2:1), 2); updateColor(1, 1); }; /** * hover属性变化监听 */ private ChangeListener<Boolean> hoverTextChangeListener = (ob, ov, nv) -> { /* * status: 1 : 默认状态下的颜色 * status: 2: hover-out focus * status: 3 : hover-focus状态下的颜色 * status: 4 : out-hover focus状态的颜色 */ if (nv) { if (textPane.isFocused()) { updateColor(3,1); } else { updateColor(2,1); } } else { if (textPane.isFocused()) { updateColor(4,1); } else { updateColor(1,1); } } if(iconPane.isFocused() && !textPane.isFocused()){ updateColor(4, 2); }else{ updateColor(1, 2); } }; /** * hover属性变化监听 */ private ChangeListener<Boolean> hoverIconChangeListener = (ob, ov, nv) -> { /* * status: 1 : 默认状态下的颜色 * status: 2: hover-out focus * status: 3 : hover-focus状态下的颜色 * status: 4 : out-hover focus状态的颜色 */ if (nv) { if (iconPane.isFocused()) { updateColor(3, 2); } else { updateColor(2, 2); } // System.out.println("trigger:"+control.getTriggerType()); if(TriggerType.HOVER.equals(control.getTriggerType())){ showPop(); } } else { if (iconPane.isFocused()) { updateColor(4, 2); } else { updateColor(1, 2); } } if(textPane.isFocused() && !iconPane.isFocused()){ updateColor(4, 1); }else{ updateColor(1, 1); } }; /* ------------------------------- methods ---------------------------- */ private ClickAnimate getTextClickAnimate(){ if(textClickAnimate == null){ ClickAnimateType type = control.getClickAnimateType(); if(ClickAnimateType.SHADOW.equals(type)){
textClickAnimate = new ClickShadowAnimate(textPane, control.getColorType());
4
2023-10-17 08:57:08+00:00
24k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/ling/CollinsHeadFinder.java
[ { "identifier": "Tree", "path": "src/berkeley_parser/edu/berkeley/nlp/syntax/Tree.java", "snippet": "public class Tree<L> implements Serializable, Comparable<Tree<L>>,\n\t\tIterable<Tree<L>> {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tL label;\n\n\tList<Tree<L>> children;\n\n\tpublic vo...
import java.io.StringReader; import java.util.HashMap; import java.util.List; import edu.berkeley.nlp.syntax.Tree; import edu.berkeley.nlp.syntax.Trees; import edu.berkeley.nlp.treebank.PennTreebankLanguagePack; import edu.berkeley.nlp.treebank.TreebankLanguagePack;
18,207
package edu.berkeley.nlp.ling; //import edu.berkeley.nlp.ling.CategoryWordTag; /** * Implements the HeadFinder found in Michael Collins' 1999 thesis. Except: * we've added a head rule for NX, which returns the leftmost item. No rule for * the head of NX is found in any of the versions of Collins' head table that we * have (did he perhaps use the NP rules for NX? -- no Bikel, CL, 2005 says it * defaults to leftmost). These rules are suitable for the Penn Treebank. * <p> * May 2004: Added support for AUX and AUXG to the VP rules; these cause no * interference in Penn Treebank parsing, but means that these rules also work * for the BLLIP corpus (or Charniak parser output in general). Feb 2005: Fixes * to coordination reheading so that punctuation cannot become head. * * @author Christopher Manning */ public class CollinsHeadFinder extends AbstractCollinsHeadFinder { public CollinsHeadFinder() { this(new PennTreebankLanguagePack()); } protected int postOperationFix(int headIdx, List<Tree<String>> daughterTrees) { if (headIdx >= 2) { String prevLab = daughterTrees.get(headIdx - 1).getLabel(); if (prevLab.equals("CC")) { int newHeadIdx = headIdx - 2; Tree<String> t = daughterTrees.get(newHeadIdx); while (newHeadIdx >= 0 && t.isPreTerminal() && tlp.isPunctuationTag(t.getLabel())) { newHeadIdx--; } if (newHeadIdx >= 0) { headIdx = newHeadIdx; } } } return headIdx; } @SuppressWarnings("unchecked") public CollinsHeadFinder(TreebankLanguagePack tlp) { super(tlp); nonTerminalInfo = new HashMap(); // This version from Collins' diss (1999: 236-238) nonTerminalInfo.put("ADJP", new String[][] { { "left", "NNS", "QP", "NN", "$", "ADVP", "JJ", "VBN", "VBG", "ADJP", "JJR", "NP", "JJS", "DT", "FW", "RBR", "RBS", "SBAR", "RB" } }); nonTerminalInfo.put("ADVP", new String[][] { { "right", "RB", "RBR", "RBS", "FW", "ADVP", "TO", "CD", "JJR", "JJ", "IN", "NP", "JJS", "NN" } }); nonTerminalInfo.put("CONJP", new String[][] { { "right", "CC", "RB", "IN" } }); nonTerminalInfo.put("FRAG", new String[][] { { "right" } }); // crap nonTerminalInfo.put("INTJ", new String[][] { { "left" } }); nonTerminalInfo.put("LST", new String[][] { { "right", "LS", ":" } }); nonTerminalInfo.put("NAC", new String[][] { { "left", "NN", "NNS", "NNP", "NNPS", "NP", "NAC", "EX", "$", "CD", "QP", "PRP", "VBG", "JJ", "JJS", "JJR", "ADJP", "FW" } }); nonTerminalInfo.put("NX", new String[][] { { "left" } }); // crap nonTerminalInfo.put("PP", new String[][] { { "right", "IN", "TO", "VBG", "VBN", "RP", "FW" } }); // should prefer JJ? (PP (JJ such) (IN as) (NP (NN crocidolite))) nonTerminalInfo.put("PRN", new String[][] { { "left" } }); nonTerminalInfo.put("PRT", new String[][] { { "right", "RP" } }); nonTerminalInfo.put("QP", new String[][] { { "left", "$", "IN", "NNS", "NN", "JJ", "RB", "DT", "CD", "NCD", "QP", "JJR", "JJS" } }); nonTerminalInfo.put("RRC", new String[][] { { "right", "VP", "NP", "ADVP", "ADJP", "PP" } }); nonTerminalInfo.put("S", new String[][] { { "left", "TO", "IN", "VP", "S", "SBAR", "ADJP", "UCP", "NP" } }); nonTerminalInfo.put("SBAR", new String[][] { { "left", "WHNP", "WHPP", "WHADVP", "WHADJP", "IN", "DT", "S", "SQ", "SINV", "SBAR", "FRAG" } }); nonTerminalInfo.put("SBARQ", new String[][] { { "left", "SQ", "S", "SINV", "SBARQ", "FRAG" } }); nonTerminalInfo.put("SINV", new String[][] { { "left", "VBZ", "VBD", "VBP", "VB", "MD", "VP", "S", "SINV", "ADJP", "NP" } }); nonTerminalInfo.put("SQ", new String[][] { { "left", "VBZ", "VBD", "VBP", "VB", "MD", "VP", "SQ" } }); nonTerminalInfo.put("UCP", new String[][] { { "right" } }); nonTerminalInfo.put("VP", new String[][] { { "left", "TO", "VBD", "VBN", "MD", "VBZ", "VB", "VBG", "VBP", "AUX", "AUXG", "VP", "ADJP", "NN", "NNS", "NP" } }); nonTerminalInfo.put("WHADJP", new String[][] { { "left", "CC", "WRB", "JJ", "ADJP" } }); nonTerminalInfo.put("WHADVP", new String[][] { { "right", "CC", "WRB" } }); nonTerminalInfo.put("WHNP", new String[][] { { "left", "WDT", "WP", "WP$", "WHADJP", "WHPP", "WHNP" } }); nonTerminalInfo.put("WHPP", new String[][] { { "right", "IN", "TO", "FW" } }); nonTerminalInfo.put("X", new String[][] { { "right" } }); // crap rule nonTerminalInfo.put("NP", new String[][] { { "rightdis", "NN", "NNP", "NNPS", "NNS", "NX", "POS", "JJR" }, { "left", "NP" }, { "rightdis", "$", "ADJP", "PRN" }, { "right", "CD" }, { "rightdis", "JJ", "JJS", "RB", "QP" } }); nonTerminalInfo.put("TYPO", new String[][] { { "left" } }); // another // crap // rule, for // Switchboard // (Roger) } /** * Go through trees and determine their heads and print them. Just for * debuggin'. <br> * Usage: <code> * java edu.stanford.nlp.trees.CollinsHeadFinder treebankFilePath * </code> * * @param args * The treebankFilePath */ public static void main(String[] args) {
package edu.berkeley.nlp.ling; //import edu.berkeley.nlp.ling.CategoryWordTag; /** * Implements the HeadFinder found in Michael Collins' 1999 thesis. Except: * we've added a head rule for NX, which returns the leftmost item. No rule for * the head of NX is found in any of the versions of Collins' head table that we * have (did he perhaps use the NP rules for NX? -- no Bikel, CL, 2005 says it * defaults to leftmost). These rules are suitable for the Penn Treebank. * <p> * May 2004: Added support for AUX and AUXG to the VP rules; these cause no * interference in Penn Treebank parsing, but means that these rules also work * for the BLLIP corpus (or Charniak parser output in general). Feb 2005: Fixes * to coordination reheading so that punctuation cannot become head. * * @author Christopher Manning */ public class CollinsHeadFinder extends AbstractCollinsHeadFinder { public CollinsHeadFinder() { this(new PennTreebankLanguagePack()); } protected int postOperationFix(int headIdx, List<Tree<String>> daughterTrees) { if (headIdx >= 2) { String prevLab = daughterTrees.get(headIdx - 1).getLabel(); if (prevLab.equals("CC")) { int newHeadIdx = headIdx - 2; Tree<String> t = daughterTrees.get(newHeadIdx); while (newHeadIdx >= 0 && t.isPreTerminal() && tlp.isPunctuationTag(t.getLabel())) { newHeadIdx--; } if (newHeadIdx >= 0) { headIdx = newHeadIdx; } } } return headIdx; } @SuppressWarnings("unchecked") public CollinsHeadFinder(TreebankLanguagePack tlp) { super(tlp); nonTerminalInfo = new HashMap(); // This version from Collins' diss (1999: 236-238) nonTerminalInfo.put("ADJP", new String[][] { { "left", "NNS", "QP", "NN", "$", "ADVP", "JJ", "VBN", "VBG", "ADJP", "JJR", "NP", "JJS", "DT", "FW", "RBR", "RBS", "SBAR", "RB" } }); nonTerminalInfo.put("ADVP", new String[][] { { "right", "RB", "RBR", "RBS", "FW", "ADVP", "TO", "CD", "JJR", "JJ", "IN", "NP", "JJS", "NN" } }); nonTerminalInfo.put("CONJP", new String[][] { { "right", "CC", "RB", "IN" } }); nonTerminalInfo.put("FRAG", new String[][] { { "right" } }); // crap nonTerminalInfo.put("INTJ", new String[][] { { "left" } }); nonTerminalInfo.put("LST", new String[][] { { "right", "LS", ":" } }); nonTerminalInfo.put("NAC", new String[][] { { "left", "NN", "NNS", "NNP", "NNPS", "NP", "NAC", "EX", "$", "CD", "QP", "PRP", "VBG", "JJ", "JJS", "JJR", "ADJP", "FW" } }); nonTerminalInfo.put("NX", new String[][] { { "left" } }); // crap nonTerminalInfo.put("PP", new String[][] { { "right", "IN", "TO", "VBG", "VBN", "RP", "FW" } }); // should prefer JJ? (PP (JJ such) (IN as) (NP (NN crocidolite))) nonTerminalInfo.put("PRN", new String[][] { { "left" } }); nonTerminalInfo.put("PRT", new String[][] { { "right", "RP" } }); nonTerminalInfo.put("QP", new String[][] { { "left", "$", "IN", "NNS", "NN", "JJ", "RB", "DT", "CD", "NCD", "QP", "JJR", "JJS" } }); nonTerminalInfo.put("RRC", new String[][] { { "right", "VP", "NP", "ADVP", "ADJP", "PP" } }); nonTerminalInfo.put("S", new String[][] { { "left", "TO", "IN", "VP", "S", "SBAR", "ADJP", "UCP", "NP" } }); nonTerminalInfo.put("SBAR", new String[][] { { "left", "WHNP", "WHPP", "WHADVP", "WHADJP", "IN", "DT", "S", "SQ", "SINV", "SBAR", "FRAG" } }); nonTerminalInfo.put("SBARQ", new String[][] { { "left", "SQ", "S", "SINV", "SBARQ", "FRAG" } }); nonTerminalInfo.put("SINV", new String[][] { { "left", "VBZ", "VBD", "VBP", "VB", "MD", "VP", "S", "SINV", "ADJP", "NP" } }); nonTerminalInfo.put("SQ", new String[][] { { "left", "VBZ", "VBD", "VBP", "VB", "MD", "VP", "SQ" } }); nonTerminalInfo.put("UCP", new String[][] { { "right" } }); nonTerminalInfo.put("VP", new String[][] { { "left", "TO", "VBD", "VBN", "MD", "VBZ", "VB", "VBG", "VBP", "AUX", "AUXG", "VP", "ADJP", "NN", "NNS", "NP" } }); nonTerminalInfo.put("WHADJP", new String[][] { { "left", "CC", "WRB", "JJ", "ADJP" } }); nonTerminalInfo.put("WHADVP", new String[][] { { "right", "CC", "WRB" } }); nonTerminalInfo.put("WHNP", new String[][] { { "left", "WDT", "WP", "WP$", "WHADJP", "WHPP", "WHNP" } }); nonTerminalInfo.put("WHPP", new String[][] { { "right", "IN", "TO", "FW" } }); nonTerminalInfo.put("X", new String[][] { { "right" } }); // crap rule nonTerminalInfo.put("NP", new String[][] { { "rightdis", "NN", "NNP", "NNPS", "NNS", "NX", "POS", "JJR" }, { "left", "NP" }, { "rightdis", "$", "ADJP", "PRN" }, { "right", "CD" }, { "rightdis", "JJ", "JJS", "RB", "QP" } }); nonTerminalInfo.put("TYPO", new String[][] { { "left" } }); // another // crap // rule, for // Switchboard // (Roger) } /** * Go through trees and determine their heads and print them. Just for * debuggin'. <br> * Usage: <code> * java edu.stanford.nlp.trees.CollinsHeadFinder treebankFilePath * </code> * * @param args * The treebankFilePath */ public static void main(String[] args) {
Trees.PennTreeReader reader = new Trees.PennTreeReader(
1
2023-10-22 13:13:22+00:00
24k
neftalito/R-Info-Plus
form/Parser.java
[ { "identifier": "Iniciar", "path": "arbol/sentencia/primitiva/Iniciar.java", "snippet": "public class Iniciar extends Primitiva {\n RobotAST r;\n int x;\n int y;\n Identificador Ident;\n DeclaracionRobots robAST;\n DeclaracionVariable varAST;\n\n public Iniciar(final Identificador I...
import arbol.sentencia.primitiva.Iniciar; import arbol.sentencia.primitiva.AsignarArea; import arbol.DeclaracionAreas; import arbol.Programa; import arbol.ParametroFormal; import arbol.Proceso; import arbol.RobotAST; import arbol.DeclaracionProcesos; import arbol.Cuerpo; import arbol.sentencia.IteradorCondicional; import arbol.sentencia.IteradorIncondicional; import arbol.sentencia.Seleccion; import arbol.sentencia.primitiva.Random; import arbol.sentencia.primitiva.RecibirMensaje; import arbol.sentencia.primitiva.EnviarMensaje; import arbol.sentencia.primitiva.DepositarPapel; import arbol.sentencia.primitiva.DepositarFlor; import arbol.sentencia.primitiva.TomarPapel; import arbol.sentencia.primitiva.TomarFlor; import arbol.sentencia.primitiva.Derecha; import arbol.sentencia.primitiva.Izquierda; import arbol.sentencia.primitiva.Mover; import arbol.sentencia.primitiva.Leer; import arbol.sentencia.primitiva.BloquearEsquina; import arbol.sentencia.primitiva.LiberarEsquina; import arbol.sentencia.primitiva.Primitiva; import arbol.llamada.IdentificadorLlamada; import arbol.sentencia.Sentencia; import arbol.sentencia.Asignacion; import arbol.llamada.Pos; import arbol.llamada.Informar; import java.util.ArrayList; import arbol.sentencia.Invocacion; import javax.swing.JOptionPane; import arbol.DeclaracionRobots; import arbol.Tipo; import arbol.Variable; import arbol.Identificador; import arbol.expresion.ExpresionBinaria; import arbol.expresion.ExpresionUnaria; import java.util.Stack; import arbol.DeclaracionVariable; import arbol.expresion.ValorBooleano; import arbol.expresion.ValorNumerico; import arbol.expresion.operador.relacional.MenorIgual; import arbol.expresion.operador.relacional.Menor; import arbol.expresion.operador.relacional.MayorIgual; import arbol.expresion.operador.relacional.Mayor; import arbol.expresion.operador.relacional.Igual; import arbol.expresion.operador.relacional.Distinto; import arbol.expresion.operador.booleano.Not; import arbol.expresion.operador.booleano.Or; import arbol.expresion.operador.booleano.And; import arbol.expresion.operador.aritmetico.Suma; import arbol.expresion.operador.aritmetico.Resta; import arbol.expresion.operador.aritmetico.Multiplicacion; import arbol.expresion.operador.aritmetico.Division; import arbol.expresion.operador.aritmetico.Modulo; import arbol.expresion.operador.Operador; import arbol.expresion.HayObstaculo; import arbol.expresion.HayPapelEnLaEsquina; import arbol.expresion.HayFlorEnLaEsquina; import arbol.expresion.HayPapelEnLaBolsa; import arbol.expresion.HayFlorEnLaBolsa; import arbol.expresion.PosCa; import arbol.expresion.PosAv; import arbol.expresion.CantidadFloresBolsa; import arbol.expresion.CantidadPapelesBolsa; import arbol.expresion.Expresion;
20,847
package form; public class Parser { public Token currentToken; private Scanner scanner; Ciudad city; Parser(final String fuente, final Ciudad city) throws Exception { this.city = city; this.scanner = new Scanner(fuente); try { this.nextToken(); } catch (Exception e) { this.reportParseError("Error in Parser!"); } } public boolean isOperando(final Token token) { return token.kind == 23 || token.kind == 32 || token.kind == 33; } public boolean isVariableEntorno(final Token token) { switch (token.kind) { case 8: case 9: case 10: case 11: case 12: case 13: case 63: case 82: case 83: { return true; } default: { return false; } } } public boolean isOperador(final Token token) { boolean res = false; switch (token.kind) { case 30: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 81: { res = true; break; } default: { res = false; break; } } return res; } public boolean isParentesis(final Token token) { boolean res = false; switch (token.kind) { case 21: case 22: { res = true; break; } default: { res = false; break; } } return res; } public boolean thereIsHighOrEqualPrecedence(final Object o) { boolean res = true; final Token t = (Token) o; if (t.kind == 21 || (this.currentToken.kind == 49 && t.kind == 50) || (this.currentToken.kind == 49 && t.kind == 51) || ((this.currentToken.kind == 48 || this.currentToken.kind == 47 || this.currentToken.kind == 81) && (t.kind == 45 || t.kind == 46))) { res = false; } return res; } public Expresion parseVariableEntorno(final Token t) { Expresion expAST = null; switch (t.kind) { case 8: { expAST = new PosAv(); break; } case 9: { expAST = new PosCa(); break; } case 11: { expAST = new HayFlorEnLaBolsa(); break; } case 13: {
package form; public class Parser { public Token currentToken; private Scanner scanner; Ciudad city; Parser(final String fuente, final Ciudad city) throws Exception { this.city = city; this.scanner = new Scanner(fuente); try { this.nextToken(); } catch (Exception e) { this.reportParseError("Error in Parser!"); } } public boolean isOperando(final Token token) { return token.kind == 23 || token.kind == 32 || token.kind == 33; } public boolean isVariableEntorno(final Token token) { switch (token.kind) { case 8: case 9: case 10: case 11: case 12: case 13: case 63: case 82: case 83: { return true; } default: { return false; } } } public boolean isOperador(final Token token) { boolean res = false; switch (token.kind) { case 30: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 81: { res = true; break; } default: { res = false; break; } } return res; } public boolean isParentesis(final Token token) { boolean res = false; switch (token.kind) { case 21: case 22: { res = true; break; } default: { res = false; break; } } return res; } public boolean thereIsHighOrEqualPrecedence(final Object o) { boolean res = true; final Token t = (Token) o; if (t.kind == 21 || (this.currentToken.kind == 49 && t.kind == 50) || (this.currentToken.kind == 49 && t.kind == 51) || ((this.currentToken.kind == 48 || this.currentToken.kind == 47 || this.currentToken.kind == 81) && (t.kind == 45 || t.kind == 46))) { res = false; } return res; } public Expresion parseVariableEntorno(final Token t) { Expresion expAST = null; switch (t.kind) { case 8: { expAST = new PosAv(); break; } case 9: { expAST = new PosCa(); break; } case 11: { expAST = new HayFlorEnLaBolsa(); break; } case 13: {
expAST = new HayPapelEnLaBolsa();
59
2023-10-20 15:45:37+00:00
24k
moonstoneid/aero-cast
apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/eth/EthSubscriberAdapter.java
[ { "identifier": "EthRegistryProperties", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/config/EthRegistryProperties.java", "snippet": "@ConfigurationProperties(prefix = \"eth.registry\")\n@Data\npublic class EthRegistryProperties {\n public String contractAddress;\n}" }, ...
import java.util.List; import com.moonstoneid.aerocast.common.config.EthRegistryProperties; import com.moonstoneid.aerocast.common.eth.BaseEthAdapter; import com.moonstoneid.aerocast.common.eth.EthUtil; import com.moonstoneid.aerocast.common.eth.contracts.FeedRegistry; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber.CreateSubscriptionEventResponse; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber.RemoveSubscriptionEventResponse; import io.reactivex.disposables.Disposable; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.web3j.crypto.Credentials; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.request.EthFilter;
17,794
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j public class EthSubscriberAdapter extends BaseEthAdapter { public interface EventCallback { void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr); void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr); } private final Credentials credentials; private final String regContractAddr; private final MultiValueMap<String, Disposable> eventSubscribers = new LinkedMultiValueMap<>(); public EthSubscriberAdapter(Web3j web3j, EthRegistryProperties ethRegistryProperties) { super(web3j); this.credentials = createDummyCredentials(); this.regContractAddr = ethRegistryProperties.getContractAddress(); } public String getSubscriberContractAddress(String subAccountAddr) {
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j public class EthSubscriberAdapter extends BaseEthAdapter { public interface EventCallback { void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr); void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr); } private final Credentials credentials; private final String regContractAddr; private final MultiValueMap<String, Disposable> eventSubscribers = new LinkedMultiValueMap<>(); public EthSubscriberAdapter(Web3j web3j, EthRegistryProperties ethRegistryProperties) { super(web3j); this.credentials = createDummyCredentials(); this.regContractAddr = ethRegistryProperties.getContractAddress(); } public String getSubscriberContractAddress(String subAccountAddr) {
FeedRegistry contract = getRegistryContract();
3
2023-10-23 20:33:07+00:00
24k
JonnyOnlineYT/xenza
src/minecraft/net/minecraft/crash/CrashReport.java
[ { "identifier": "Logger", "path": "src/minecraft/net/augustus/utils/Logger.java", "snippet": "public class Logger {\n public void info(String s) {\n System.out.println(s);\n }\n public void info(String s, Throwable var13) {\n System.out.println(s);\n var13.printStackTrace()...
import com.google.common.collect.Lists; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; import net.augustus.utils.Logger; import net.minecraft.util.ReportedException; import net.minecraft.world.gen.layer.IntCache; import optifine.CrashReportCpu; import optifine.CrashReporter; import optifine.Reflector; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils;
16,295
} }); this.theReportCategory.addCrashSectionCallable("IntCache", new Callable() { private static final String __OBFID = "CL_00001355"; public String call() throws Exception { return IntCache.getCacheSizes(); } }); if (Reflector.FMLCommonHandler_enhanceCrashReport.exists()) { Object object = Reflector.call(Reflector.FMLCommonHandler_instance, new Object[0]); Reflector.callString(object, Reflector.FMLCommonHandler_enhanceCrashReport, new Object[] {this, this.theReportCategory}); } } /** * Returns the description of the Crash Report. */ public String getDescription() { return this.description; } /** * Returns the Throwable object that is the cause for the crash and Crash Report. */ public Throwable getCrashCause() { return this.cause; } /** * Gets the various sections of the crash report into the given StringBuilder */ public void getSectionsInStringBuilder(StringBuilder builder) { if ((this.stacktrace == null || this.stacktrace.length <= 0) && this.crashReportSections.size() > 0) { this.stacktrace = (StackTraceElement[])((StackTraceElement[])ArrayUtils.subarray(((CrashReportCategory)this.crashReportSections.get(0)).getStackTrace(), 0, 1)); } if (this.stacktrace != null && this.stacktrace.length > 0) { builder.append("-- Head --\n"); builder.append("Stacktrace:\n"); for (StackTraceElement stacktraceelement : this.stacktrace) { builder.append("\t").append("at ").append(stacktraceelement.toString()); builder.append("\n"); } builder.append("\n"); } for (Object crashreportcategory : this.crashReportSections) { ((CrashReportCategory) crashreportcategory).appendToStringBuilder(builder); builder.append("\n\n"); } this.theReportCategory.appendToStringBuilder(builder); } /** * Gets the stack trace of the Throwable that caused this crash report, or if that fails, the cause .toString(). */ public String getCauseStackTraceOrString() { StringWriter stringwriter = null; PrintWriter printwriter = null; Object object = this.cause; if (((Throwable)object).getMessage() == null) { if (object instanceof NullPointerException) { object = new NullPointerException(this.description); } else if (object instanceof StackOverflowError) { object = new StackOverflowError(this.description); } else if (object instanceof OutOfMemoryError) { object = new OutOfMemoryError(this.description); } ((Throwable)object).setStackTrace(this.cause.getStackTrace()); } String s = ((Throwable)object).toString(); try { stringwriter = new StringWriter(); printwriter = new PrintWriter(stringwriter); ((Throwable)object).printStackTrace(printwriter); s = stringwriter.toString(); } finally { IOUtils.closeQuietly((Writer)stringwriter); IOUtils.closeQuietly((Writer)printwriter); } return s; } /** * Gets the complete report with headers, stack trace, and different sections as a string. */ public String getCompleteReport() { if (!this.reported) { this.reported = true;
package net.minecraft.crash; public class CrashReport { private static final Logger logger = new Logger(); /** Description of the crash report. */ private final String description; /** The Throwable that is the "cause" for this crash and Crash Report. */ private final Throwable cause; /** Category of crash */ private final CrashReportCategory theReportCategory = new CrashReportCategory(this, "System Details"); /** Holds the keys and values of all crash report sections. */ private final List crashReportSections = Lists.newArrayList(); /** File of crash report. */ private File crashReportFile; private boolean field_85059_f = true; private StackTraceElement[] stacktrace = new StackTraceElement[0]; private static final String __OBFID = "CL_00000990"; private boolean reported = false; public CrashReport(String descriptionIn, Throwable causeThrowable) { this.description = descriptionIn; this.cause = causeThrowable; this.populateEnvironment(); } /** * Populates this crash report with initial information about the running server and operating system / java * environment */ private void populateEnvironment() { this.theReportCategory.addCrashSectionCallable("Minecraft Version", new Callable() { private static final String __OBFID = "CL_00001197"; public String call() { return "1.8.8"; } }); this.theReportCategory.addCrashSectionCallable("Operating System", new Callable() { private static final String __OBFID = "CL_00001222"; public String call() { return System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version"); } }); this.theReportCategory.addCrashSectionCallable("CPU", new CrashReportCpu()); this.theReportCategory.addCrashSectionCallable("Java Version", new Callable<String>() { public String call() { return System.getProperty("java.version") + ", " + System.getProperty("java.vendor"); } }); this.theReportCategory.addCrashSectionCallable("Java VM Version", new Callable() { private static final String __OBFID = "CL_00001275"; public String call() { return System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor"); } }); this.theReportCategory.addCrashSectionCallable("Memory", new Callable() { private static final String __OBFID = "CL_00001302"; public String call() { Runtime runtime = Runtime.getRuntime(); long i = runtime.maxMemory(); long j = runtime.totalMemory(); long k = runtime.freeMemory(); long l = i / 1024L / 1024L; long i1 = j / 1024L / 1024L; long j1 = k / 1024L / 1024L; return k + " bytes (" + j1 + " MB) / " + j + " bytes (" + i1 + " MB) up to " + i + " bytes (" + l + " MB)"; } }); this.theReportCategory.addCrashSectionCallable("JVM Flags", new Callable() { private static final String __OBFID = "CL_00001329"; public String call() { RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean(); List list = runtimemxbean.getInputArguments(); int i = 0; StringBuilder stringbuilder = new StringBuilder(); for (Object s : list) { if (((String) s).startsWith("-X")) { if (i++ > 0) { stringbuilder.append(" "); } stringbuilder.append(s); } } return String.format("%d total; %s", new Object[] {Integer.valueOf(i), stringbuilder.toString()}); } }); this.theReportCategory.addCrashSectionCallable("IntCache", new Callable() { private static final String __OBFID = "CL_00001355"; public String call() throws Exception { return IntCache.getCacheSizes(); } }); if (Reflector.FMLCommonHandler_enhanceCrashReport.exists()) { Object object = Reflector.call(Reflector.FMLCommonHandler_instance, new Object[0]); Reflector.callString(object, Reflector.FMLCommonHandler_enhanceCrashReport, new Object[] {this, this.theReportCategory}); } } /** * Returns the description of the Crash Report. */ public String getDescription() { return this.description; } /** * Returns the Throwable object that is the cause for the crash and Crash Report. */ public Throwable getCrashCause() { return this.cause; } /** * Gets the various sections of the crash report into the given StringBuilder */ public void getSectionsInStringBuilder(StringBuilder builder) { if ((this.stacktrace == null || this.stacktrace.length <= 0) && this.crashReportSections.size() > 0) { this.stacktrace = (StackTraceElement[])((StackTraceElement[])ArrayUtils.subarray(((CrashReportCategory)this.crashReportSections.get(0)).getStackTrace(), 0, 1)); } if (this.stacktrace != null && this.stacktrace.length > 0) { builder.append("-- Head --\n"); builder.append("Stacktrace:\n"); for (StackTraceElement stacktraceelement : this.stacktrace) { builder.append("\t").append("at ").append(stacktraceelement.toString()); builder.append("\n"); } builder.append("\n"); } for (Object crashreportcategory : this.crashReportSections) { ((CrashReportCategory) crashreportcategory).appendToStringBuilder(builder); builder.append("\n\n"); } this.theReportCategory.appendToStringBuilder(builder); } /** * Gets the stack trace of the Throwable that caused this crash report, or if that fails, the cause .toString(). */ public String getCauseStackTraceOrString() { StringWriter stringwriter = null; PrintWriter printwriter = null; Object object = this.cause; if (((Throwable)object).getMessage() == null) { if (object instanceof NullPointerException) { object = new NullPointerException(this.description); } else if (object instanceof StackOverflowError) { object = new StackOverflowError(this.description); } else if (object instanceof OutOfMemoryError) { object = new OutOfMemoryError(this.description); } ((Throwable)object).setStackTrace(this.cause.getStackTrace()); } String s = ((Throwable)object).toString(); try { stringwriter = new StringWriter(); printwriter = new PrintWriter(stringwriter); ((Throwable)object).printStackTrace(printwriter); s = stringwriter.toString(); } finally { IOUtils.closeQuietly((Writer)stringwriter); IOUtils.closeQuietly((Writer)printwriter); } return s; } /** * Gets the complete report with headers, stack trace, and different sections as a string. */ public String getCompleteReport() { if (!this.reported) { this.reported = true;
CrashReporter.onCrashReport(this, this.theReportCategory);
4
2023-10-15 00:21:15+00:00
24k
instrumental-id/iiq-common-public
src/com/identityworksllc/iiq/common/query/QueryUtil.java
[ { "identifier": "ResultSetIterator", "path": "src/com/identityworksllc/iiq/common/iterators/ResultSetIterator.java", "snippet": "@SuppressWarnings(\"unused\")\npublic final class ResultSetIterator implements Iterator<Object[]>, AutoCloseable {\n\n\t/**\n\t * An interface to use for custom type handlers\...
import com.identityworksllc.iiq.common.iterators.ResultSetIterator; import com.identityworksllc.iiq.common.threads.PooledWorkerResults; import com.identityworksllc.iiq.common.threads.SailPointWorker; import com.identityworksllc.iiq.common.vo.Failure; import openconnector.Util; import org.apache.commons.logging.Log; import sailpoint.api.SailPointContext; import sailpoint.api.SailPointFactory; import sailpoint.object.Filter; import sailpoint.object.QueryOptions; import sailpoint.object.SailPointObject; import sailpoint.tools.GeneralException; import sailpoint.tools.ObjectNotFoundException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger;
14,554
package com.identityworksllc.iiq.common.query; /** * Simplifies querying by automatically enclosing queries in a result processing loop. * This is copied from an older project. IIQ also provides a number of similar utilities * in their JdbcUtil class. * * @param <T> The type returned from the result processor */ @SuppressWarnings("unused") public class QueryUtil<T> { /** * Callback for processing the result * * @param <U> The type returned from the result processor, must extend T */ @FunctionalInterface public interface ResultProcessor<U> { /** * Callback to indicate that the result set had no results * * @throws SQLException on failures */ @SuppressWarnings("unused") default void noResult() throws SQLException { // Blank by default } /** * Called once per result. Do not call "next" on the ResultSet here. * * @param result The result set at the current point * @return An object of type T * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ U processResult(ResultSet result) throws GeneralException, SQLException; } /** * Static helper method to retrieve the first value from the result set as a long * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static Long getLongValue(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<Long>(Log).getResult(query, result -> result.getLong(resultColumn), parameters); } /** * Retrieves the first string from the result set in the given column, then * queries for a sailPoint object of the given type based on that name or * ID. The column name is assumed to be 'id', which is the primary key in * most of the SailPoint tables. * * @param context The Sailpoint context to use to query * @param cls The class to query based on the ID being pulled * @param query The query to run * @param log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static <T extends SailPointObject> T getObjectByQuery(final SailPointContext context, Class<T> cls, final String query, final Log log, Object... parameters) throws Throwable { return getObjectByQuery(context, cls, query, "id", log, parameters); } /** * Retrieves the first string from the result set in the given column, then * queries for a sailPoint object of the given type based on that name or * ID. * * @param context The Sailpoint context to use to query * @param cls The class to query based on the ID being pulled * @param query The query to run * @param idColumn The column to grab from the results * @param log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static <T extends SailPointObject> T getObjectByQuery(final SailPointContext context, Class<T> cls, final String query, final String idColumn, final Log log, Object... parameters) throws Throwable { String id = getStringValue(query, idColumn, log, parameters); return context.getObject(cls, id); } /** * Static helper method ot retrieve values from the query as a list of strings * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static List<String> getStringList(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<String>(Log).getResults(query, result -> result.getString(resultColumn), parameters); } /** * Static helper method to retrieve the first string value from the result set * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static String getStringValue(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<String>(Log).getResult(query, result -> result.getString(resultColumn), parameters); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param filterString The Filter string * @param <T> The type of the object to query * @return The queried object * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, String filterString) throws GeneralException { Filter filter = Filter.compile(filterString); return getUniqueObject(context, cls, filter); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param filter a Filter object * @param <T> The type of the object to query * @return The queried object * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, Filter filter) throws GeneralException { QueryOptions qo = new QueryOptions(); qo.add(filter); return getUniqueObject(context, cls, qo); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param queryOptions a QueryOptions object which will be cloned before querying * @param <T> The type of the object to query * @return The queried object * @throws ObjectNotFoundException if no matches are found * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, QueryOptions queryOptions) throws ObjectNotFoundException, GeneralException { QueryOptions qo = new QueryOptions(); qo.setFilters(queryOptions.getFilters()); qo.setCacheResults(queryOptions.isCacheResults()); qo.setDirtyRead(queryOptions.isDirtyRead()); qo.setDistinct(queryOptions.isDistinct()); qo.setFlushBeforeQuery(queryOptions.isFlushBeforeQuery()); qo.setGroupBys(queryOptions.getGroupBys()); qo.setOrderings(queryOptions.getOrderings()); qo.setScopeResults(queryOptions.getScopeResults()); qo.setTransactionLock(queryOptions.isTransactionLock()); qo.setUnscopedGloballyAccessible(queryOptions.getUnscopedGloballyAccessible()); qo.setResultLimit(2); List<T> results = context.getObjects(cls, qo); if (results == null || results.isEmpty()) { throw new ObjectNotFoundException(); } else if (results.size() > 1) { throw new GeneralException("Expected a unique result, got " + results.size() + " results"); } return results.get(0); } /** * Set up the given parameters in the prepared statmeent * @param stmt The statement * @param parameters The parameters * @throws SQLException if any failures occur setting parameters */ public static void setupParameters(PreparedStatement stmt, Object[] parameters) throws SQLException { Parameters.setupParameters(stmt, parameters); } /** * Logger */ private final Log logger; /** * Connection to SailPoint */ private final SailPointContext sailPointContext; /** * Constructor * @param Log logger * @throws GeneralException if there is an error getting the current thread's SailPoint context */ public QueryUtil(@SuppressWarnings("unused") Log Log) throws GeneralException { this(SailPointFactory.getCurrentContext(), Log); } /** * Constructor * @param context The SailPoint context * @param log The logger */ public QueryUtil(SailPointContext context, Log log) { this.sailPointContext = context; this.logger = log; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public T getResult(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); T output = null; try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { if (results.next()) { output = processor.processResult(results); } else { processor.noResult(); } } } } return output; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public List<T> getResults(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); List<T> output = new ArrayList<>(); try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { boolean hasResults = false; while (results.next()) { hasResults = true; output.add(processor.processResult(results)); } if (!hasResults) { processor.noResult(); } } } } return output; } /** * Iterates a query by invoking a Beanshell callback for each method * @param inputs The inputs * @throws GeneralException if anything goes wrong */ public void iterateQuery(IterateQueryOptions inputs) throws GeneralException { try (Connection connection = inputs.openConnection()) { try (NamedParameterStatement stmt = new NamedParameterStatement(connection, inputs.getQuery())) { if (!Util.isEmpty(inputs.getQueryParams())) { stmt.setParameters(inputs.getQueryParams()); } try (ResultSet results = stmt.executeQuery()) { ResultSetMetaData rsmd = results.getMetaData(); List<String> columns = new ArrayList<>(); for(int c = 1; c <= rsmd.getColumnCount(); c++) { columns.add(rsmd.getColumnLabel(c)); }
package com.identityworksllc.iiq.common.query; /** * Simplifies querying by automatically enclosing queries in a result processing loop. * This is copied from an older project. IIQ also provides a number of similar utilities * in their JdbcUtil class. * * @param <T> The type returned from the result processor */ @SuppressWarnings("unused") public class QueryUtil<T> { /** * Callback for processing the result * * @param <U> The type returned from the result processor, must extend T */ @FunctionalInterface public interface ResultProcessor<U> { /** * Callback to indicate that the result set had no results * * @throws SQLException on failures */ @SuppressWarnings("unused") default void noResult() throws SQLException { // Blank by default } /** * Called once per result. Do not call "next" on the ResultSet here. * * @param result The result set at the current point * @return An object of type T * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ U processResult(ResultSet result) throws GeneralException, SQLException; } /** * Static helper method to retrieve the first value from the result set as a long * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static Long getLongValue(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<Long>(Log).getResult(query, result -> result.getLong(resultColumn), parameters); } /** * Retrieves the first string from the result set in the given column, then * queries for a sailPoint object of the given type based on that name or * ID. The column name is assumed to be 'id', which is the primary key in * most of the SailPoint tables. * * @param context The Sailpoint context to use to query * @param cls The class to query based on the ID being pulled * @param query The query to run * @param log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static <T extends SailPointObject> T getObjectByQuery(final SailPointContext context, Class<T> cls, final String query, final Log log, Object... parameters) throws Throwable { return getObjectByQuery(context, cls, query, "id", log, parameters); } /** * Retrieves the first string from the result set in the given column, then * queries for a sailPoint object of the given type based on that name or * ID. * * @param context The Sailpoint context to use to query * @param cls The class to query based on the ID being pulled * @param query The query to run * @param idColumn The column to grab from the results * @param log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static <T extends SailPointObject> T getObjectByQuery(final SailPointContext context, Class<T> cls, final String query, final String idColumn, final Log log, Object... parameters) throws Throwable { String id = getStringValue(query, idColumn, log, parameters); return context.getObject(cls, id); } /** * Static helper method ot retrieve values from the query as a list of strings * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static List<String> getStringList(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<String>(Log).getResults(query, result -> result.getString(resultColumn), parameters); } /** * Static helper method to retrieve the first string value from the result set * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static String getStringValue(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<String>(Log).getResult(query, result -> result.getString(resultColumn), parameters); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param filterString The Filter string * @param <T> The type of the object to query * @return The queried object * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, String filterString) throws GeneralException { Filter filter = Filter.compile(filterString); return getUniqueObject(context, cls, filter); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param filter a Filter object * @param <T> The type of the object to query * @return The queried object * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, Filter filter) throws GeneralException { QueryOptions qo = new QueryOptions(); qo.add(filter); return getUniqueObject(context, cls, qo); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param queryOptions a QueryOptions object which will be cloned before querying * @param <T> The type of the object to query * @return The queried object * @throws ObjectNotFoundException if no matches are found * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, QueryOptions queryOptions) throws ObjectNotFoundException, GeneralException { QueryOptions qo = new QueryOptions(); qo.setFilters(queryOptions.getFilters()); qo.setCacheResults(queryOptions.isCacheResults()); qo.setDirtyRead(queryOptions.isDirtyRead()); qo.setDistinct(queryOptions.isDistinct()); qo.setFlushBeforeQuery(queryOptions.isFlushBeforeQuery()); qo.setGroupBys(queryOptions.getGroupBys()); qo.setOrderings(queryOptions.getOrderings()); qo.setScopeResults(queryOptions.getScopeResults()); qo.setTransactionLock(queryOptions.isTransactionLock()); qo.setUnscopedGloballyAccessible(queryOptions.getUnscopedGloballyAccessible()); qo.setResultLimit(2); List<T> results = context.getObjects(cls, qo); if (results == null || results.isEmpty()) { throw new ObjectNotFoundException(); } else if (results.size() > 1) { throw new GeneralException("Expected a unique result, got " + results.size() + " results"); } return results.get(0); } /** * Set up the given parameters in the prepared statmeent * @param stmt The statement * @param parameters The parameters * @throws SQLException if any failures occur setting parameters */ public static void setupParameters(PreparedStatement stmt, Object[] parameters) throws SQLException { Parameters.setupParameters(stmt, parameters); } /** * Logger */ private final Log logger; /** * Connection to SailPoint */ private final SailPointContext sailPointContext; /** * Constructor * @param Log logger * @throws GeneralException if there is an error getting the current thread's SailPoint context */ public QueryUtil(@SuppressWarnings("unused") Log Log) throws GeneralException { this(SailPointFactory.getCurrentContext(), Log); } /** * Constructor * @param context The SailPoint context * @param log The logger */ public QueryUtil(SailPointContext context, Log log) { this.sailPointContext = context; this.logger = log; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public T getResult(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); T output = null; try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { if (results.next()) { output = processor.processResult(results); } else { processor.noResult(); } } } } return output; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public List<T> getResults(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); List<T> output = new ArrayList<>(); try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { boolean hasResults = false; while (results.next()) { hasResults = true; output.add(processor.processResult(results)); } if (!hasResults) { processor.noResult(); } } } } return output; } /** * Iterates a query by invoking a Beanshell callback for each method * @param inputs The inputs * @throws GeneralException if anything goes wrong */ public void iterateQuery(IterateQueryOptions inputs) throws GeneralException { try (Connection connection = inputs.openConnection()) { try (NamedParameterStatement stmt = new NamedParameterStatement(connection, inputs.getQuery())) { if (!Util.isEmpty(inputs.getQueryParams())) { stmt.setParameters(inputs.getQueryParams()); } try (ResultSet results = stmt.executeQuery()) { ResultSetMetaData rsmd = results.getMetaData(); List<String> columns = new ArrayList<>(); for(int c = 1; c <= rsmd.getColumnCount(); c++) { columns.add(rsmd.getColumnLabel(c)); }
ResultSetIterator rsi = new ResultSetIterator(results, columns, sailPointContext);
0
2023-10-20 15:20:16+00:00
24k
mosaic-addons/traffic-state-estimation
src/main/java/com/dcaiti/mosaic/app/tse/TseServerApp.java
[ { "identifier": "FcdRecord", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FcdRecord.java", "snippet": "public class FcdRecord extends FxdRecord {\n\n /**\n * List of vehicles perceived during the collection of FCD in the form of {@link VehicleObject VehicleObjects}.\n */\n private...
import java.nio.file.Path; import java.nio.file.Paths; import com.dcaiti.mosaic.app.fxd.data.FcdRecord; import com.dcaiti.mosaic.app.fxd.data.FcdTraversal; import com.dcaiti.mosaic.app.fxd.messages.FcdUpdateMessage; import com.dcaiti.mosaic.app.tse.config.CTseServerApp; import com.dcaiti.mosaic.app.tse.persistence.FcdDataStorage; import com.dcaiti.mosaic.app.tse.persistence.FcdDatabaseHelper; import com.dcaiti.mosaic.app.tse.persistence.ScenarioDatabaseHelper; import com.dcaiti.mosaic.app.tse.processors.SpatioTemporalProcessor; import com.dcaiti.mosaic.app.tse.processors.ThresholdProcessor; import org.eclipse.mosaic.lib.database.Database; import org.eclipse.mosaic.lib.objects.v2x.V2xMessage; import org.eclipse.mosaic.lib.util.scheduling.EventManager; import com.google.common.collect.Lists;
15,522
/* * Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse; /** * An extension of {@link FxdReceiverApp} adding the data storage in the form of the {@link FcdDataStorage} and the * Network-{@link Database} and configuring default * {@link com.dcaiti.mosaic.app.tse.processors.FxdProcessor FxdProcessors}. */ public class TseServerApp extends FxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage, CTseServerApp, TseKernel> { /** * Storage field, allowing to persist TSE results as well as data exchange between processors. * Default value will be a {@link FcdDatabaseHelper} */ private FcdDataStorage fcdDataStorage; public TseServerApp() { super(CTseServerApp.class); } @Override public void enableCellModule() { getOs().getCellModule().enable(); } /** * Initializes the {@link TseKernel} by * <ul> * <li>validating that processors for minimal function are configured,</li> * <li> reading the scenario database for access to network specific data,</li> * <li>and setting up the {@link #fcdDataStorage} to persist TSE metrics.</li> * </ul> * * @param eventManager the {@link EventManager} to enable the kernel with event handling capabilities * @param config configuration for the server * @return the initialized {@link TseKernel} */ @Override protected TseKernel initKernel(EventManager eventManager, CTseServerApp config) { addRequiredProcessors(config);
/* * Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse; /** * An extension of {@link FxdReceiverApp} adding the data storage in the form of the {@link FcdDataStorage} and the * Network-{@link Database} and configuring default * {@link com.dcaiti.mosaic.app.tse.processors.FxdProcessor FxdProcessors}. */ public class TseServerApp extends FxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage, CTseServerApp, TseKernel> { /** * Storage field, allowing to persist TSE results as well as data exchange between processors. * Default value will be a {@link FcdDatabaseHelper} */ private FcdDataStorage fcdDataStorage; public TseServerApp() { super(CTseServerApp.class); } @Override public void enableCellModule() { getOs().getCellModule().enable(); } /** * Initializes the {@link TseKernel} by * <ul> * <li>validating that processors for minimal function are configured,</li> * <li> reading the scenario database for access to network specific data,</li> * <li>and setting up the {@link #fcdDataStorage} to persist TSE metrics.</li> * </ul> * * @param eventManager the {@link EventManager} to enable the kernel with event handling capabilities * @param config configuration for the server * @return the initialized {@link TseKernel} */ @Override protected TseKernel initKernel(EventManager eventManager, CTseServerApp config) { addRequiredProcessors(config);
Database networkDatabase = ScenarioDatabaseHelper.getNetworkDbFromFile(getOs());
6
2023-10-23 16:39:40+00:00
24k
eclipse-egit/egit
org.eclipse.egit.core/src/org/eclipse/egit/core/op/CommitOperation.java
[ { "identifier": "Activator", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/Activator.java", "snippet": "public class Activator extends Plugin {\n\n\t/** The plug-in ID for Egit core. */\n\tpublic static final String PLUGIN_ID = \"org.eclipse.egit.core\"; //$NON-NLS-1$\n\n\tprivate static Acti...
import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.TimeZone; import java.util.regex.Pattern; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.egit.core.Activator; import org.eclipse.egit.core.RepositoryUtil; import org.eclipse.egit.core.internal.CoreText; import org.eclipse.egit.core.internal.job.RuleUtil; import org.eclipse.egit.core.internal.signing.GpgConfigurationException; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.core.settings.GitSettings; import org.eclipse.jgit.api.AddCommand; import org.eclipse.jgit.api.CommitCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.JGitInternalException; import org.eclipse.jgit.lib.GpgConfig; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryState; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.util.RawParseUtils; import org.eclipse.osgi.util.NLS; import org.eclipse.team.core.TeamException;
19,618
/******************************************************************************* * Copyright (c) 2010-2012, SAP AG and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Stefan Lay (SAP AG) - initial implementation * Jens Baumgart (SAP AG) * Robin Stocker (independent) *******************************************************************************/ package org.eclipse.egit.core.op; /** * This class implements the commit of a list of files. */ public class CommitOperation implements IEGitOperation { private static final Pattern LEADING_WHITESPACE = Pattern .compile("^[\\h\\v]+"); //$NON-NLS-1$ Collection<String> commitFileList; private boolean commitWorkingDirChanges = false; private final String author; private final String committer; private final String message; private boolean amending = false; private boolean commitAll = false; private boolean sign = false; private Repository repo; Collection<String> notTracked; private boolean createChangeId; private boolean commitIndex; RevCommit commit = null; /** * @param filesToCommit * a list of files which will be included in the commit * @param notTracked * a list of all untracked files * @param author * the author of the commit * @param committer * the committer of the commit * @param message * the commit message * @throws CoreException */ public CommitOperation(IFile[] filesToCommit, Collection<IFile> notTracked, String author, String committer, String message) throws CoreException { this.author = author; this.committer = committer; this.message = stripLeadingWhitespace(message); if (filesToCommit != null && filesToCommit.length > 0) setRepository(filesToCommit[0]); if (filesToCommit != null) commitFileList = buildFileList(Arrays.asList(filesToCommit)); if (notTracked != null) this.notTracked = buildFileList(notTracked); } /** * @param repository * @param filesToCommit * a list of files which will be included in the commit * @param notTracked * a list of all untracked files * @param author * the author of the commit * @param committer * the committer of the commit * @param message * the commit message * @throws CoreException */ public CommitOperation(Repository repository, Collection<String> filesToCommit, Collection<String> notTracked, String author, String committer, String message) throws CoreException { this.repo = repository; this.author = author; this.committer = committer; this.message = stripLeadingWhitespace(message); if (filesToCommit != null) commitFileList = new HashSet<>(filesToCommit); if (notTracked != null) this.notTracked = new HashSet<>(notTracked); } /** * Constructs a CommitOperation that commits the index * @param repository * @param author * @param committer * @param message * @throws CoreException */ public CommitOperation(Repository repository, String author, String committer, String message) throws CoreException { this.repo = repository; this.author = author; this.committer = committer; this.message = stripLeadingWhitespace(message); this.commitIndex = true; } private String stripLeadingWhitespace(String text) { return text == null ? "" //$NON-NLS-1$ : LEADING_WHITESPACE.matcher(text).replaceFirst(""); //$NON-NLS-1$ } private void setRepository(IFile file) throws CoreException { RepositoryMapping mapping = RepositoryMapping.getMapping(file); if (mapping == null)
/******************************************************************************* * Copyright (c) 2010-2012, SAP AG and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Stefan Lay (SAP AG) - initial implementation * Jens Baumgart (SAP AG) * Robin Stocker (independent) *******************************************************************************/ package org.eclipse.egit.core.op; /** * This class implements the commit of a list of files. */ public class CommitOperation implements IEGitOperation { private static final Pattern LEADING_WHITESPACE = Pattern .compile("^[\\h\\v]+"); //$NON-NLS-1$ Collection<String> commitFileList; private boolean commitWorkingDirChanges = false; private final String author; private final String committer; private final String message; private boolean amending = false; private boolean commitAll = false; private boolean sign = false; private Repository repo; Collection<String> notTracked; private boolean createChangeId; private boolean commitIndex; RevCommit commit = null; /** * @param filesToCommit * a list of files which will be included in the commit * @param notTracked * a list of all untracked files * @param author * the author of the commit * @param committer * the committer of the commit * @param message * the commit message * @throws CoreException */ public CommitOperation(IFile[] filesToCommit, Collection<IFile> notTracked, String author, String committer, String message) throws CoreException { this.author = author; this.committer = committer; this.message = stripLeadingWhitespace(message); if (filesToCommit != null && filesToCommit.length > 0) setRepository(filesToCommit[0]); if (filesToCommit != null) commitFileList = buildFileList(Arrays.asList(filesToCommit)); if (notTracked != null) this.notTracked = buildFileList(notTracked); } /** * @param repository * @param filesToCommit * a list of files which will be included in the commit * @param notTracked * a list of all untracked files * @param author * the author of the commit * @param committer * the committer of the commit * @param message * the commit message * @throws CoreException */ public CommitOperation(Repository repository, Collection<String> filesToCommit, Collection<String> notTracked, String author, String committer, String message) throws CoreException { this.repo = repository; this.author = author; this.committer = committer; this.message = stripLeadingWhitespace(message); if (filesToCommit != null) commitFileList = new HashSet<>(filesToCommit); if (notTracked != null) this.notTracked = new HashSet<>(notTracked); } /** * Constructs a CommitOperation that commits the index * @param repository * @param author * @param committer * @param message * @throws CoreException */ public CommitOperation(Repository repository, String author, String committer, String message) throws CoreException { this.repo = repository; this.author = author; this.committer = committer; this.message = stripLeadingWhitespace(message); this.commitIndex = true; } private String stripLeadingWhitespace(String text) { return text == null ? "" //$NON-NLS-1$ : LEADING_WHITESPACE.matcher(text).replaceFirst(""); //$NON-NLS-1$ } private void setRepository(IFile file) throws CoreException { RepositoryMapping mapping = RepositoryMapping.getMapping(file); if (mapping == null)
throw new CoreException(Activator.error(NLS.bind(
0
2023-10-20 15:17:51+00:00
24k
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/query/Q10.java
[ { "identifier": "OLAPTerminal", "path": "code/src/main/java/benchmark/olap/OLAPTerminal.java", "snippet": "public class OLAPTerminal implements Runnable {\n // public static AtomicInteger DeliveryBG=new AtomicInteger(0);\n public static AtomicLong oorderTableSize = new AtomicLong(benchmark.olap.qu...
import benchmark.olap.OLAPTerminal; import benchmark.oltp.OLTPClient; import config.CommonConfig; import org.apache.log4j.Logger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import static benchmark.oltp.OLTPClient.gloabalSysCurrentTime; import static config.CommonConfig.DB_OCEANBASE;
14,793
package benchmark.olap.query; public class Q10 extends baseQuery { private static Logger log = Logger.getLogger(Q10.class); public double k; public double b; private int dbType; public Q10(int dbType) throws ParseException { super(); this.k = OLTPClient.k1; this.b = OLTPClient.b1; this.filterRate = benchmark.olap.OLAPClient.filterRate[9]; //o_entry_d0.0765 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { // this.orderlineTSize=OLAPTerminal.orderLineTableSize; // this.orderTSize=OLAPTerminal.oorderTableSize; // this.olNotnullSize=OLAPTerminal.orderlineTableNotNullSize; this.k = OLTPClient.k1; this.b = OLTPClient.b1; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException { double countNumber = OLAPTerminal.oorderTableSize.get() * filterRate; // log.info("#10:filterRate" + filterRate); // log.info("#1:countNumber"); SimpleDateFormat simFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start_d = simFormat.parse("1998-08-02 00:00:00");//min date 1992-01-01,1993-10-01 Date start_d_1 = simFormat.parse("1992-01-01 00:00:00"); // log.info("#10: countNumber:" + countNumber + ",size:" + this.orderOriginSize); if (countNumber >= this.orderOriginSize) { // int s = (int) (((countNumber - this.b) / this.k) / 1000); // log.info("Q10-this.b" + this.b + ",this.k" + this.k); // log.info("Q10-1 s: " + s); // return simFormat.format(super.getDateAfter(start_d, s)); int s = (int) ((countNumber / OLAPTerminal.oorderTableSize.get()) * ((2405+OLTPClient.deltaDays2) * 24 * 60 * 60)); // log.info("Q10-1 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } else { // double historyNumber = this.orderOriginSize - countNumber; int s = (int) ((countNumber / this.orderOriginSize) * (2405 * 24 * 60 * 60)); // log.info("Q10-2 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } } @Override public String getQuery() throws ParseException { // this.dynamicParam = getDeltaTimes(); String query; switch (this.dbType) {
package benchmark.olap.query; public class Q10 extends baseQuery { private static Logger log = Logger.getLogger(Q10.class); public double k; public double b; private int dbType; public Q10(int dbType) throws ParseException { super(); this.k = OLTPClient.k1; this.b = OLTPClient.b1; this.filterRate = benchmark.olap.OLAPClient.filterRate[9]; //o_entry_d0.0765 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { // this.orderlineTSize=OLAPTerminal.orderLineTableSize; // this.orderTSize=OLAPTerminal.oorderTableSize; // this.olNotnullSize=OLAPTerminal.orderlineTableNotNullSize; this.k = OLTPClient.k1; this.b = OLTPClient.b1; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException { double countNumber = OLAPTerminal.oorderTableSize.get() * filterRate; // log.info("#10:filterRate" + filterRate); // log.info("#1:countNumber"); SimpleDateFormat simFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start_d = simFormat.parse("1998-08-02 00:00:00");//min date 1992-01-01,1993-10-01 Date start_d_1 = simFormat.parse("1992-01-01 00:00:00"); // log.info("#10: countNumber:" + countNumber + ",size:" + this.orderOriginSize); if (countNumber >= this.orderOriginSize) { // int s = (int) (((countNumber - this.b) / this.k) / 1000); // log.info("Q10-this.b" + this.b + ",this.k" + this.k); // log.info("Q10-1 s: " + s); // return simFormat.format(super.getDateAfter(start_d, s)); int s = (int) ((countNumber / OLAPTerminal.oorderTableSize.get()) * ((2405+OLTPClient.deltaDays2) * 24 * 60 * 60)); // log.info("Q10-1 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } else { // double historyNumber = this.orderOriginSize - countNumber; int s = (int) ((countNumber / this.orderOriginSize) * (2405 * 24 * 60 * 60)); // log.info("Q10-2 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } } @Override public String getQuery() throws ParseException { // this.dynamicParam = getDeltaTimes(); String query; switch (this.dbType) {
case CommonConfig.DB_TIDB:
2
2023-10-22 11:22:32+00:00
24k
bowbahdoe/java-audio-stack
tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/file/TAudioOutputStream.java
[ { "identifier": "convertSign8", "path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/TConversionTool.java", "snippet": "public static void convertSign8(byte[] buffer, int byteOffset, int sampleCount) {\r\n\tsampleCount+=byteOffset;\r\n\tfor (int i=byteOffset; i<sampleCount; i++) {\r\n\...
import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import static dev.mccue.tritonus.share.sampled.TConversionTool.convertSign8; import static dev.mccue.tritonus.share.sampled.TConversionTool.swapOrder16; import static dev.mccue.tritonus.share.sampled.TConversionTool.swapOrder24; import static dev.mccue.tritonus.share.sampled.TConversionTool.swapOrder32; import dev.mccue.tritonus.share.TDebug; import dev.mccue.tritonus.share.sampled.AudioUtils; import dev.mccue.tritonus.share.sampled.TConversionTool;
21,282
/* * TAudioOutputStream.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 2000 by Matthias Pfisterer * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* |<--- this code is formatted to fit into 80 columns --->| */ package dev.mccue.tritonus.share.sampled.file; /** * Base class for classes implementing AudioOutputStream. * * @author Matthias Pfisterer */ public abstract class TAudioOutputStream implements AudioOutputStream { private AudioFormat m_audioFormat; private long m_lLength; // in bytes private long m_lCalculatedLength; private TDataOutputStream m_dataOutputStream; private boolean m_bDoBackPatching; private boolean m_bHeaderWritten; /** if this flag is set, do sign conversion for 8-bit PCM data */ private boolean m_doSignConversion; /** if this flag is set, do endian conversion for 16-bit PCM data */ private boolean m_doEndianConversion; protected TAudioOutputStream(AudioFormat audioFormat, long lLength, TDataOutputStream dataOutputStream, boolean bDoBackPatching) { m_audioFormat = audioFormat; m_lLength = lLength; m_lCalculatedLength = 0; m_dataOutputStream = dataOutputStream; m_bDoBackPatching = bDoBackPatching; m_bHeaderWritten = false; } /** * descendants should call this method if implicit sign conversion for 8-bit * data should be done */ protected void requireSign8bit(boolean signed) { if (m_audioFormat.getSampleSizeInBits() == 8 && AudioUtils.isPCM(m_audioFormat)) { boolean si = m_audioFormat.getEncoding().equals( AudioFormat.Encoding.PCM_SIGNED); m_doSignConversion = signed != si; } } /** * descendants should call this method if implicit endian conversion should * be done. Currently supported for 16, 24, and 32 bits per sample. */ protected void requireEndianness(boolean bigEndian) { int ssib = m_audioFormat.getSampleSizeInBits(); if ((ssib == 16 || ssib == 24 || ssib == 32) && AudioUtils.isPCM(m_audioFormat)) { m_doEndianConversion = bigEndian != m_audioFormat.isBigEndian(); } } public AudioFormat getFormat() { return m_audioFormat; } /** Gives length of the stream. * This value is in bytes. It may be AudioSystem.NOT_SPECIFIED * to express that the length is unknown. */ public long getLength() { return m_lLength; } /** Gives number of bytes already written. */ // IDEA: rename this to BytesWritten or something like that ? public long getCalculatedLength() { return m_lCalculatedLength; } protected TDataOutputStream getDataOutputStream() { return m_dataOutputStream; } /** do sign or endianness conversion */ private void handleImplicitConversions(byte[] abData, int nOffset, int nLength) { if (m_doSignConversion) {
/* * TAudioOutputStream.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 2000 by Matthias Pfisterer * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* |<--- this code is formatted to fit into 80 columns --->| */ package dev.mccue.tritonus.share.sampled.file; /** * Base class for classes implementing AudioOutputStream. * * @author Matthias Pfisterer */ public abstract class TAudioOutputStream implements AudioOutputStream { private AudioFormat m_audioFormat; private long m_lLength; // in bytes private long m_lCalculatedLength; private TDataOutputStream m_dataOutputStream; private boolean m_bDoBackPatching; private boolean m_bHeaderWritten; /** if this flag is set, do sign conversion for 8-bit PCM data */ private boolean m_doSignConversion; /** if this flag is set, do endian conversion for 16-bit PCM data */ private boolean m_doEndianConversion; protected TAudioOutputStream(AudioFormat audioFormat, long lLength, TDataOutputStream dataOutputStream, boolean bDoBackPatching) { m_audioFormat = audioFormat; m_lLength = lLength; m_lCalculatedLength = 0; m_dataOutputStream = dataOutputStream; m_bDoBackPatching = bDoBackPatching; m_bHeaderWritten = false; } /** * descendants should call this method if implicit sign conversion for 8-bit * data should be done */ protected void requireSign8bit(boolean signed) { if (m_audioFormat.getSampleSizeInBits() == 8 && AudioUtils.isPCM(m_audioFormat)) { boolean si = m_audioFormat.getEncoding().equals( AudioFormat.Encoding.PCM_SIGNED); m_doSignConversion = signed != si; } } /** * descendants should call this method if implicit endian conversion should * be done. Currently supported for 16, 24, and 32 bits per sample. */ protected void requireEndianness(boolean bigEndian) { int ssib = m_audioFormat.getSampleSizeInBits(); if ((ssib == 16 || ssib == 24 || ssib == 32) && AudioUtils.isPCM(m_audioFormat)) { m_doEndianConversion = bigEndian != m_audioFormat.isBigEndian(); } } public AudioFormat getFormat() { return m_audioFormat; } /** Gives length of the stream. * This value is in bytes. It may be AudioSystem.NOT_SPECIFIED * to express that the length is unknown. */ public long getLength() { return m_lLength; } /** Gives number of bytes already written. */ // IDEA: rename this to BytesWritten or something like that ? public long getCalculatedLength() { return m_lCalculatedLength; } protected TDataOutputStream getDataOutputStream() { return m_dataOutputStream; } /** do sign or endianness conversion */ private void handleImplicitConversions(byte[] abData, int nOffset, int nLength) { if (m_doSignConversion) {
TConversionTool.convertSign8(abData, nOffset, nLength);
0
2023-10-19 14:09:37+00:00
24k
AstroDev2023/2023-studio-1-but-better
source/core/src/test/com/csse3200/game/physics/PhysicsMovementComponentTest.java
[ { "identifier": "TestGameArea", "path": "source/core/src/main/com/csse3200/game/areas/TestGameArea.java", "snippet": "public class TestGameArea extends GameArea {\n\tprivate GameMap gameMap;\n\tprivate ClimateController climateController = new ClimateController();\n\n\t@Override\n\tpublic void create() ...
import com.badlogic.gdx.math.Vector2; import com.csse3200.game.areas.TestGameArea; import com.csse3200.game.areas.terrain.GameMap; import com.csse3200.game.areas.terrain.TerrainComponent; import com.csse3200.game.areas.terrain.TerrainFactory; import com.csse3200.game.components.CameraComponent; import com.csse3200.game.entities.Entity; import com.csse3200.game.entities.EntityService; import com.csse3200.game.entities.EntityType; import com.csse3200.game.extensions.GameExtension; import com.csse3200.game.physics.components.PhysicsComponent; import com.csse3200.game.physics.components.PhysicsMovementComponent; import com.csse3200.game.services.ResourceService; import com.csse3200.game.services.ServiceLocator; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
20,202
package com.csse3200.game.physics; @ExtendWith(GameExtension.class) class PhysicsMovementComponentTest { private Entity flyingEntity; private Entity nonFlyingEntity; private static final TestGameArea gameArea = new TestGameArea(); @BeforeAll static void setupGameAreaAndMap() { //necessary for allowing the Terrain factory to properly generate the map with correct tile dimensions ResourceService resourceService = new ResourceService(); resourceService.loadTextures(TerrainFactory.getMapTextures()); resourceService.loadAll(); ServiceLocator.registerResourceService(resourceService); //Loads the test terrain into the GameMap TerrainComponent terrainComponent = mock(TerrainComponent.class); doReturn(TerrainFactory.WORLD_TILE_SIZE).when(terrainComponent).getTileSize(); GameMap gameMap = new GameMap(new TerrainFactory(new CameraComponent())); gameMap.setTerrainComponent(terrainComponent); gameMap.loadTestTerrain("configs/TestMaps/playerActionsTest_map.txt"); //Sets the GameMap in the TestGameArea gameArea.setGameMap(gameMap); //Only needed the assets for the map loading, can be unloaded resourceService.unloadAssets(TerrainFactory.getMapTextures()); resourceService.dispose(); } @BeforeEach void beforeEach() { // Mock rendering, physics, game time PhysicsService physicsService = new PhysicsService(); ServiceLocator.registerPhysicsService(physicsService); ServiceLocator.registerResourceService(mock(ResourceService.class)); ServiceLocator.registerEntityService(mock(EntityService.class)); ServiceLocator.registerGameArea(gameArea); } @Test void nonFlyingEntitiesMovementModifiersTest() {
package com.csse3200.game.physics; @ExtendWith(GameExtension.class) class PhysicsMovementComponentTest { private Entity flyingEntity; private Entity nonFlyingEntity; private static final TestGameArea gameArea = new TestGameArea(); @BeforeAll static void setupGameAreaAndMap() { //necessary for allowing the Terrain factory to properly generate the map with correct tile dimensions ResourceService resourceService = new ResourceService(); resourceService.loadTextures(TerrainFactory.getMapTextures()); resourceService.loadAll(); ServiceLocator.registerResourceService(resourceService); //Loads the test terrain into the GameMap TerrainComponent terrainComponent = mock(TerrainComponent.class); doReturn(TerrainFactory.WORLD_TILE_SIZE).when(terrainComponent).getTileSize(); GameMap gameMap = new GameMap(new TerrainFactory(new CameraComponent())); gameMap.setTerrainComponent(terrainComponent); gameMap.loadTestTerrain("configs/TestMaps/playerActionsTest_map.txt"); //Sets the GameMap in the TestGameArea gameArea.setGameMap(gameMap); //Only needed the assets for the map loading, can be unloaded resourceService.unloadAssets(TerrainFactory.getMapTextures()); resourceService.dispose(); } @BeforeEach void beforeEach() { // Mock rendering, physics, game time PhysicsService physicsService = new PhysicsService(); ServiceLocator.registerPhysicsService(physicsService); ServiceLocator.registerResourceService(mock(ResourceService.class)); ServiceLocator.registerEntityService(mock(EntityService.class)); ServiceLocator.registerGameArea(gameArea); } @Test void nonFlyingEntitiesMovementModifiersTest() {
nonFlyingEntity = new Entity(EntityType.DUMMY);
7
2023-10-17 22:34:04+00:00
24k
RoessinghResearch/senseeact
SenSeeActService/src/main/java/nl/rrd/senseeact/service/DatabaseLoader.java
[ { "identifier": "PerformanceStatTable", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/PerformanceStatTable.java", "snippet": "public class PerformanceStatTable extends DatabaseTableDef<PerformanceStat> {\n\tpublic static final String NAME = \"performance_stats\";\n\t\n\tprivate st...
import nl.rrd.senseeact.client.model.PerformanceStatTable; import nl.rrd.senseeact.client.model.Role; import nl.rrd.senseeact.client.model.SystemStatTable; import nl.rrd.senseeact.client.project.BaseProject; import nl.rrd.senseeact.client.project.ProjectRepository; import nl.rrd.senseeact.dao.*; import nl.rrd.senseeact.dao.listener.DatabaseActionListener; import nl.rrd.senseeact.dao.listener.DatabaseListenerRepository; import nl.rrd.senseeact.service.access.ProjectUserAccessControl; import nl.rrd.senseeact.service.access.ProjectUserAccessControlRepository; import nl.rrd.senseeact.service.controller.AuthControllerExecution; import nl.rrd.senseeact.service.exception.HttpException; import nl.rrd.senseeact.service.model.UserTable; import nl.rrd.senseeact.service.model.*; import nl.rrd.utils.AppComponents; import nl.rrd.utils.ReferenceParameter; import nl.rrd.utils.datetime.DateTimeUtils; import nl.rrd.utils.exception.DatabaseException; import nl.rrd.utils.schedule.AbstractScheduledTask; import nl.rrd.utils.schedule.ScheduleParams; import nl.rrd.utils.schedule.TaskSchedule; import nl.rrd.utils.schedule.TaskScheduler; import org.slf4j.Logger; import java.io.IOException; import java.time.ZonedDateTime; import java.util.*;
16,150
openConn.baseConn = baseConn; openConn.openTime = System.currentTimeMillis(); CloseListenDatabaseConnection conn = new CloseListenDatabaseConnection(openConn); openConn.dbConns.add(conn); openConns.add(openConn); saved = true; logger.trace("Saved new database connection"); return conn; } } finally { if (!saved) { baseConn.close(); logger.trace("Closed unsaved database connection"); } } } /** * Closes this database loader and any open database connections. */ public void close() { synchronized (INSTANCE_LOCK) { if (closed) return; closed = true; TaskScheduler scheduler = AppComponents.get(TaskScheduler.class); scheduler.cancelTask(null, cleanTaskId); for (OpenDatabaseConnection openConn : openConns) { openConn.baseConn.close(); } openConns.clear(); Logger logger = AppComponents.getLogger(getClass().getSimpleName()); logger.info("Closed database loader and connections"); } } /** * Returns the authentication database. It will create, initialise or * upgrade the database if needed. If no user exists, it will create the * admin user. You should not call any queries that change the database * structure. * * @param conn the database connection * @return the database * @throws DatabaseException if a database error occurs */ public Database initAuthDatabase(DatabaseConnection conn) throws DatabaseException { synchronized (AUTH_DB_LOCK) { List<DatabaseTableDef<?>> tableDefs = getAuthDbTables(); Configuration config = AppComponents.get(Configuration.class); String dbNamePrefix = config.get(Configuration.DB_NAME_PREFIX); Database db = conn.initDatabase(dbNamePrefix + "_auth", tableDefs, true); db.setSyncEnabled(false); UserCache userCache = UserCache.createInstance(db); int count = userCache.getCount(); if (count == 0) createInitialAuthData(db); return db; } } public static List<DatabaseTableDef<?>> getAuthDbTables() { List<DatabaseTableDef<?>> result = new ArrayList<>(); result.add(new UserTable()); result.add(new GroupTable()); result.add(new UserProjectTable()); result.add(new GroupMemberTable()); result.add(new PermissionTable()); result.add(new ProjectUserAccessTable()); result.add(new UserActiveChangeTable()); result.add(new SyncPushRegistrationTable()); result.add(new WatchSubjectRegistrationTable()); result.add(new WatchTableRegistrationTable()); result.add(new MobileWakeRequestTable()); result.add(new DataExportTable()); result.add(new SystemStatTable()); result.add(new PerformanceStatTable()); OAuthTableRepository oauthRepo = AppComponents.get( OAuthTableRepository.class); result.addAll(oauthRepo.getOAuthTables()); ProjectUserAccessControlRepository uacRepo = AppComponents.get( ProjectUserAccessControlRepository.class); Map<String,ProjectUserAccessControl> projectAccessControlMap = uacRepo.getProjectMap(); for (String project : projectAccessControlMap.keySet()) { ProjectUserAccessControl projectAccessControl = projectAccessControlMap.get(project); result.addAll(projectAccessControl.getTables()); } return result; } /** * This method is called on the authentication database if it doesn't have * any users. It will create the admin user. * * @param db the authentication database * @throws DatabaseException if a database error occurs */ private void createInitialAuthData(Database db) throws DatabaseException { Configuration config = AppComponents.get(Configuration.class); User user = new User(); user.setUserid(UUID.randomUUID().toString().toLowerCase() .replaceAll("-", "")); user.setEmail(config.get(Configuration.ADMIN_EMAIL)); try { AuthControllerExecution.setPassword(user, config.get(Configuration.ADMIN_PASSWORD), "password", false); } catch (HttpException ex) { throw new RuntimeException( "Invalid admin password in configuration: " + ex.getMessage(), ex); } ZonedDateTime now = DateTimeUtils.nowMs(); user.setCreated(now); user.setLastActive(now);
package nl.rrd.senseeact.service; /** * Utility class to load the authentication database and project databases. * This is thread-safe. * * @author Dennis Hofs (RRD) */ public class DatabaseLoader { private static final int MIN_KEEP_OPEN_DURATION = 300000; // milliseconds private static final int MAX_KEEP_OPEN_DURATION = 600000; // milliseconds private static final int CLEAN_INTERVAL = 60000; // milliseconds private final Object AUTH_DB_LOCK = new Object(); private final Map<String,Object> PROJECT_DB_LOCKS = new LinkedHashMap<>(); private final List<String> listeningDatabases = new ArrayList<>(); private List<OpenDatabaseConnection> openConns = new ArrayList<>(); private static final Object INSTANCE_LOCK = new Object(); private static DatabaseLoader instance = null; private boolean closed = false; private String cleanTaskId; private DatabaseLoader() { TaskScheduler scheduler = AppComponents.get(TaskScheduler.class); cleanTaskId = scheduler.generateTaskId(); scheduler.scheduleTask(null, new CleanConnectionsTask(), cleanTaskId); } public static DatabaseLoader getInstance() { synchronized (INSTANCE_LOCK) { if (instance == null) instance = new DatabaseLoader(); return instance; } } /** * Opens a connection to the database server. It enables action logging * for synchronisation with a remote database. When you have completed the * database operations, you should close the connection. * * @return the database connection * @throws IOException if the connection could not be opened */ public DatabaseConnection openConnection() throws IOException { Logger logger = AppComponents.getLogger(getClass().getSimpleName()); synchronized (INSTANCE_LOCK) { if (closed) throw new IOException("DatabaseLoader closed"); OpenDatabaseConnection openConn = findMatchingOpenConnection(); if (openConn != null) { CloseListenDatabaseConnection conn = new CloseListenDatabaseConnection(openConn); openConn.dbConns.add(conn); logger.trace("Reuse database connection"); return conn; } } DatabaseFactory dbFactory = AppComponents.getInstance() .getComponent(DatabaseFactory.class); boolean saved = false; DatabaseConnection baseConn = dbFactory.connect(); logger.trace("Created new database connection"); try { baseConn.setSyncEnabled(true); synchronized (INSTANCE_LOCK) { if (closed) throw new IOException("DatabaseLoader closed"); OpenDatabaseConnection openConn = findMatchingOpenConnection(); if (openConn != null) { CloseListenDatabaseConnection conn = new CloseListenDatabaseConnection(openConn); openConn.dbConns.add(conn); logger.trace("Reuse simultaneously created new database connection"); return conn; } openConn = new OpenDatabaseConnection(); openConn.baseConn = baseConn; openConn.openTime = System.currentTimeMillis(); CloseListenDatabaseConnection conn = new CloseListenDatabaseConnection(openConn); openConn.dbConns.add(conn); openConns.add(openConn); saved = true; logger.trace("Saved new database connection"); return conn; } } finally { if (!saved) { baseConn.close(); logger.trace("Closed unsaved database connection"); } } } /** * Closes this database loader and any open database connections. */ public void close() { synchronized (INSTANCE_LOCK) { if (closed) return; closed = true; TaskScheduler scheduler = AppComponents.get(TaskScheduler.class); scheduler.cancelTask(null, cleanTaskId); for (OpenDatabaseConnection openConn : openConns) { openConn.baseConn.close(); } openConns.clear(); Logger logger = AppComponents.getLogger(getClass().getSimpleName()); logger.info("Closed database loader and connections"); } } /** * Returns the authentication database. It will create, initialise or * upgrade the database if needed. If no user exists, it will create the * admin user. You should not call any queries that change the database * structure. * * @param conn the database connection * @return the database * @throws DatabaseException if a database error occurs */ public Database initAuthDatabase(DatabaseConnection conn) throws DatabaseException { synchronized (AUTH_DB_LOCK) { List<DatabaseTableDef<?>> tableDefs = getAuthDbTables(); Configuration config = AppComponents.get(Configuration.class); String dbNamePrefix = config.get(Configuration.DB_NAME_PREFIX); Database db = conn.initDatabase(dbNamePrefix + "_auth", tableDefs, true); db.setSyncEnabled(false); UserCache userCache = UserCache.createInstance(db); int count = userCache.getCount(); if (count == 0) createInitialAuthData(db); return db; } } public static List<DatabaseTableDef<?>> getAuthDbTables() { List<DatabaseTableDef<?>> result = new ArrayList<>(); result.add(new UserTable()); result.add(new GroupTable()); result.add(new UserProjectTable()); result.add(new GroupMemberTable()); result.add(new PermissionTable()); result.add(new ProjectUserAccessTable()); result.add(new UserActiveChangeTable()); result.add(new SyncPushRegistrationTable()); result.add(new WatchSubjectRegistrationTable()); result.add(new WatchTableRegistrationTable()); result.add(new MobileWakeRequestTable()); result.add(new DataExportTable()); result.add(new SystemStatTable()); result.add(new PerformanceStatTable()); OAuthTableRepository oauthRepo = AppComponents.get( OAuthTableRepository.class); result.addAll(oauthRepo.getOAuthTables()); ProjectUserAccessControlRepository uacRepo = AppComponents.get( ProjectUserAccessControlRepository.class); Map<String,ProjectUserAccessControl> projectAccessControlMap = uacRepo.getProjectMap(); for (String project : projectAccessControlMap.keySet()) { ProjectUserAccessControl projectAccessControl = projectAccessControlMap.get(project); result.addAll(projectAccessControl.getTables()); } return result; } /** * This method is called on the authentication database if it doesn't have * any users. It will create the admin user. * * @param db the authentication database * @throws DatabaseException if a database error occurs */ private void createInitialAuthData(Database db) throws DatabaseException { Configuration config = AppComponents.get(Configuration.class); User user = new User(); user.setUserid(UUID.randomUUID().toString().toLowerCase() .replaceAll("-", "")); user.setEmail(config.get(Configuration.ADMIN_EMAIL)); try { AuthControllerExecution.setPassword(user, config.get(Configuration.ADMIN_PASSWORD), "password", false); } catch (HttpException ex) { throw new RuntimeException( "Invalid admin password in configuration: " + ex.getMessage(), ex); } ZonedDateTime now = DateTimeUtils.nowMs(); user.setCreated(now); user.setLastActive(now);
user.setRole(Role.ADMIN);
1
2023-10-24 09:36:50+00:00
24k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/admin/usersws/UserWsServiceImpl.java
[ { "identifier": "Messages", "path": "src/main/java/org/msh/etbm/commons/Messages.java", "snippet": "@Component\npublic class Messages {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(Messages.class);\n\n public static final String NOT_UNIQUE = \"NotUnique\";\n public static fi...
import org.msh.etbm.commons.Messages; import org.msh.etbm.commons.commands.CommandLog; import org.msh.etbm.commons.commands.CommandTypes; import org.msh.etbm.commons.entities.EntityServiceContext; import org.msh.etbm.commons.entities.EntityServiceImpl; import org.msh.etbm.commons.entities.ServiceResult; import org.msh.etbm.commons.entities.dao.EntityDAO; import org.msh.etbm.commons.entities.query.QueryBuilder; import org.msh.etbm.commons.mail.MailService; import org.msh.etbm.db.entities.User; import org.msh.etbm.db.entities.UserWorkspace; import org.msh.etbm.services.admin.usersws.data.UserWsChangePwdFormData; import org.msh.etbm.services.admin.usersws.data.UserWsData; import org.msh.etbm.services.admin.usersws.data.UserWsDetailedData; import org.msh.etbm.services.admin.usersws.data.UserWsItemData; import org.msh.etbm.services.pub.ForgotPwdService; import org.msh.etbm.services.security.UserUtils; import org.msh.etbm.services.security.password.ChangePasswordResponse; import org.msh.etbm.services.security.password.PasswordLogHandler; import org.msh.etbm.services.security.password.PasswordUpdateService; import org.msh.etbm.services.session.usersession.UserRequestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Errors; import java.util.Date; import java.util.HashMap; import java.util.Map;
19,385
package org.msh.etbm.services.admin.usersws; /** * Implementation of the {@link UserWsService} to handle CRUD operations for User workspace * <p> * Created by rmemoria on 26/1/16. */ @Service public class UserWsServiceImpl extends EntityServiceImpl<UserWorkspace, UserWsQueryParams> implements UserWsService { @Autowired UserRequestService userRequestService; @Autowired MailService mailService; @Autowired Messages messages; @Autowired PasswordUpdateService passwordUpdateService; @Autowired ForgotPwdService forgotPwdService; @Override protected void buildQuery(QueryBuilder<UserWorkspace> builder, UserWsQueryParams queryParams) { builder.setEntityAlias("a"); // add profiles builder.addProfile(UserWsQueryParams.PROFILE_ITEM, UserWsItemData.class);
package org.msh.etbm.services.admin.usersws; /** * Implementation of the {@link UserWsService} to handle CRUD operations for User workspace * <p> * Created by rmemoria on 26/1/16. */ @Service public class UserWsServiceImpl extends EntityServiceImpl<UserWorkspace, UserWsQueryParams> implements UserWsService { @Autowired UserRequestService userRequestService; @Autowired MailService mailService; @Autowired Messages messages; @Autowired PasswordUpdateService passwordUpdateService; @Autowired ForgotPwdService forgotPwdService; @Override protected void buildQuery(QueryBuilder<UserWorkspace> builder, UserWsQueryParams queryParams) { builder.setEntityAlias("a"); // add profiles builder.addProfile(UserWsQueryParams.PROFILE_ITEM, UserWsItemData.class);
builder.addDefaultProfile(UserWsQueryParams.PROFILE_DEFAULT, UserWsData.class);
11
2023-10-23 13:47:54+00:00
24k
toel--/ocpp-backend-emulator
src/org/java_websocket/server/WebSocketServer.java
[ { "identifier": "AbstractWebSocket", "path": "src/org/java_websocket/AbstractWebSocket.java", "snippet": "public abstract class AbstractWebSocket extends WebSocketAdapter {\n\n /**\n * Logger instance\n *\n * @since 1.4.0\n */\n private final Logger log = LoggerFactory.getLogger(AbstractWebSoc...
import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.java_websocket.AbstractWebSocket; import org.java_websocket.SocketChannelIOHelper; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketFactory; import org.java_websocket.WebSocketImpl; import org.java_websocket.WebSocketServerFactory; import org.java_websocket.WrappedByteChannel; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.exceptions.WrappedIOException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.Handshakedata; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
19,632
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.server; /** * <tt>WebSocketServer</tt> is an abstract class that only takes care of the * HTTP handshake portion of WebSockets. It's up to a subclass to add functionality/purpose to the * server. */ public abstract class WebSocketServer extends AbstractWebSocket implements Runnable { private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); /** * Logger instance * * @since 1.4.0 */ private final Logger log = LoggerFactory.getLogger(WebSocketServer.class); /** * Holds the list of active WebSocket connections. "Active" means WebSocket handshake is complete * and socket can be written to, or read from. */
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.server; /** * <tt>WebSocketServer</tt> is an abstract class that only takes care of the * HTTP handshake portion of WebSockets. It's up to a subclass to add functionality/purpose to the * server. */ public abstract class WebSocketServer extends AbstractWebSocket implements Runnable { private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); /** * Logger instance * * @since 1.4.0 */ private final Logger log = LoggerFactory.getLogger(WebSocketServer.class); /** * Holds the list of active WebSocket connections. "Active" means WebSocket handshake is complete * and socket can be written to, or read from. */
private final Collection<WebSocket> connections;
2
2023-10-16 23:10:55+00:00
24k
weibocom/rill-flow
rill-flow-dag/olympicene-spring-boot-starter/src/main/java/com/weibo/rill/flow/olympicene/spring/boot/OlympiceneAutoConfiguration.java
[ { "identifier": "Callback", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/event/Callback.java", "snippet": "public interface Callback<T> {\n\n void onEvent(Event<T> event);\n}" }, { "identifier": "TaskCategory", "path": "rill-flow-dag/olympicene-...
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.weibo.rill.flow.olympicene.core.event.Callback; import com.weibo.rill.flow.olympicene.core.model.task.TaskCategory; import com.weibo.rill.flow.olympicene.core.result.DAGResultHandler; import com.weibo.rill.flow.olympicene.core.runtime.DAGContextStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGInfoStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGStorageProcedure; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.olympicene.ddl.parser.DAGStringParser; import com.weibo.rill.flow.olympicene.ddl.serialize.YAMLSerializer; import com.weibo.rill.flow.olympicene.ddl.validation.dag.impl.FlowDAGValidator; import com.weibo.rill.flow.olympicene.ddl.validation.dag.impl.ResourceDAGValidator; import com.weibo.rill.flow.olympicene.spring.boot.exception.OlympicenceStarterException; import com.weibo.rill.flow.olympicene.traversal.DAGOperations; import com.weibo.rill.flow.olympicene.traversal.DAGTraversal; import com.weibo.rill.flow.olympicene.traversal.Olympicene; import com.weibo.rill.flow.olympicene.traversal.callback.DAGCallbackInfo; import com.weibo.rill.flow.olympicene.traversal.checker.DefaultTimeChecker; import com.weibo.rill.flow.olympicene.traversal.checker.TimeChecker; import com.weibo.rill.flow.olympicene.traversal.dispatcher.DAGDispatcher; import com.weibo.rill.flow.olympicene.traversal.helper.*; import com.weibo.rill.flow.olympicene.traversal.mappings.JSONPathInputOutputMapping; import com.weibo.rill.flow.olympicene.traversal.runners.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Map; import java.util.concurrent.ExecutorService;
15,044
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.olympicene.spring.boot; @Slf4j @Configuration @AutoConfigureOrder(Integer.MIN_VALUE) public class OlympiceneAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "dagInfoStorage") public DAGInfoStorage dagInfoStorage() { throw new OlympicenceStarterException("need customized DAGInfoStorage type bean"); } @Bean @ConditionalOnMissingBean(name = "dagContextStorage") public DAGContextStorage dagContextStorage() { throw new OlympicenceStarterException("need customized DAGContextStorage type bean"); } @Bean @ConditionalOnMissingBean(name = "dagStorageProcedure") public DAGStorageProcedure dagStorageProcedure() { throw new OlympicenceStarterException("need customized DAGStorageProcedure type bean"); } @Bean @ConditionalOnMissingBean(name = "dagCallback") public Callback<DAGCallbackInfo> dagCallback() { throw new OlympicenceStarterException("need customized Callback<DAGCallbackInfo> type bean"); } @Bean @ConditionalOnMissingBean(name = "stasher") public Stasher stasher() { return new DefaultStasher(); } @Bean @ConditionalOnMissingBean(name = "popper")
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.olympicene.spring.boot; @Slf4j @Configuration @AutoConfigureOrder(Integer.MIN_VALUE) public class OlympiceneAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "dagInfoStorage") public DAGInfoStorage dagInfoStorage() { throw new OlympicenceStarterException("need customized DAGInfoStorage type bean"); } @Bean @ConditionalOnMissingBean(name = "dagContextStorage") public DAGContextStorage dagContextStorage() { throw new OlympicenceStarterException("need customized DAGContextStorage type bean"); } @Bean @ConditionalOnMissingBean(name = "dagStorageProcedure") public DAGStorageProcedure dagStorageProcedure() { throw new OlympicenceStarterException("need customized DAGStorageProcedure type bean"); } @Bean @ConditionalOnMissingBean(name = "dagCallback") public Callback<DAGCallbackInfo> dagCallback() { throw new OlympicenceStarterException("need customized Callback<DAGCallbackInfo> type bean"); } @Bean @ConditionalOnMissingBean(name = "stasher") public Stasher stasher() { return new DefaultStasher(); } @Bean @ConditionalOnMissingBean(name = "popper")
public Popper popper(@Autowired DAGOperations dagOperations) {
12
2023-11-03 03:46:01+00:00
24k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/activities/profile/SettingsActivity.java
[ { "identifier": "UserDAO", "path": "app/src/main/java/com/daominh/quickmem/data/dao/UserDAO.java", "snippet": "public class UserDAO {\n\n private final QMDatabaseHelper qmDatabaseHelper;\n private SQLiteDatabase sqLiteDatabase;\n\n public UserDAO(Context context) {\n qmDatabaseHelper = n...
import android.app.Dialog; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Toast; import com.daominh.quickmem.R; import com.daominh.quickmem.data.dao.UserDAO; import com.daominh.quickmem.databinding.ActivitySettingsBinding; import com.daominh.quickmem.databinding.DialogChangeEmailBinding; import com.daominh.quickmem.databinding.DialogChangeUsernameBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.auth.signin.SignInActivity; import com.daominh.quickmem.ui.activities.profile.change.ChangeEmailActivity; import com.daominh.quickmem.ui.activities.profile.change.ChangePasswordActivity; import com.daominh.quickmem.ui.activities.profile.change.ChangeUsernameActivity; import com.daominh.quickmem.ui.activities.set.ViewSetActivity; import com.daominh.quickmem.utils.PasswordHasher; import com.saadahmedsoft.popupdialog.PopupDialog; import com.saadahmedsoft.popupdialog.Styles; import com.saadahmedsoft.popupdialog.listener.OnDialogButtonClickListener; import java.util.Objects;
15,275
package com.daominh.quickmem.ui.activities.profile; public class SettingsActivity extends AppCompatActivity { private ActivitySettingsBinding binding; private UserSharePreferences userSharePreferences; private AlertDialog detailDialog; UserDAO userDAO; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivitySettingsBinding.inflate(getLayoutInflater()); final View view = binding.getRoot(); setContentView(view); userSharePreferences = new UserSharePreferences(SettingsActivity.this); binding.usernameTv.setText(userSharePreferences.getUserName()); binding.emailTv.setText(userSharePreferences.getEmail()); onClickItemSetting(); setSupportActionBar(binding.toolbar); binding.toolbar.setNavigationOnClickListener(v -> finish()); } private void onClickItemSetting() { binding.usernameCl.setOnClickListener(view -> openDialogChangeUsername()); binding.emailCl.setOnClickListener(view -> openDialogChangeEmail()); binding.passwordCl.setOnClickListener(view -> {
package com.daominh.quickmem.ui.activities.profile; public class SettingsActivity extends AppCompatActivity { private ActivitySettingsBinding binding; private UserSharePreferences userSharePreferences; private AlertDialog detailDialog; UserDAO userDAO; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivitySettingsBinding.inflate(getLayoutInflater()); final View view = binding.getRoot(); setContentView(view); userSharePreferences = new UserSharePreferences(SettingsActivity.this); binding.usernameTv.setText(userSharePreferences.getUserName()); binding.emailTv.setText(userSharePreferences.getEmail()); onClickItemSetting(); setSupportActionBar(binding.toolbar); binding.toolbar.setNavigationOnClickListener(v -> finish()); } private void onClickItemSetting() { binding.usernameCl.setOnClickListener(view -> openDialogChangeUsername()); binding.emailCl.setOnClickListener(view -> openDialogChangeEmail()); binding.passwordCl.setOnClickListener(view -> {
startActivity(new Intent(SettingsActivity.this, ChangePasswordActivity.class));
4
2023-11-07 16:56:39+00:00
24k
estkme-group/InfiLPA
core/src/main/java/com/infineon/esim/lpa/core/worker/remote/CancelSessionWorker.java
[ { "identifier": "CancelSessionReason", "path": "messages/src/main/java/com/gsma/sgp/messages/rspdefinitions/CancelSessionReason.java", "snippet": "public class CancelSessionReason extends BerInteger {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic CancelSessionReason() {\n\t}\n\n\tpub...
import com.infineon.esim.lpa.core.es9plus.Es9PlusInterface; import com.infineon.esim.util.Log; import com.gsma.sgp.messages.rspdefinitions.CancelSessionReason; import com.gsma.sgp.messages.rspdefinitions.CancelSessionRequest; import com.gsma.sgp.messages.rspdefinitions.CancelSessionRequestEs9; import com.gsma.sgp.messages.rspdefinitions.CancelSessionResponse; import com.gsma.sgp.messages.rspdefinitions.CancelSessionResponseEs9; import com.infineon.esim.lpa.core.dtos.ProfileDownloadSession; import com.infineon.esim.lpa.core.es10.Es10Interface;
14,714
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.worker.remote; public class CancelSessionWorker { private static final String TAG = CancelSessionWorker.class.getName();
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.worker.remote; public class CancelSessionWorker { private static final String TAG = CancelSessionWorker.class.getName();
private final ProfileDownloadSession profileDownloadSession;
5
2023-11-06 02:41:13+00:00
24k
CxyJerry/pilipala
src/main/java/com/jerry/pilipala/domain/vod/service/impl/VodServiceImpl.java
[ { "identifier": "UserInfoBO", "path": "src/main/java/com/jerry/pilipala/application/bo/UserInfoBO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class UserInfoBO {\n private String uid;\n private String roleId;\n private List<String> permissionIdList;\n}" }, { "identifier": ...
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.util.IdUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.jerry.pilipala.application.bo.UserInfoBO; import com.jerry.pilipala.application.dto.PreUploadDTO; import com.jerry.pilipala.application.dto.VideoPostDTO; import com.jerry.pilipala.application.vo.bvod.BVodVO; import com.jerry.pilipala.application.vo.bvod.PreviewBVodVO; import com.jerry.pilipala.application.vo.user.PreviewUserVO; import com.jerry.pilipala.application.vo.vod.*; import com.jerry.pilipala.domain.common.template.MessageTrigger; import com.jerry.pilipala.domain.message.service.MessageService; import com.jerry.pilipala.domain.user.entity.mongo.Permission; import com.jerry.pilipala.domain.user.entity.mongo.User; import com.jerry.pilipala.domain.user.entity.neo4j.UserEntity; import com.jerry.pilipala.domain.user.repository.UserEntityRepository; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.Quality; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.VodDistributeInfo; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionEvent; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionRecord; import com.jerry.pilipala.domain.vod.entity.mongo.statitics.VodStatistics; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.Thumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.VodThumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.vod.BVod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.Vod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodInfo; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodProfiles; import com.jerry.pilipala.domain.vod.entity.neo4j.VodInfoEntity; import com.jerry.pilipala.domain.vod.repository.VodInfoRepository; import com.jerry.pilipala.domain.vod.service.FileService; import com.jerry.pilipala.domain.vod.service.VodService; import com.jerry.pilipala.domain.vod.service.media.UGCSchema; import com.jerry.pilipala.domain.vod.service.media.encoder.Encoder; import com.jerry.pilipala.domain.vod.service.media.profiles.Profile; import com.jerry.pilipala.infrastructure.common.errors.BusinessException; import com.jerry.pilipala.infrastructure.common.response.StandardResponse; import com.jerry.pilipala.infrastructure.enums.ActionStatusEnum; import com.jerry.pilipala.infrastructure.enums.Qn; import com.jerry.pilipala.infrastructure.enums.VodHandleActionEnum; import com.jerry.pilipala.infrastructure.enums.VodStatusEnum; import com.jerry.pilipala.infrastructure.enums.message.TemplateNameEnum; import com.jerry.pilipala.infrastructure.enums.redis.VodCacheKeyEnum; import com.jerry.pilipala.infrastructure.enums.video.Resolution; import com.jerry.pilipala.infrastructure.utils.JsonHelper; import com.jerry.pilipala.infrastructure.utils.Page; import com.jerry.pilipala.infrastructure.utils.SecurityTool; import lombok.extern.slf4j.Slf4j; import net.bramp.ffmpeg.FFmpeg; import net.bramp.ffmpeg.FFmpegExecutor; import net.bramp.ffmpeg.FFprobe; import net.bramp.ffmpeg.builder.FFmpegBuilder; import net.bramp.ffmpeg.builder.FFmpegOutputBuilder; import net.bramp.ffmpeg.probe.FFmpegFormat; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.io.InputStreamResource; import org.springframework.core.task.TaskExecutor; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
14,977
String thumbnailsDirPath = fileService.generateThumbnailsDirPath(vod.getFilename()); String thumbnailsNamePattern = "%s/%s".formatted(thumbnailsDirPath, "%05d.png"); FFmpegOutputBuilder builder = fFmpeg.builder() .setInput(originVideoPath) .overrideOutputFiles(true) .setVideoFilter("fps=0.5,scale=56:32") .addOutput(thumbnailsNamePattern); FFmpegExecutor executor = new FFmpegExecutor(fFmpeg, fFprobe); executor.createJob(builder.done()).run(); Double realDuration = vod.getVideo().getDuration(); int duration = realDuration.intValue(); List<Thumbnails> thumbnails = new ArrayList<>(); for (int i = 0; i <= duration; i += 2) { Thumbnails thumbnailsPng = new Thumbnails(); thumbnailsPng.setTime(i).setUrl("%s/%05d.png".formatted(fileService.filePathRemoveWorkspace(thumbnailsDirPath), i)); thumbnails.add(thumbnailsPng); } // 上传七牛 fileService.uploadDirToOss(thumbnailsDirPath); fileService.deleteDirOfWorkSpace(thumbnailsDirPath); VodThumbnails vodThumbnails = new VodThumbnails() .setCid(cid) .setThumbnails(thumbnails); mongoTemplate.save(vodThumbnails); log.info("cid: {},thumbnails generate completed.", cid); } catch (Exception e) { log.error("缩略图转码失败,cause ", e); log.error("缩略图转码失败"); } }).get(); } catch (Exception e) { log.error("缩略图转码任务失败,", e); } } /** * 视频转码任务 * * @param profile 需要转出的视频规格 * @param vod 稿件素材信息 * @param originFilePath 原始素材文件地址 */ private void transcodeTask(Profile profile, Vod vod, String originFilePath) { Long cid = vod.getCid(); // f2023101502380651aed32d88f9984f5cb2f264e26c85b9/16 String saveTo = profile.getSaveTo(); String outputDir = fileService.generateTranscodeResSaveToPath(saveTo); // 16.mpd String outputFilename = "%s.%s".formatted( profile.getEncoder().quality().getQn(), profile.getFormat().getExt() ); String outputPath = "%s/%s".formatted(outputDir, outputFilename); Encoder encoder = profile.getEncoder(); encoder.fitInput(vod); Resolution resolution = encoder.getResolution(); // ffmpeg -i input.mp4 -c copy -f dash output.mpd FFmpegOutputBuilder builder = fFmpeg.builder() .setInput(originFilePath) .overrideOutputFiles(true) .addOutput(outputPath) .setFormat(profile.getFormat().getValue()) .setAudioCodec(encoder.getAudioCodec()) .setAudioBitRate(encoder.getAudioBitrate()) .setVideoCodec(encoder.getVideoCodec()) .setVideoFrameRate(encoder.getFrameRate()) .setVideoBitRate(encoder.getVideoBitrate()) .setVideoResolution(resolution.getWidth(), resolution.getHeight()) .setStrict(FFmpegBuilder.Strict.EXPERIMENTAL); if (!profile.isEnableAudio()) { builder.disableAudio(); } if (!profile.isEnableVideo()) { builder.disableVideo(); } if (profile.getDuration() > 0) { long duration = Math.min(vod.getVideo().getDuration().longValue(), profile.getDuration()); builder.setDuration(duration, TimeUnit.SECONDS); } FFmpegExecutor executor = new FFmpegExecutor(fFmpeg, fFprobe); executor.createJob(builder.done()).run(); log.info("cid: {}, resolution: {}x{} transcode completed.", cid, resolution.getWidth(), resolution.getHeight()); distribute(cid, vod.getFilename(), profile.getSaveTo(), encoder.quality(), profile.getFormat().getExt()); } /** * 转码后的稿件分发 * * @param cid 稿件唯一ID * @param filename 稿件文件名 * @param saveTo 转码后文件存储目录 * @param qn 清晰度代号 * @param ext 转码后文件拓展名 */ private void distribute(Long cid, String filename, String saveTo, Qn qn, String ext) { String saveToDir = fileService.generateTranscodeResSaveToPath(saveTo); fileService.uploadDirToOss(saveToDir); fileService.deleteDirOfWorkSpace(saveToDir); Query queryDistributeInfo = new Query(Criteria.where("_id").is(cid)); Update update = new Update() .set("filename", filename) .set("ready", false) .set("qualityMap." + qn.getQn() + ".qn", qn.getQn()) .set("qualityMap." + qn.getQn() + ".saveTo", saveTo) .set("qualityMap." + qn.getQn() + ".ext", ext) .set("qualityMap." + qn.getQn() + ".type", "auto");
package com.jerry.pilipala.domain.vod.service.impl; @Slf4j @Service public class VodServiceImpl implements VodService { private final FFprobe fFprobe; private final FFmpeg fFmpeg; private final MongoTemplate mongoTemplate; private final RedisTemplate<String, Object> redisTemplate; private final Snowflake snowflake = IdUtil.getSnowflake(); private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); private final ApplicationEventPublisher applicationEventPublisher; private final UGCSchema ugcSchema; private final TaskExecutor taskExecutor; private final VodInfoRepository vodInfoRepository; private final UserEntityRepository userEntityRepository; private final JsonHelper jsonHelper; private final FileService fileService; private final MessageTrigger messageTrigger; public VodServiceImpl(MongoTemplate mongoTemplate, RedisTemplate<String, Object> redisTemplate, ApplicationEventPublisher applicationEventPublisher, UGCSchema ugcSchema, @Qualifier("asyncServiceExecutor") TaskExecutor taskExecutor, VodInfoRepository vodInfoRepository, UserEntityRepository userEntityRepository, MessageService messageService, JsonHelper jsonHelper, FileService fileService, MessageTrigger messageTrigger1) { this.mongoTemplate = mongoTemplate; this.redisTemplate = redisTemplate; this.applicationEventPublisher = applicationEventPublisher; this.ugcSchema = ugcSchema; this.taskExecutor = taskExecutor; this.vodInfoRepository = vodInfoRepository; this.userEntityRepository = userEntityRepository; this.jsonHelper = jsonHelper; this.fileService = fileService; this.messageTrigger = messageTrigger1; } { try { fFprobe = new FFprobe(); fFmpeg = new FFmpeg(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void ffprobe(String filepath) { try { FFmpegProbeResult probeResult = fFprobe.probe(filepath); FFmpegFormat format = probeResult.getFormat(); System.out.println(probeResult.getStreams()); } catch (IOException e) { throw new RuntimeException(e); } } /** * 生成全局唯一的 filename * * @param preUploadDTO 预上传稿件素材信息 * @return filename */ @Override public String genFilename(PreUploadDTO preUploadDTO) { try { String json = jsonHelper.as(preUploadDTO); String now = DATE_TIME_FORMATTER.format(LocalDateTime.now()); String md5 = SecurityTool.getMd5(json); return "f%s%s".formatted(now, md5); } catch (Exception e) { throw new BusinessException("文件名生成失败", StandardResponse.ERROR); } } /** * 预上传稿件 * * @param preUploadDTO 稿件素材信息 * @return 预上传结果 */ @Override @Transactional(rollbackFor = Exception.class, value = "multiTransactionManager") public PreUploadVO preUpload(PreUploadDTO preUploadDTO) { String bvId = preUploadDTO.getBvId(); String filename = genFilename(preUploadDTO); Long cid = snowflake.nextId(); // 触发初始化开始 applicationEventPublisher.publishEvent(new VodHandleActionEvent(VodHandleActionEnum.PRE_UPLOAD, ActionStatusEnum.init, cid)); BVod bVod; if (StringUtils.isNotBlank(bvId)) { Query query = new Query(Criteria.where("_id").is(bvId)); bVod = mongoTemplate.findOne(query, BVod.class); if (Objects.isNull(bVod)) { throw new BusinessException("bvid 不存在", StandardResponse.ERROR); } } else { bvId = "BV" + UUID.randomUUID().toString().replace("-", "").toUpperCase(); bVod = new BVod() .setBvId(bvId) .setUid((String) StpUtil.getLoginId()) .setCidList(new ArrayList<>()); } mongoTemplate.save(bVod); Vod vod = new Vod() .setCid(cid) .setBvId(bvId) .setFilename(filename) .setContainer(preUploadDTO.getContainer()) .setVideo(preUploadDTO.getVideo()) .setAudio(preUploadDTO.getAudio()) .setExtra(preUploadDTO.getExtra()); mongoTemplate.save(vod); // 触发初始化结束 applicationEventPublisher.publishEvent(new VodHandleActionEvent(VodHandleActionEnum.PRE_UPLOAD, ActionStatusEnum.finished, cid)); return new PreUploadVO().setBvId(bvId).setCid(cid).setFilename(filename); } /** * 投递稿件 * * @param videoPostDTO 稿件信息 */ public void post(VideoPostDTO videoPostDTO) { Query query = new Query(Criteria.where("_id").is(videoPostDTO.getBvId())); BVod bVod = mongoTemplate.findOne(query, BVod.class); if (Objects.isNull(bVod)) { throw new BusinessException("稿件不存在,请重新投稿", StandardResponse.ERROR); } bVod.getCidList().add(videoPostDTO.getCid()); bVod.setReady(true); mongoTemplate.save(bVod); Vod vod = mongoTemplate.findById(videoPostDTO.getCid(), Vod.class); if (Objects.isNull(vod)) { throw BusinessException.businessError("稿件不存在"); } VodInfo vodInfo = new VodInfo(); vodInfo.setBvId(videoPostDTO.getBvId()) .setCid(videoPostDTO.getCid()) .setUid((String) StpUtil.getLoginId()) .setStatus(VodStatusEnum.HANDING) .setCoverUrl(videoPostDTO.getCoverUrl()) .setTitle(videoPostDTO.getTitle()) .setGcType(videoPostDTO.getGcType()) .setPartition(videoPostDTO.getPartition()) .setSubPartition(videoPostDTO.getSubPartition()) .setLabels(videoPostDTO.getLabels()) .setDesc(videoPostDTO.getDesc()) .setDuration(vod.getContainer().getDuration()) .setMtime(System.currentTimeMillis()); mongoTemplate.save(vodInfo); VodHandleActionEvent actionEvent = new VodHandleActionEvent( VodHandleActionEnum.SUBMIT, ActionStatusEnum.finished, videoPostDTO.getCid() ); // 触发提交结束 applicationEventPublisher.publishEvent(actionEvent); // 推送站内信 User author = mongoTemplate.findById(new ObjectId(bVod.getUid()), User.class); if (Objects.isNull(author)) { log.error("消息推送失败,稿件作者信息异常."); return; } Map<String, String> variables = new HashMap<>(); variables.put("username", author.getNickname()); variables.put("title", vodInfo.getTitle()); variables.put("bvid", vodInfo.getBvId()); variables.put("cid", vodInfo.getCid().toString()); messageTrigger.triggerSystemMessage( TemplateNameEnum.POST_VOD_NOTIFY, bVod.getUid(), variables ); } /** * 规划需要转出的视频规格 * * @param cid 稿件唯一ID * @param vod 稿件素材信息 * @return 视频规格列表 * @throws JsonProcessingException 打印视频规格信息时可能产生的序列化异常 */ @Override public List<Profile> schema(Long cid, Vod vod) throws JsonProcessingException { Query query = new Query(Criteria.where("_id").is(cid)); VodProfiles vodProfiles = mongoTemplate.findOne(query, VodProfiles.class); List<Profile> profiles; if (Objects.isNull(vodProfiles)) { profiles = ugcSchema.selectAvProfiles(vod); vodProfiles = new VodProfiles().setCid(cid).setProfiles(profiles).setCompleted(false); mongoTemplate.save(vodProfiles); } else { profiles = vodProfiles.getProfiles(); } log.info("cid [{}] -> select profiles: {}", cid, jsonHelper.as(profiles)); return profiles; } /** * 视频转码 * * @param cid 稿件唯一ID * @throws ExecutionException ffmpeg 执行可能出现的异常 * @throws InterruptedException ffmpeg 执行可能出现的异常 * @throws JsonProcessingException 打印视频规格信息时可能产生的序列化异常 */ @Override public void transcode(Long cid) throws ExecutionException, InterruptedException, JsonProcessingException { Query query = new Query(Criteria.where("_id").is(cid)); Vod vod = mongoTemplate.findOne(query, Vod.class); if (Objects.isNull(vod)) { throw new BusinessException("稿件不存在", StandardResponse.ERROR); } String originFilePath = fileService.downloadVideo(vod.getFilename(), vod.getExt()); // 规划转码规格 List<Profile> profiles = schema(cid, vod); CompletableFuture<?>[] tasks = new CompletableFuture[profiles.size()]; for (int i = 0; i < profiles.size(); i++) { final Profile profile = profiles.get(i); tasks[i] = CompletableFuture.runAsync(() -> transcodeTask(profile, vod, originFilePath), taskExecutor); } CompletableFuture.allOf(tasks).get(); // 转码结束,删除本地临时文件 fileService.deleteVideoOfWorkSpace(vod.getFilename(), vod.getExt()); } /** * 转出缩略图 * * @param cid 稿件唯一ID */ @Override public void transcodeThumbnails(Long cid) { try { CompletableFuture.runAsync(() -> { try { // 每两秒抽一帧 // ffmpeg -i f2023102822062151aed32d88f9984f5cb2f264e26c85b9.mp4 -vf "fps=0.5,scale=56:32" "thumbnails_%05d.png Query query = new Query(Criteria.where("_id").is(cid)); Vod vod = mongoTemplate.findOne(query, Vod.class); if (Objects.isNull(vod)) { throw new BusinessException("稿件不存在", StandardResponse.ERROR); } String originVideoPath = fileService.downloadVideo(vod.getFilename(), vod.getExt()); String thumbnailsDirPath = fileService.generateThumbnailsDirPath(vod.getFilename()); String thumbnailsNamePattern = "%s/%s".formatted(thumbnailsDirPath, "%05d.png"); FFmpegOutputBuilder builder = fFmpeg.builder() .setInput(originVideoPath) .overrideOutputFiles(true) .setVideoFilter("fps=0.5,scale=56:32") .addOutput(thumbnailsNamePattern); FFmpegExecutor executor = new FFmpegExecutor(fFmpeg, fFprobe); executor.createJob(builder.done()).run(); Double realDuration = vod.getVideo().getDuration(); int duration = realDuration.intValue(); List<Thumbnails> thumbnails = new ArrayList<>(); for (int i = 0; i <= duration; i += 2) { Thumbnails thumbnailsPng = new Thumbnails(); thumbnailsPng.setTime(i).setUrl("%s/%05d.png".formatted(fileService.filePathRemoveWorkspace(thumbnailsDirPath), i)); thumbnails.add(thumbnailsPng); } // 上传七牛 fileService.uploadDirToOss(thumbnailsDirPath); fileService.deleteDirOfWorkSpace(thumbnailsDirPath); VodThumbnails vodThumbnails = new VodThumbnails() .setCid(cid) .setThumbnails(thumbnails); mongoTemplate.save(vodThumbnails); log.info("cid: {},thumbnails generate completed.", cid); } catch (Exception e) { log.error("缩略图转码失败,cause ", e); log.error("缩略图转码失败"); } }).get(); } catch (Exception e) { log.error("缩略图转码任务失败,", e); } } /** * 视频转码任务 * * @param profile 需要转出的视频规格 * @param vod 稿件素材信息 * @param originFilePath 原始素材文件地址 */ private void transcodeTask(Profile profile, Vod vod, String originFilePath) { Long cid = vod.getCid(); // f2023101502380651aed32d88f9984f5cb2f264e26c85b9/16 String saveTo = profile.getSaveTo(); String outputDir = fileService.generateTranscodeResSaveToPath(saveTo); // 16.mpd String outputFilename = "%s.%s".formatted( profile.getEncoder().quality().getQn(), profile.getFormat().getExt() ); String outputPath = "%s/%s".formatted(outputDir, outputFilename); Encoder encoder = profile.getEncoder(); encoder.fitInput(vod); Resolution resolution = encoder.getResolution(); // ffmpeg -i input.mp4 -c copy -f dash output.mpd FFmpegOutputBuilder builder = fFmpeg.builder() .setInput(originFilePath) .overrideOutputFiles(true) .addOutput(outputPath) .setFormat(profile.getFormat().getValue()) .setAudioCodec(encoder.getAudioCodec()) .setAudioBitRate(encoder.getAudioBitrate()) .setVideoCodec(encoder.getVideoCodec()) .setVideoFrameRate(encoder.getFrameRate()) .setVideoBitRate(encoder.getVideoBitrate()) .setVideoResolution(resolution.getWidth(), resolution.getHeight()) .setStrict(FFmpegBuilder.Strict.EXPERIMENTAL); if (!profile.isEnableAudio()) { builder.disableAudio(); } if (!profile.isEnableVideo()) { builder.disableVideo(); } if (profile.getDuration() > 0) { long duration = Math.min(vod.getVideo().getDuration().longValue(), profile.getDuration()); builder.setDuration(duration, TimeUnit.SECONDS); } FFmpegExecutor executor = new FFmpegExecutor(fFmpeg, fFprobe); executor.createJob(builder.done()).run(); log.info("cid: {}, resolution: {}x{} transcode completed.", cid, resolution.getWidth(), resolution.getHeight()); distribute(cid, vod.getFilename(), profile.getSaveTo(), encoder.quality(), profile.getFormat().getExt()); } /** * 转码后的稿件分发 * * @param cid 稿件唯一ID * @param filename 稿件文件名 * @param saveTo 转码后文件存储目录 * @param qn 清晰度代号 * @param ext 转码后文件拓展名 */ private void distribute(Long cid, String filename, String saveTo, Qn qn, String ext) { String saveToDir = fileService.generateTranscodeResSaveToPath(saveTo); fileService.uploadDirToOss(saveToDir); fileService.deleteDirOfWorkSpace(saveToDir); Query queryDistributeInfo = new Query(Criteria.where("_id").is(cid)); Update update = new Update() .set("filename", filename) .set("ready", false) .set("qualityMap." + qn.getQn() + ".qn", qn.getQn()) .set("qualityMap." + qn.getQn() + ".saveTo", saveTo) .set("qualityMap." + qn.getQn() + ".ext", ext) .set("qualityMap." + qn.getQn() + ".type", "auto");
mongoTemplate.upsert(queryDistributeInfo, update, VodDistributeInfo.class);
13
2023-11-03 10:05:02+00:00
24k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/test/FakePlayer.java
[ { "identifier": "Main", "path": "Core/src/main/java/org/by1337/bauction/Main.java", "snippet": "public final class Main extends JavaPlugin {\n private static Message message;\n private static Plugin instance;\n private static Config cfg;\n private static FileDataBase storage;\n private Co...
import com.google.common.base.Charsets; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.inventory.ItemStack; import org.by1337.bauction.Main; import org.by1337.bauction.auc.SellItem; import org.by1337.bauction.auc.User; import org.by1337.bauction.db.event.BuyItemEvent; import org.by1337.bauction.db.event.SellItemEvent; import org.by1337.bauction.db.kernel.CSellItem; import org.by1337.bauction.db.kernel.CUser; import org.by1337.bauction.db.kernel.FileDataBase; import java.util.Random; import java.util.UUID;
18,294
package org.by1337.bauction.test; public class FakePlayer { private final Random random = new Random(); private final FileDataBase storage; private UUID uuid; private String nickName; private int ahLimit; public FakePlayer(FileDataBase storage) { this(storage, Integer.MAX_VALUE); } public FakePlayer(FileDataBase core, int ahLimit) { this.ahLimit = ahLimit; this.storage = core; nickName = UUID.randomUUID().toString().substring(30); uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + nickName).getBytes(Charsets.UTF_8)); } public void randomAction() { if (storage.getSellItemsSize() >= ahLimit) { buyItem(); return; } if (random.nextBoolean()) { buyItem(); } else { sellItem(); } } private void buyItem() { if (storage.getSellItemsSize() == 0) return; SellItem item = storage.getFirstSellItem(); User user = storage.getUserOrCreate(nickName, uuid); BuyItemEvent event = new BuyItemEvent(user, item);
package org.by1337.bauction.test; public class FakePlayer { private final Random random = new Random(); private final FileDataBase storage; private UUID uuid; private String nickName; private int ahLimit; public FakePlayer(FileDataBase storage) { this(storage, Integer.MAX_VALUE); } public FakePlayer(FileDataBase core, int ahLimit) { this.ahLimit = ahLimit; this.storage = core; nickName = UUID.randomUUID().toString().substring(30); uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + nickName).getBytes(Charsets.UTF_8)); } public void randomAction() { if (storage.getSellItemsSize() >= ahLimit) { buyItem(); return; } if (random.nextBoolean()) { buyItem(); } else { sellItem(); } } private void buyItem() { if (storage.getSellItemsSize() == 0) return; SellItem item = storage.getFirstSellItem(); User user = storage.getUserOrCreate(nickName, uuid); BuyItemEvent event = new BuyItemEvent(user, item);
Main.getStorage().validateAndRemoveItem(event);
0
2023-11-08 18:25:18+00:00
24k
momentohq/momento-dynamodb-lock-client
src/main/java/com/amazonaws/services/dynamodbv2/MomentoDynamoDBLockClient.java
[ { "identifier": "LockItemUtils", "path": "src/main/java/momento/lock/client/LockItemUtils.java", "snippet": "public class LockItemUtils {\n\n private static final ObjectMapper MAPPER = new ObjectMapper();\n\n public static byte[] serialize(final MomentoLockItem lockItem) {\n try {\n ...
import com.amazonaws.services.dynamodbv2.model.LockCurrentlyUnavailableException; import com.amazonaws.services.dynamodbv2.model.LockNotGrantedException; import com.amazonaws.services.dynamodbv2.util.LockClientUtils; import momento.lock.client.LockItemUtils; import momento.lock.client.LockStorage; import momento.lock.client.MomentoDynamoDBLockClientOptions; import momento.lock.client.MomentoLockClient; import momento.lock.client.MomentoLockClientHeartbeatHandler; import momento.lock.client.MomentoLockItem; import momento.lock.client.NoopDynamoDbClient; import momento.lock.client.model.MomentoClientException; import momento.sdk.CacheClient; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import software.amazon.awssdk.core.exception.SdkClientException; import java.io.Closeable; import java.io.IOException; import java.time.Duration; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Stream;
18,784
/* * This Java source file was generated by the Gradle 'init' task. */ package com.amazonaws.services.dynamodbv2; /** * <p> * Provides a simple library for using DynamoDB's consistent read/write feature to use it for managing distributed locks. * </p> * <p> * In order to use this library, the client must create a cache in Momento, although the library provides a convenience method * for creating that cache (createLockCache.) * </p> * <p> * Here is some example code for how to use the lock client for leader election to work on a resource called "host-2" (it * assumes you already have a Momento cache named lockCache, which can be created with the * {@code createLockCache} helper method): * </p> * <pre> * {@code * AmazonDynamoDBLockClient lockClient = new MomentoDynamoDBLockClient( * MomentoDynamoDBLockClientOptions.builder(dynamoDBClient, "lockTable").build(); * try { * // Attempt to acquire the lock indefinitely, polling Momento every 2 seconds for the lock * LockItem lockItem = lockClient.acquireLock( * AcquireLockOptions.builder("host-2") * .withRefreshPeriod(120L) * .withAdditionalTimeToWaitForLock(Long.MAX_VALUE / 2L) * .withTimeUnit(TimeUnit.MILLISECONDS) * .build()); * if (!lockItem.isExpired()) { * // do business logic, you can call lockItem.isExpired() to periodically check to make sure you still have the lock * // the background thread will keep the lock valid for you by sending heartbeats (default is every 5 seconds) * } * } catch (LockNotGrantedException x) { * // Should only be thrown if the lock could not be acquired for Long.MAX_VALUE / 2L milliseconds. * } * } * </pre> */ public class MomentoDynamoDBLockClient extends AmazonDynamoDBLockClient implements Closeable { private static final Log logger = LogFactory.getLog(MomentoDynamoDBLockClient.class); private final String lockCacheName; private final CacheClient cacheClient; private static final long DEFAULT_BUFFER_MS = 1000; private static final int TTL_GRACE_MILLIS = 200; private final long leaseDurationMillis; private final long heartbeatPeriodInMilliseconds; private final String owner; private final ConcurrentHashMap<String, Thread> sessionMonitors; private final LockStorage lockStorage; private final Function<String, ThreadFactory> namedThreadCreator; private ScheduledExecutorService heartbeatExecutor; private MomentoLockClientHeartbeatHandler heartbeatHandler; private final MomentoLockClient momentoLockClient; private final Boolean holdLockOnServiceUnavailable; private final ScheduledExecutorService executorService;
/* * This Java source file was generated by the Gradle 'init' task. */ package com.amazonaws.services.dynamodbv2; /** * <p> * Provides a simple library for using DynamoDB's consistent read/write feature to use it for managing distributed locks. * </p> * <p> * In order to use this library, the client must create a cache in Momento, although the library provides a convenience method * for creating that cache (createLockCache.) * </p> * <p> * Here is some example code for how to use the lock client for leader election to work on a resource called "host-2" (it * assumes you already have a Momento cache named lockCache, which can be created with the * {@code createLockCache} helper method): * </p> * <pre> * {@code * AmazonDynamoDBLockClient lockClient = new MomentoDynamoDBLockClient( * MomentoDynamoDBLockClientOptions.builder(dynamoDBClient, "lockTable").build(); * try { * // Attempt to acquire the lock indefinitely, polling Momento every 2 seconds for the lock * LockItem lockItem = lockClient.acquireLock( * AcquireLockOptions.builder("host-2") * .withRefreshPeriod(120L) * .withAdditionalTimeToWaitForLock(Long.MAX_VALUE / 2L) * .withTimeUnit(TimeUnit.MILLISECONDS) * .build()); * if (!lockItem.isExpired()) { * // do business logic, you can call lockItem.isExpired() to periodically check to make sure you still have the lock * // the background thread will keep the lock valid for you by sending heartbeats (default is every 5 seconds) * } * } catch (LockNotGrantedException x) { * // Should only be thrown if the lock could not be acquired for Long.MAX_VALUE / 2L milliseconds. * } * } * </pre> */ public class MomentoDynamoDBLockClient extends AmazonDynamoDBLockClient implements Closeable { private static final Log logger = LogFactory.getLog(MomentoDynamoDBLockClient.class); private final String lockCacheName; private final CacheClient cacheClient; private static final long DEFAULT_BUFFER_MS = 1000; private static final int TTL_GRACE_MILLIS = 200; private final long leaseDurationMillis; private final long heartbeatPeriodInMilliseconds; private final String owner; private final ConcurrentHashMap<String, Thread> sessionMonitors; private final LockStorage lockStorage; private final Function<String, ThreadFactory> namedThreadCreator; private ScheduledExecutorService heartbeatExecutor; private MomentoLockClientHeartbeatHandler heartbeatHandler; private final MomentoLockClient momentoLockClient; private final Boolean holdLockOnServiceUnavailable; private final ScheduledExecutorService executorService;
public MomentoDynamoDBLockClient(final MomentoDynamoDBLockClientOptions lockClientOptions) {
2
2023-11-07 03:56:11+00:00
24k
FallenDeity/GameEngine2DJava
src/main/java/engine/scenes/LevelEditorScene.java
[ { "identifier": "Sprite", "path": "src/main/java/engine/components/sprites/Sprite.java", "snippet": "public class Sprite {\n\tprivate Texture texture = null;\n\tprivate float width = 0, height = 0;\n\tprivate Vector2f[] texCoords =\n\t\t\tnew Vector2f[]{\n\t\t\t\t\tnew Vector2f(1, 1), new Vector2f(1, 0)...
import engine.components.*; import engine.components.sprites.Sprite; import engine.components.sprites.SpriteSheet; import engine.editor.JImGui; import engine.physics2d.components.Box2DCollider; import engine.physics2d.components.RigidBody2D; import engine.physics2d.enums.BodyType; import engine.renderer.Sound; import engine.ruby.Window; import engine.util.AssetPool; import engine.util.CONSTANTS; import engine.util.PipeDirection; import engine.util.Prefabs; import imgui.ImGui; import imgui.ImVec2; import org.joml.Vector2f; import java.io.File; import java.util.ArrayList; import java.util.List;
15,736
package engine.scenes; public class LevelEditorScene extends Scene { private final SpriteSheet blocks; private final GameObject editor; public LevelEditorScene() { editor = createGameObject("Editor"); editor.setNotSerializable(); editor.addComponent(new MouseControls()); editor.addComponent(new KeyControls()); editor.addComponent(new GridLines()); editor.addComponent(new EditorCamera(camera)); editor.addComponent(new GizmoSystem(this, editor));
package engine.scenes; public class LevelEditorScene extends Scene { private final SpriteSheet blocks; private final GameObject editor; public LevelEditorScene() { editor = createGameObject("Editor"); editor.setNotSerializable(); editor.addComponent(new MouseControls()); editor.addComponent(new KeyControls()); editor.addComponent(new GridLines()); editor.addComponent(new EditorCamera(camera)); editor.addComponent(new GizmoSystem(this, editor));
blocks = AssetPool.getSpriteSheet(CONSTANTS.BLOCK_SHEET_PATH.getValue(), 16, 16, 0, 81);
9
2023-11-04 13:19:21+00:00
24k
RezaGooner/University-food-ordering
Frames/Admin/Managment/ColorChangeMenu.java
[ { "identifier": "LoginFrame", "path": "Frames/LoginFrame.java", "snippet": "public class LoginFrame extends JFrame {\r\n\r\n public static boolean isNumeric(String str) {\r\n if (str == null || str.length() == 0) {\r\n return false;\r\n }\r\n try {\r\n Long....
import static Classes.Pathes.ClassesPath.*; import static Frames.Admin.Managment.ChangeThemeColor.changeColor; import static Frames.Admin.Managment.ColorChooser.setColor; import static Frames.Profile.ChangePasswordFrame.colorBackground; import static Frames.Profile.ChangePasswordFrame.colorButton; import Frames.LoginFrame; import Frames.Order.UniversitySelfRestaurant; import Frames.Profile.ForgotPassword; import Frames.Profile.NewUserFrame; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
21,041
package Frames.Admin.Managment; /* این کد جاوا یک کلاس است که متد setColor() را دارد. این متد یک پنجره رنگ انتخاب کننده باز می کند و رنگ انتخاب شده توسط کاربر را برمی گرداند. در ابتدا، یک آرایه رشته ای و سه آرایه از integer تعریف می شود. پس از باز شدن پنجره رنگ انتخاب کننده، مقادیر رنگ قرمز، سبز و آبی را از رنگ انتخاب شده به دست می آورد و آنها را در آرایه های integer مربوطه ذخیره می کند. سپس پیامی به کاربر نمایش داده می شود که تغییرات با موفقیت اعمال شده است و رشته ای که شامل مقادیر رنگ است برمی گردانده می شود. در صورتی که کاربر هیچ رنگی را انتخاب نکرده باشد، مقدار null برگردانده می شود. ````````````````````````````````````````````````````` It extends the `JFrame` class and provides a graphical user interface for changing the colors of different frames in a Java Swing application. Here is a breakdown of the code: 1. The code imports various classes from different packages, including `javax.swing` for GUI components and `java.awt` for basic AWT components. 2. The `ColorChangeMenu` class is defined, which extends the `JFrame` class. 3. The constructor of the `ColorChangeMenu` class is defined. It sets up the main frame by setting the title, making it non-resizable, and positioning it at the center of the screen. 4. A `JPanel` named `panel` is created with a grid layout of 5 rows and 1 column. This panel will contain other panels representing different menus. 5. Five panels (`panel1` to `panel5`) are created, each representing a different menu. Each panel has a titled border. 6. Within each panel, there are two buttons and two labels representing the background color and button color of the corresponding frame. The buttons are initially set to the current colors of the frames. When clicked, these buttons open a color chooser dialog (`JColorChooser`) that allows the user to select a new color. 7. The `ColorChangeListener` class is defined as an inner class within `ColorChangeMenu`. This class implements the `ActionListener` interface and is responsible for handling color change events when the buttons are clicked. 8. The `actionPerformed` method of `ColorChangeListener` is implemented to handle the button click events. It opens a color chooser dialog and retrieves the selected color. Then it updates the background color or button color of the corresponding frame, based on which button was clicked. 9. The `main` method is defined, which creates an instance of `ColorChangeMenu` and sets it visible. Overall, this code creates a GUI with multiple panels, each allowing the user to change the colors of different frames in a Java Swing application. */ public class ColorChangeMenu extends JFrame { public ColorChangeMenu() { setTitle("تغییر رنگ منو ها"); setResizable(false); setLocationRelativeTo(null); JPanel panel = new JPanel(new GridLayout(5, 1)); JPanel panel1 = new JPanel (); panel1.setBorder(new TitledBorder(null, "منوی ورود", TitledBorder.LEFT, TitledBorder.TOP)); JButton button12 = new JButton(""); button12.setBackground(LoginFrame.colorBackground); button12.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try {
package Frames.Admin.Managment; /* این کد جاوا یک کلاس است که متد setColor() را دارد. این متد یک پنجره رنگ انتخاب کننده باز می کند و رنگ انتخاب شده توسط کاربر را برمی گرداند. در ابتدا، یک آرایه رشته ای و سه آرایه از integer تعریف می شود. پس از باز شدن پنجره رنگ انتخاب کننده، مقادیر رنگ قرمز، سبز و آبی را از رنگ انتخاب شده به دست می آورد و آنها را در آرایه های integer مربوطه ذخیره می کند. سپس پیامی به کاربر نمایش داده می شود که تغییرات با موفقیت اعمال شده است و رشته ای که شامل مقادیر رنگ است برمی گردانده می شود. در صورتی که کاربر هیچ رنگی را انتخاب نکرده باشد، مقدار null برگردانده می شود. ````````````````````````````````````````````````````` It extends the `JFrame` class and provides a graphical user interface for changing the colors of different frames in a Java Swing application. Here is a breakdown of the code: 1. The code imports various classes from different packages, including `javax.swing` for GUI components and `java.awt` for basic AWT components. 2. The `ColorChangeMenu` class is defined, which extends the `JFrame` class. 3. The constructor of the `ColorChangeMenu` class is defined. It sets up the main frame by setting the title, making it non-resizable, and positioning it at the center of the screen. 4. A `JPanel` named `panel` is created with a grid layout of 5 rows and 1 column. This panel will contain other panels representing different menus. 5. Five panels (`panel1` to `panel5`) are created, each representing a different menu. Each panel has a titled border. 6. Within each panel, there are two buttons and two labels representing the background color and button color of the corresponding frame. The buttons are initially set to the current colors of the frames. When clicked, these buttons open a color chooser dialog (`JColorChooser`) that allows the user to select a new color. 7. The `ColorChangeListener` class is defined as an inner class within `ColorChangeMenu`. This class implements the `ActionListener` interface and is responsible for handling color change events when the buttons are clicked. 8. The `actionPerformed` method of `ColorChangeListener` is implemented to handle the button click events. It opens a color chooser dialog and retrieves the selected color. Then it updates the background color or button color of the corresponding frame, based on which button was clicked. 9. The `main` method is defined, which creates an instance of `ColorChangeMenu` and sets it visible. Overall, this code creates a GUI with multiple panels, each allowing the user to change the colors of different frames in a Java Swing application. */ public class ColorChangeMenu extends JFrame { public ColorChangeMenu() { setTitle("تغییر رنگ منو ها"); setResizable(false); setLocationRelativeTo(null); JPanel panel = new JPanel(new GridLayout(5, 1)); JPanel panel1 = new JPanel (); panel1.setBorder(new TitledBorder(null, "منوی ورود", TitledBorder.LEFT, TitledBorder.TOP)); JButton button12 = new JButton(""); button12.setBackground(LoginFrame.colorBackground); button12.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try {
String Color = setColor();
6
2023-11-03 08:35:22+00:00
24k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/main/KifParser.java
[ { "identifier": "GameAnalyser", "path": "src/main/java/com/chadfield/shogiexplorer/objects/GameAnalyser.java", "snippet": "public class GameAnalyser {\n\n private Process process;\n private OutputStream stdin;\n private BufferedReader bufferedReader;\n private String lastScore = \"\";\n p...
import com.chadfield.shogiexplorer.objects.GameAnalyser; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.LinkedList; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultListModel; import com.chadfield.shogiexplorer.objects.Board; import com.chadfield.shogiexplorer.objects.Board.Turn; import com.chadfield.shogiexplorer.objects.Coordinate; import com.chadfield.shogiexplorer.objects.Game; import com.chadfield.shogiexplorer.objects.Koma; import com.chadfield.shogiexplorer.objects.Notation; import com.chadfield.shogiexplorer.objects.Position; import com.chadfield.shogiexplorer.utils.NotationUtils; import com.chadfield.shogiexplorer.utils.ParserUtils; import com.ibm.icu.text.Transliterator; import java.io.StringReader; import java.nio.charset.Charset; import java.nio.charset.MalformedInputException; import java.nio.charset.StandardCharsets; import java.util.List;
19,672
"lnsgkgsn1/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_BISHOP -> "lnsgkgsnl/1r7/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_ROOK -> "lnsgkgsnl/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_ROOK_LANCE -> "lnsgkgsn1/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_2_PIECE -> "lnsgkgsnl/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_4_PIECE -> "1nsgkgsn1/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_6_PIECE -> "2sgkgs2/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_8_PIECE -> "3gkg3/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; default -> "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1"; }; return SFENParser.parse(sfen); } private static Coordinate parseRegularMove(Board board, String line, DefaultListModel<String> moveListModel, Coordinate lastDestination, LinkedList<Position> positionList) { String[] splitLine = line.trim().split(MULTI_WHITESPACE); int gameNum; try { gameNum = Integer.parseInt(splitLine[0]); } catch (NumberFormatException ex) { positionList.getLast().setComment(positionList.getLast().getComment() + line + "\n"); return lastDestination; } String move = extractRegularMove(splitLine, isSame(line)); Position position = executeMove(board, move, lastDestination); if (position != null) { lastDestination = position.getDestination(); addMoveToMoveList(moveListModel, gameNum, position.getNotation().getJapanese(), board.getNextTurn()); positionList.add(position); } return lastDestination; } private static String extractRegularMove(String[] moveArray, boolean isSame) { String move = moveArray[1]; if (isSame) { move += "\u3000" + moveArray[2]; } return move; } private static void parseGameDetails(String line, Game game) { if (line.startsWith(SENTE)) { game.setSente(line.substring(SENTE.length()).trim()); } if (line.startsWith(GOTE)) { game.setGote(line.substring(GOTE.length()).trim()); } if (line.startsWith(PLACE)) { game.setPlace(line.substring(PLACE.length()).trim()); } if (line.startsWith(HANDICAP)) { game.setHandicap(line.substring(HANDICAP.length()).trim()); } if (line.startsWith(TIME_LIMIT)) { game.setTimeLimit(line.substring(TIME_LIMIT.length()).trim()); } if (line.startsWith(TOURNAMENT)) { game.setTournament(line.substring(TOURNAMENT.length()).trim()); } if (line.startsWith(DATE)) { game.setDate(line.substring(DATE.length()).trim()); } } private static void addMoveToMoveList(DefaultListModel<String> moveListModel, int gameNum, String move, Turn turn) { Transliterator trans = Transliterator.getInstance("Halfwidth-Fullwidth"); if (turn == Turn.SENTE) { moveListModel.addElement(gameNum + trans.transliterate(" ☖" + move)); } else { moveListModel.addElement(gameNum + trans.transliterate(" ☗" + move)); } } private static Notation getNotation(Coordinate thisSource, Coordinate thisDestination, boolean same, String move, String piece, String disambiguation) { String engineMove = ""; try { engineMove = getEngineMoveCoordinate(thisSource) + getEngineMoveCoordinate(thisDestination); if (isPromoted(move)) { engineMove += "+"; } } catch (Exception ex) { Logger.getLogger(GameAnalyser.class.getName()).log(Level.SEVERE, null, ex); } Notation notation = new Notation(); notation.setEngineMove(engineMove); String japanese = ""; if (same) { japanese += NotationUtils.SAME + piece; } else { japanese += NotationUtils.getJapaneseCoordinate(thisDestination) + piece + disambiguation; } if (isPromoted(move)) { japanese += NotationUtils.PROMOTED; } notation.setJapanese(japanese); return notation; } private static Notation executeRegularMove(Board board, Coordinate thisDestination, Coordinate thisSource, Coordinate lastDestination, String move) { Koma destinationKoma = getKoma(board, thisDestination); if (destinationKoma != null) {
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.main; public class KifParser { private static final String DATE = "開始日時:"; private static final String PLACE = "場所:"; private static final String TIME_LIMIT = "持ち時間:"; private static final String TOURNAMENT = "棋戦:"; private static final String SENTE = "先手:"; private static final String GOTE = "後手:"; private static final String MOVE_HEADER = "手数----指手---------消費時間-"; private static final String MULTI_WHITESPACE = "\\s+|\\u3000"; private static final String HANDICAP = "手合割:"; private KifParser() { throw new IllegalStateException("Utility class"); } public static Game parseKif(DefaultListModel<String> moveListModel, File kifFile, String clipboardStr, boolean shiftFile, List<List<Position>> analysisPositionList) throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("Bundle"); moveListModel.clear(); moveListModel.addElement(bundle.getString("label_start_position")); Board board = null; Game game = new Game(); game.setAnalysisPositionList(analysisPositionList); LinkedList<Position> positionList = new LinkedList<>(); boolean foundHeader = false; BufferedReader fileReader = null; try { if (clipboardStr == null) { if (shiftFile) { fileReader = Files.newBufferedReader(kifFile.toPath(), Charset.forName("SJIS")); } else { fileReader = Files.newBufferedReader(kifFile.toPath(), StandardCharsets.UTF_8); } } else { fileReader = new BufferedReader(new StringReader(clipboardStr)); } int count = 1; String line; Coordinate lastDestination = null; while ((line = fileReader.readLine()) != null) { if (!foundHeader) { foundHeader = isHeader(line); if (foundHeader || isComment(line)) { continue; } parseGameDetails(line, game); } else { if (board == null) { board = getStartBoard(game); positionList.add(new Position(SFENParser.getSFEN(board), null, null, new Notation())); } if (line.isEmpty()) { break; } if (isComment(line)) { positionList.getLast().setComment(positionList.getLast().getComment() + line.substring(1) + "\n"); continue; } if (!isRegularMove(line)) { break; } count++; board.setMoveCount(count); lastDestination = parseRegularMove(board, line, moveListModel, lastDestination, positionList); } } } catch (MalformedInputException ex) { return null; } finally { if (fileReader != null) { fileReader.close(); } } game.setPositionList(positionList); return game; } private static Board getStartBoard(Game game) { String sfen; sfen = switch (game.getHandicap()) { case Game.HANDICAP_LANCE -> "lnsgkgsn1/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_BISHOP -> "lnsgkgsnl/1r7/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_ROOK -> "lnsgkgsnl/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_ROOK_LANCE -> "lnsgkgsn1/7b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_2_PIECE -> "lnsgkgsnl/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_4_PIECE -> "1nsgkgsn1/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_6_PIECE -> "2sgkgs2/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; case Game.HANDICAP_8_PIECE -> "3gkg3/9/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL w - 1"; default -> "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1"; }; return SFENParser.parse(sfen); } private static Coordinate parseRegularMove(Board board, String line, DefaultListModel<String> moveListModel, Coordinate lastDestination, LinkedList<Position> positionList) { String[] splitLine = line.trim().split(MULTI_WHITESPACE); int gameNum; try { gameNum = Integer.parseInt(splitLine[0]); } catch (NumberFormatException ex) { positionList.getLast().setComment(positionList.getLast().getComment() + line + "\n"); return lastDestination; } String move = extractRegularMove(splitLine, isSame(line)); Position position = executeMove(board, move, lastDestination); if (position != null) { lastDestination = position.getDestination(); addMoveToMoveList(moveListModel, gameNum, position.getNotation().getJapanese(), board.getNextTurn()); positionList.add(position); } return lastDestination; } private static String extractRegularMove(String[] moveArray, boolean isSame) { String move = moveArray[1]; if (isSame) { move += "\u3000" + moveArray[2]; } return move; } private static void parseGameDetails(String line, Game game) { if (line.startsWith(SENTE)) { game.setSente(line.substring(SENTE.length()).trim()); } if (line.startsWith(GOTE)) { game.setGote(line.substring(GOTE.length()).trim()); } if (line.startsWith(PLACE)) { game.setPlace(line.substring(PLACE.length()).trim()); } if (line.startsWith(HANDICAP)) { game.setHandicap(line.substring(HANDICAP.length()).trim()); } if (line.startsWith(TIME_LIMIT)) { game.setTimeLimit(line.substring(TIME_LIMIT.length()).trim()); } if (line.startsWith(TOURNAMENT)) { game.setTournament(line.substring(TOURNAMENT.length()).trim()); } if (line.startsWith(DATE)) { game.setDate(line.substring(DATE.length()).trim()); } } private static void addMoveToMoveList(DefaultListModel<String> moveListModel, int gameNum, String move, Turn turn) { Transliterator trans = Transliterator.getInstance("Halfwidth-Fullwidth"); if (turn == Turn.SENTE) { moveListModel.addElement(gameNum + trans.transliterate(" ☖" + move)); } else { moveListModel.addElement(gameNum + trans.transliterate(" ☗" + move)); } } private static Notation getNotation(Coordinate thisSource, Coordinate thisDestination, boolean same, String move, String piece, String disambiguation) { String engineMove = ""; try { engineMove = getEngineMoveCoordinate(thisSource) + getEngineMoveCoordinate(thisDestination); if (isPromoted(move)) { engineMove += "+"; } } catch (Exception ex) { Logger.getLogger(GameAnalyser.class.getName()).log(Level.SEVERE, null, ex); } Notation notation = new Notation(); notation.setEngineMove(engineMove); String japanese = ""; if (same) { japanese += NotationUtils.SAME + piece; } else { japanese += NotationUtils.getJapaneseCoordinate(thisDestination) + piece + disambiguation; } if (isPromoted(move)) { japanese += NotationUtils.PROMOTED; } notation.setJapanese(japanese); return notation; } private static Notation executeRegularMove(Board board, Coordinate thisDestination, Coordinate thisSource, Coordinate lastDestination, String move) { Koma destinationKoma = getKoma(board, thisDestination); if (destinationKoma != null) {
ParserUtils.addPieceToInHand(getKoma(board, thisDestination), board);
9
2023-11-08 09:24:57+00:00
24k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/SysUserServiceImpl.java
[ { "identifier": "LoginAboutAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/LoginAboutAdapt.java", "snippet": "public class LoginAboutAdapt {\n\n public static final int USE_NAME_LENGTH = 8;\n\n /**\n * 构造token信息类\n *\n * @param saTokenInfo s...
import cn.dev33.satoken.secure.SaSecureUtil; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.codec.Base64; import cn.hutool.core.util.RandomUtil; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.provider.StaticCredentialProvider; import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient; import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest; import com.google.code.kaptcha.Producer; import com.qingmeng.config.adapt.LoginAboutAdapt; import com.qingmeng.config.adapt.UserInfoAdapt; import com.qingmeng.config.adapt.UserSettingAdapt; import com.qingmeng.config.cache.UserCache; import com.qingmeng.config.cache.UserFriendSettingCache; import com.qingmeng.config.cache.UserSettingCache; import com.qingmeng.constant.RedisConstant; import com.qingmeng.constant.SystemConstant; import com.qingmeng.dao.*; import com.qingmeng.dto.login.CheckFriendDTO; import com.qingmeng.dto.login.LoginParamDTO; import com.qingmeng.dto.login.RegisterDTO; import com.qingmeng.dto.user.AlterAccountDTO; import com.qingmeng.dto.user.AlterPersonalInfoDTO; import com.qingmeng.dto.user.PersonalPrivacySettingDTO; import com.qingmeng.entity.ChatFriendRoom; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserFriendSetting; import com.qingmeng.entity.SysUserPrivacySetting; import com.qingmeng.enums.user.LoginMethodEnum; import com.qingmeng.config.event.SysUserRegisterEvent; import com.qingmeng.exception.TalkTimeException; import com.qingmeng.service.SysUserFriendService; import com.qingmeng.service.SysUserService; import com.qingmeng.config.strategy.login.LoginFactory; import com.qingmeng.config.strategy.login.LoginStrategy; import com.qingmeng.utils.*; import com.qingmeng.vo.login.CaptchaVO; import com.qingmeng.vo.login.TokenInfoVO; import com.qingmeng.vo.user.*; import darabonba.core.client.ClientOverrideConfiguration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.FastByteArrayOutputStream; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit;
14,787
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:19:00 */ @Service public class SysUserServiceImpl implements SysUserService { public static final String MATH = "math"; public static final String CHAR = "char"; @Value("${alibaba.sms.accessKeyId}") private String aliAccessKeyId; @Value("${alibaba.sms.accessKeySecret}") private String aliAccessKeySecret; @Resource @Lazy private LoginFactory loginFactory; @Resource(name = "captchaProducer") private Producer captchaProducer; @Resource(name = "captchaProducerMath") private Producer captchaProducerMath; @Resource private SysUserDao sysUserDao; @Resource private ApplicationEventPublisher applicationEventPublisher; @Resource private UserCache userCache; @Resource private SysUserPrivacySettingDao sysUserPrivacySettingDao; @Resource private SysUserFriendDao sysUserFriendDao; @Resource
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:19:00 */ @Service public class SysUserServiceImpl implements SysUserService { public static final String MATH = "math"; public static final String CHAR = "char"; @Value("${alibaba.sms.accessKeyId}") private String aliAccessKeyId; @Value("${alibaba.sms.accessKeySecret}") private String aliAccessKeySecret; @Resource @Lazy private LoginFactory loginFactory; @Resource(name = "captchaProducer") private Producer captchaProducer; @Resource(name = "captchaProducerMath") private Producer captchaProducerMath; @Resource private SysUserDao sysUserDao; @Resource private ApplicationEventPublisher applicationEventPublisher; @Resource private UserCache userCache; @Resource private SysUserPrivacySettingDao sysUserPrivacySettingDao; @Resource private SysUserFriendDao sysUserFriendDao; @Resource
private UserFriendSettingCache userFriendSettingCache;
4
2023-11-07 16:04:55+00:00
24k
Griefed/AddEmAll
common/src/main/java/de/griefed/addemall/block/GeneratedModBlocks.java
[ { "identifier": "Constants", "path": "common/src/main/java/de/griefed/addemall/Constants.java", "snippet": "public class Constants {\n\n\tpublic static final String MOD_ID = \"addemall\";\n\tpublic static final String MOD_NAME = \"AddEmAll\";\n\tpublic static final Logger LOG = LoggerFactory.getLogger(M...
import de.griefed.addemall.Constants; import de.griefed.addemall.platform.Services; import de.griefed.addemall.registry.RegistrationProvider; import de.griefed.addemall.registry.RegistryObject; import net.minecraft.core.Registry; import net.minecraft.world.item.*; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SlabBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.StairBlock; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.material.Material;
17,814
package de.griefed.addemall.block; @SuppressWarnings("unused") public class GeneratedModBlocks { public static final RegistrationProvider<Block> BLOCKS = RegistrationProvider.get(Registry.BLOCK_REGISTRY, Constants.MOD_ID); public static final RegistrationProvider<Item> ITEMS = RegistrationProvider.get(Registry.ITEM_REGISTRY, Constants.MOD_ID); /*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###*/ public static final RegistryObject<Block> GREEN_ZEN = BLOCKS.register("generated/dirt/green_zen_block", () -> new Block(BlockBehaviour.Properties.of(Material.DIRT).sound(SoundType.GRASS).strength(2f, 2f).lightLevel(state -> 4).explosionResistance(0f))); public static final RegistryObject<Item> GREEN_ZEN_ITEM = ITEMS.register("generated/dirt/green_zen", () -> new BlockItem(GREEN_ZEN.get(), itemBuilder())); public static final RegistryObject<Block> GREEN_ZEN_SLAB = BLOCKS.register("generated/dirt/green_zen_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(GREEN_ZEN.get()))); public static final RegistryObject<Item> GREEN_ZEN_SLAB_ITEM = ITEMS.register("generated/dirt/green_zen_slab", () -> new BlockItem(GREEN_ZEN_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> GREEN_ZEN_STAIRS = BLOCKS.register("generated/dirt/green_zen_stairs", () -> new ModStairs(GREEN_ZEN.get().defaultBlockState(), BlockBehaviour.Properties.copy(GREEN_ZEN.get()))); public static final RegistryObject<Item> GREEN_ZEN_STAIRS_ITEM = ITEMS.register("generated/dirt/green_zen_stairs", () -> new BlockItem(GREEN_ZEN_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> YELLOW_ZEN = BLOCKS.register("generated/dirt/yellow_zen_block", () -> new Block(BlockBehaviour.Properties.of(Material.DIRT).sound(SoundType.GRASS).strength(2f, 2f).lightLevel(state -> 4).explosionResistance(0f))); public static final RegistryObject<Item> YELLOW_ZEN_ITEM = ITEMS.register("generated/dirt/yellow_zen", () -> new BlockItem(YELLOW_ZEN.get(), itemBuilder())); public static final RegistryObject<Block> YELLOW_ZEN_SLAB = BLOCKS.register("generated/dirt/yellow_zen_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(YELLOW_ZEN.get()))); public static final RegistryObject<Item> YELLOW_ZEN_SLAB_ITEM = ITEMS.register("generated/dirt/yellow_zen_slab", () -> new BlockItem(YELLOW_ZEN_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> YELLOW_ZEN_STAIRS = BLOCKS.register("generated/dirt/yellow_zen_stairs", () -> new ModStairs(YELLOW_ZEN.get().defaultBlockState(), BlockBehaviour.Properties.copy(YELLOW_ZEN.get()))); public static final RegistryObject<Item> YELLOW_ZEN_STAIRS_ITEM = ITEMS.register("generated/dirt/yellow_zen_stairs", () -> new BlockItem(YELLOW_ZEN_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> BLUE_ZEN = BLOCKS.register("generated/dirt/blue_zen_block", () -> new Block(BlockBehaviour.Properties.of(Material.DIRT).sound(SoundType.GRASS).strength(2f, 2f).lightLevel(state -> 4).explosionResistance(0f))); public static final RegistryObject<Item> BLUE_ZEN_ITEM = ITEMS.register("generated/dirt/blue_zen", () -> new BlockItem(BLUE_ZEN.get(), itemBuilder())); public static final RegistryObject<Block> BLUE_ZEN_SLAB = BLOCKS.register("generated/dirt/blue_zen_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(BLUE_ZEN.get()))); public static final RegistryObject<Item> BLUE_ZEN_SLAB_ITEM = ITEMS.register("generated/dirt/blue_zen_slab", () -> new BlockItem(BLUE_ZEN_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> BLUE_ZEN_STAIRS = BLOCKS.register("generated/dirt/blue_zen_stairs", () -> new ModStairs(BLUE_ZEN.get().defaultBlockState(), BlockBehaviour.Properties.copy(BLUE_ZEN.get()))); public static final RegistryObject<Item> BLUE_ZEN_STAIRS_ITEM = ITEMS.register("generated/dirt/blue_zen_stairs", () -> new BlockItem(BLUE_ZEN_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> BROWN_ZEN = BLOCKS.register("generated/dirt/brown_zen_block", () -> new Block(BlockBehaviour.Properties.of(Material.DIRT).sound(SoundType.GRASS).strength(2f, 2f).lightLevel(state -> 4).explosionResistance(0f))); public static final RegistryObject<Item> BROWN_ZEN_ITEM = ITEMS.register("generated/dirt/brown_zen", () -> new BlockItem(BROWN_ZEN.get(), itemBuilder())); public static final RegistryObject<Block> BROWN_ZEN_SLAB = BLOCKS.register("generated/dirt/brown_zen_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(BROWN_ZEN.get()))); public static final RegistryObject<Item> BROWN_ZEN_SLAB_ITEM = ITEMS.register("generated/dirt/brown_zen_slab", () -> new BlockItem(BROWN_ZEN_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> BROWN_ZEN_STAIRS = BLOCKS.register("generated/dirt/brown_zen_stairs", () -> new ModStairs(BROWN_ZEN.get().defaultBlockState(), BlockBehaviour.Properties.copy(BROWN_ZEN.get()))); public static final RegistryObject<Item> BROWN_ZEN_STAIRS_ITEM = ITEMS.register("generated/dirt/brown_zen_stairs", () -> new BlockItem(BROWN_ZEN_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> RED_ZEN = BLOCKS.register("generated/dirt/red_zen_block", () -> new Block(BlockBehaviour.Properties.of(Material.DIRT).sound(SoundType.GRASS).strength(2f, 2f).lightLevel(state -> 4).explosionResistance(0f))); public static final RegistryObject<Item> RED_ZEN_ITEM = ITEMS.register("generated/dirt/red_zen", () -> new BlockItem(RED_ZEN.get(), itemBuilder())); public static final RegistryObject<Block> RED_ZEN_SLAB = BLOCKS.register("generated/dirt/red_zen_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(RED_ZEN.get()))); public static final RegistryObject<Item> RED_ZEN_SLAB_ITEM = ITEMS.register("generated/dirt/red_zen_slab", () -> new BlockItem(RED_ZEN_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> RED_ZEN_STAIRS = BLOCKS.register("generated/dirt/red_zen_stairs", () -> new ModStairs(RED_ZEN.get().defaultBlockState(), BlockBehaviour.Properties.copy(RED_ZEN.get()))); public static final RegistryObject<Item> RED_ZEN_STAIRS_ITEM = ITEMS.register("generated/dirt/red_zen_stairs", () -> new BlockItem(RED_ZEN_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_1 = BLOCKS.register("generated/metal/metal_floor_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_1_ITEM = ITEMS.register("generated/metal/metal_floor_1", () -> new BlockItem(METAL_FLOOR_1.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_1_SLAB = BLOCKS.register("generated/metal/metal_floor_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_1.get()))); public static final RegistryObject<Item> METAL_FLOOR_1_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_1_slab", () -> new BlockItem(METAL_FLOOR_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_1_STAIRS = BLOCKS.register("generated/metal/metal_floor_1_stairs", () -> new ModStairs(METAL_FLOOR_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_1.get()))); public static final RegistryObject<Item> METAL_FLOOR_1_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_1_stairs", () -> new BlockItem(METAL_FLOOR_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_2 = BLOCKS.register("generated/metal/metal_floor_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_2_ITEM = ITEMS.register("generated/metal/metal_floor_2", () -> new BlockItem(METAL_FLOOR_2.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_2_SLAB = BLOCKS.register("generated/metal/metal_floor_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_2.get()))); public static final RegistryObject<Item> METAL_FLOOR_2_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_2_slab", () -> new BlockItem(METAL_FLOOR_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_2_STAIRS = BLOCKS.register("generated/metal/metal_floor_2_stairs", () -> new ModStairs(METAL_FLOOR_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_2.get()))); public static final RegistryObject<Item> METAL_FLOOR_2_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_2_stairs", () -> new BlockItem(METAL_FLOOR_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_3 = BLOCKS.register("generated/metal/metal_floor_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_3_ITEM = ITEMS.register("generated/metal/metal_floor_3", () -> new BlockItem(METAL_FLOOR_3.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_3_SLAB = BLOCKS.register("generated/metal/metal_floor_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_3.get()))); public static final RegistryObject<Item> METAL_FLOOR_3_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_3_slab", () -> new BlockItem(METAL_FLOOR_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_3_STAIRS = BLOCKS.register("generated/metal/metal_floor_3_stairs", () -> new ModStairs(METAL_FLOOR_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_3.get()))); public static final RegistryObject<Item> METAL_FLOOR_3_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_3_stairs", () -> new BlockItem(METAL_FLOOR_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_4 = BLOCKS.register("generated/metal/metal_floor_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_4_ITEM = ITEMS.register("generated/metal/metal_floor_4", () -> new BlockItem(METAL_FLOOR_4.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_4_SLAB = BLOCKS.register("generated/metal/metal_floor_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_4.get()))); public static final RegistryObject<Item> METAL_FLOOR_4_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_4_slab", () -> new BlockItem(METAL_FLOOR_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_4_STAIRS = BLOCKS.register("generated/metal/metal_floor_4_stairs", () -> new ModStairs(METAL_FLOOR_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_4.get()))); public static final RegistryObject<Item> METAL_FLOOR_4_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_4_stairs", () -> new BlockItem(METAL_FLOOR_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_5 = BLOCKS.register("generated/metal/metal_floor_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_5_ITEM = ITEMS.register("generated/metal/metal_floor_5", () -> new BlockItem(METAL_FLOOR_5.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_5_SLAB = BLOCKS.register("generated/metal/metal_floor_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_5.get()))); public static final RegistryObject<Item> METAL_FLOOR_5_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_5_slab", () -> new BlockItem(METAL_FLOOR_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_5_STAIRS = BLOCKS.register("generated/metal/metal_floor_5_stairs", () -> new ModStairs(METAL_FLOOR_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_5.get()))); public static final RegistryObject<Item> METAL_FLOOR_5_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_5_stairs", () -> new BlockItem(METAL_FLOOR_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_6 = BLOCKS.register("generated/metal/metal_floor_6_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_6_ITEM = ITEMS.register("generated/metal/metal_floor_6", () -> new BlockItem(METAL_FLOOR_6.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_6_SLAB = BLOCKS.register("generated/metal/metal_floor_6_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_6.get()))); public static final RegistryObject<Item> METAL_FLOOR_6_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_6_slab", () -> new BlockItem(METAL_FLOOR_6_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_6_STAIRS = BLOCKS.register("generated/metal/metal_floor_6_stairs", () -> new ModStairs(METAL_FLOOR_6.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_6.get()))); public static final RegistryObject<Item> METAL_FLOOR_6_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_6_stairs", () -> new BlockItem(METAL_FLOOR_6_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_1 = BLOCKS.register("generated/metal/metal_plating_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_PLATING_1_ITEM = ITEMS.register("generated/metal/metal_plating_1", () -> new BlockItem(METAL_PLATING_1.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_1_SLAB = BLOCKS.register("generated/metal/metal_plating_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_PLATING_1.get()))); public static final RegistryObject<Item> METAL_PLATING_1_SLAB_ITEM = ITEMS.register("generated/metal/metal_plating_1_slab", () -> new BlockItem(METAL_PLATING_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_1_STAIRS = BLOCKS.register("generated/metal/metal_plating_1_stairs", () -> new ModStairs(METAL_PLATING_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_PLATING_1.get()))); public static final RegistryObject<Item> METAL_PLATING_1_STAIRS_ITEM = ITEMS.register("generated/metal/metal_plating_1_stairs", () -> new BlockItem(METAL_PLATING_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_2 = BLOCKS.register("generated/metal/metal_plating_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_PLATING_2_ITEM = ITEMS.register("generated/metal/metal_plating_2", () -> new BlockItem(METAL_PLATING_2.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_2_SLAB = BLOCKS.register("generated/metal/metal_plating_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_PLATING_2.get()))); public static final RegistryObject<Item> METAL_PLATING_2_SLAB_ITEM = ITEMS.register("generated/metal/metal_plating_2_slab", () -> new BlockItem(METAL_PLATING_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_2_STAIRS = BLOCKS.register("generated/metal/metal_plating_2_stairs", () -> new ModStairs(METAL_PLATING_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_PLATING_2.get()))); public static final RegistryObject<Item> METAL_PLATING_2_STAIRS_ITEM = ITEMS.register("generated/metal/metal_plating_2_stairs", () -> new BlockItem(METAL_PLATING_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_3 = BLOCKS.register("generated/metal/metal_plating_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_PLATING_3_ITEM = ITEMS.register("generated/metal/metal_plating_3", () -> new BlockItem(METAL_PLATING_3.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_3_SLAB = BLOCKS.register("generated/metal/metal_plating_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_PLATING_3.get()))); public static final RegistryObject<Item> METAL_PLATING_3_SLAB_ITEM = ITEMS.register("generated/metal/metal_plating_3_slab", () -> new BlockItem(METAL_PLATING_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_3_STAIRS = BLOCKS.register("generated/metal/metal_plating_3_stairs", () -> new ModStairs(METAL_PLATING_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_PLATING_3.get()))); public static final RegistryObject<Item> METAL_PLATING_3_STAIRS_ITEM = ITEMS.register("generated/metal/metal_plating_3_stairs", () -> new BlockItem(METAL_PLATING_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_4 = BLOCKS.register("generated/metal/metal_plating_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_PLATING_4_ITEM = ITEMS.register("generated/metal/metal_plating_4", () -> new BlockItem(METAL_PLATING_4.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_4_SLAB = BLOCKS.register("generated/metal/metal_plating_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_PLATING_4.get()))); public static final RegistryObject<Item> METAL_PLATING_4_SLAB_ITEM = ITEMS.register("generated/metal/metal_plating_4_slab", () -> new BlockItem(METAL_PLATING_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_4_STAIRS = BLOCKS.register("generated/metal/metal_plating_4_stairs", () -> new ModStairs(METAL_PLATING_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_PLATING_4.get()))); public static final RegistryObject<Item> METAL_PLATING_4_STAIRS_ITEM = ITEMS.register("generated/metal/metal_plating_4_stairs", () -> new BlockItem(METAL_PLATING_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_5 = BLOCKS.register("generated/metal/metal_plating_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_PLATING_5_ITEM = ITEMS.register("generated/metal/metal_plating_5", () -> new BlockItem(METAL_PLATING_5.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_5_SLAB = BLOCKS.register("generated/metal/metal_plating_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_PLATING_5.get()))); public static final RegistryObject<Item> METAL_PLATING_5_SLAB_ITEM = ITEMS.register("generated/metal/metal_plating_5_slab", () -> new BlockItem(METAL_PLATING_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_5_STAIRS = BLOCKS.register("generated/metal/metal_plating_5_stairs", () -> new ModStairs(METAL_PLATING_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_PLATING_5.get()))); public static final RegistryObject<Item> METAL_PLATING_5_STAIRS_ITEM = ITEMS.register("generated/metal/metal_plating_5_stairs", () -> new BlockItem(METAL_PLATING_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_1 = BLOCKS.register("generated/metal/metal_roof_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_ROOF_1_ITEM = ITEMS.register("generated/metal/metal_roof_1", () -> new BlockItem(METAL_ROOF_1.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_1_SLAB = BLOCKS.register("generated/metal/metal_roof_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_ROOF_1.get()))); public static final RegistryObject<Item> METAL_ROOF_1_SLAB_ITEM = ITEMS.register("generated/metal/metal_roof_1_slab", () -> new BlockItem(METAL_ROOF_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_1_STAIRS = BLOCKS.register("generated/metal/metal_roof_1_stairs", () -> new ModStairs(METAL_ROOF_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_ROOF_1.get()))); public static final RegistryObject<Item> METAL_ROOF_1_STAIRS_ITEM = ITEMS.register("generated/metal/metal_roof_1_stairs", () -> new BlockItem(METAL_ROOF_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_2 = BLOCKS.register("generated/metal/metal_roof_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_ROOF_2_ITEM = ITEMS.register("generated/metal/metal_roof_2", () -> new BlockItem(METAL_ROOF_2.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_2_SLAB = BLOCKS.register("generated/metal/metal_roof_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_ROOF_2.get()))); public static final RegistryObject<Item> METAL_ROOF_2_SLAB_ITEM = ITEMS.register("generated/metal/metal_roof_2_slab", () -> new BlockItem(METAL_ROOF_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_2_STAIRS = BLOCKS.register("generated/metal/metal_roof_2_stairs", () -> new ModStairs(METAL_ROOF_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_ROOF_2.get()))); public static final RegistryObject<Item> METAL_ROOF_2_STAIRS_ITEM = ITEMS.register("generated/metal/metal_roof_2_stairs", () -> new BlockItem(METAL_ROOF_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_3 = BLOCKS.register("generated/metal/metal_roof_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_ROOF_3_ITEM = ITEMS.register("generated/metal/metal_roof_3", () -> new BlockItem(METAL_ROOF_3.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_3_SLAB = BLOCKS.register("generated/metal/metal_roof_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_ROOF_3.get()))); public static final RegistryObject<Item> METAL_ROOF_3_SLAB_ITEM = ITEMS.register("generated/metal/metal_roof_3_slab", () -> new BlockItem(METAL_ROOF_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_3_STAIRS = BLOCKS.register("generated/metal/metal_roof_3_stairs", () -> new ModStairs(METAL_ROOF_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_ROOF_3.get()))); public static final RegistryObject<Item> METAL_ROOF_3_STAIRS_ITEM = ITEMS.register("generated/metal/metal_roof_3_stairs", () -> new BlockItem(METAL_ROOF_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_4 = BLOCKS.register("generated/metal/metal_roof_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_ROOF_4_ITEM = ITEMS.register("generated/metal/metal_roof_4", () -> new BlockItem(METAL_ROOF_4.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_4_SLAB = BLOCKS.register("generated/metal/metal_roof_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_ROOF_4.get()))); public static final RegistryObject<Item> METAL_ROOF_4_SLAB_ITEM = ITEMS.register("generated/metal/metal_roof_4_slab", () -> new BlockItem(METAL_ROOF_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_4_STAIRS = BLOCKS.register("generated/metal/metal_roof_4_stairs", () -> new ModStairs(METAL_ROOF_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_ROOF_4.get()))); public static final RegistryObject<Item> METAL_ROOF_4_STAIRS_ITEM = ITEMS.register("generated/metal/metal_roof_4_stairs", () -> new BlockItem(METAL_ROOF_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_5 = BLOCKS.register("generated/metal/metal_roof_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_ROOF_5_ITEM = ITEMS.register("generated/metal/metal_roof_5", () -> new BlockItem(METAL_ROOF_5.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_5_SLAB = BLOCKS.register("generated/metal/metal_roof_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_ROOF_5.get()))); public static final RegistryObject<Item> METAL_ROOF_5_SLAB_ITEM = ITEMS.register("generated/metal/metal_roof_5_slab", () -> new BlockItem(METAL_ROOF_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_5_STAIRS = BLOCKS.register("generated/metal/metal_roof_5_stairs", () -> new ModStairs(METAL_ROOF_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_ROOF_5.get()))); public static final RegistryObject<Item> METAL_ROOF_5_STAIRS_ITEM = ITEMS.register("generated/metal/metal_roof_5_stairs", () -> new BlockItem(METAL_ROOF_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_VENT_1 = BLOCKS.register("generated/metal/metal_vent_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_VENT_1_ITEM = ITEMS.register("generated/metal/metal_vent_1", () -> new BlockItem(METAL_VENT_1.get(), itemBuilder())); public static final RegistryObject<Block> METAL_VENT_1_SLAB = BLOCKS.register("generated/metal/metal_vent_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_VENT_1.get()))); public static final RegistryObject<Item> METAL_VENT_1_SLAB_ITEM = ITEMS.register("generated/metal/metal_vent_1_slab", () -> new BlockItem(METAL_VENT_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_VENT_1_STAIRS = BLOCKS.register("generated/metal/metal_vent_1_stairs", () -> new ModStairs(METAL_VENT_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_VENT_1.get()))); public static final RegistryObject<Item> METAL_VENT_1_STAIRS_ITEM = ITEMS.register("generated/metal/metal_vent_1_stairs", () -> new BlockItem(METAL_VENT_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_1 = BLOCKS.register("generated/metal/metal_wall_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_1_ITEM = ITEMS.register("generated/metal/metal_wall_1", () -> new BlockItem(METAL_WALL_1.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_1_SLAB = BLOCKS.register("generated/metal/metal_wall_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_1.get()))); public static final RegistryObject<Item> METAL_WALL_1_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_1_slab", () -> new BlockItem(METAL_WALL_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_1_STAIRS = BLOCKS.register("generated/metal/metal_wall_1_stairs", () -> new ModStairs(METAL_WALL_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_1.get()))); public static final RegistryObject<Item> METAL_WALL_1_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_1_stairs", () -> new BlockItem(METAL_WALL_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_2 = BLOCKS.register("generated/metal/metal_wall_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_2_ITEM = ITEMS.register("generated/metal/metal_wall_2", () -> new BlockItem(METAL_WALL_2.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_2_SLAB = BLOCKS.register("generated/metal/metal_wall_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_2.get()))); public static final RegistryObject<Item> METAL_WALL_2_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_2_slab", () -> new BlockItem(METAL_WALL_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_2_STAIRS = BLOCKS.register("generated/metal/metal_wall_2_stairs", () -> new ModStairs(METAL_WALL_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_2.get()))); public static final RegistryObject<Item> METAL_WALL_2_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_2_stairs", () -> new BlockItem(METAL_WALL_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_3 = BLOCKS.register("generated/metal/metal_wall_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_3_ITEM = ITEMS.register("generated/metal/metal_wall_3", () -> new BlockItem(METAL_WALL_3.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_3_SLAB = BLOCKS.register("generated/metal/metal_wall_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_3.get()))); public static final RegistryObject<Item> METAL_WALL_3_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_3_slab", () -> new BlockItem(METAL_WALL_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_3_STAIRS = BLOCKS.register("generated/metal/metal_wall_3_stairs", () -> new ModStairs(METAL_WALL_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_3.get()))); public static final RegistryObject<Item> METAL_WALL_3_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_3_stairs", () -> new BlockItem(METAL_WALL_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_4 = BLOCKS.register("generated/metal/metal_wall_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_4_ITEM = ITEMS.register("generated/metal/metal_wall_4", () -> new BlockItem(METAL_WALL_4.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_4_SLAB = BLOCKS.register("generated/metal/metal_wall_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_4.get()))); public static final RegistryObject<Item> METAL_WALL_4_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_4_slab", () -> new BlockItem(METAL_WALL_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_4_STAIRS = BLOCKS.register("generated/metal/metal_wall_4_stairs", () -> new ModStairs(METAL_WALL_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_4.get()))); public static final RegistryObject<Item> METAL_WALL_4_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_4_stairs", () -> new BlockItem(METAL_WALL_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_5 = BLOCKS.register("generated/metal/metal_wall_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_5_ITEM = ITEMS.register("generated/metal/metal_wall_5", () -> new BlockItem(METAL_WALL_5.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_5_SLAB = BLOCKS.register("generated/metal/metal_wall_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_5.get()))); public static final RegistryObject<Item> METAL_WALL_5_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_5_slab", () -> new BlockItem(METAL_WALL_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_5_STAIRS = BLOCKS.register("generated/metal/metal_wall_5_stairs", () -> new ModStairs(METAL_WALL_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_5.get()))); public static final RegistryObject<Item> METAL_WALL_5_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_5_stairs", () -> new BlockItem(METAL_WALL_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_6 = BLOCKS.register("generated/metal/metal_wall_6_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_6_ITEM = ITEMS.register("generated/metal/metal_wall_6", () -> new BlockItem(METAL_WALL_6.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_6_SLAB = BLOCKS.register("generated/metal/metal_wall_6_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_6.get()))); public static final RegistryObject<Item> METAL_WALL_6_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_6_slab", () -> new BlockItem(METAL_WALL_6_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_6_STAIRS = BLOCKS.register("generated/metal/metal_wall_6_stairs", () -> new ModStairs(METAL_WALL_6.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_6.get()))); public static final RegistryObject<Item> METAL_WALL_6_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_6_stairs", () -> new BlockItem(METAL_WALL_6_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_7 = BLOCKS.register("generated/metal/metal_wall_7_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_7_ITEM = ITEMS.register("generated/metal/metal_wall_7", () -> new BlockItem(METAL_WALL_7.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_7_SLAB = BLOCKS.register("generated/metal/metal_wall_7_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_7.get()))); public static final RegistryObject<Item> METAL_WALL_7_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_7_slab", () -> new BlockItem(METAL_WALL_7_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_7_STAIRS = BLOCKS.register("generated/metal/metal_wall_7_stairs", () -> new ModStairs(METAL_WALL_7.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_7.get()))); public static final RegistryObject<Item> METAL_WALL_7_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_7_stairs", () -> new BlockItem(METAL_WALL_7_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_8 = BLOCKS.register("generated/metal/metal_wall_8_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_8_ITEM = ITEMS.register("generated/metal/metal_wall_8", () -> new BlockItem(METAL_WALL_8.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_8_SLAB = BLOCKS.register("generated/metal/metal_wall_8_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_8.get()))); public static final RegistryObject<Item> METAL_WALL_8_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_8_slab", () -> new BlockItem(METAL_WALL_8_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_8_STAIRS = BLOCKS.register("generated/metal/metal_wall_8_stairs", () -> new ModStairs(METAL_WALL_8.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_8.get()))); public static final RegistryObject<Item> METAL_WALL_8_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_8_stairs", () -> new BlockItem(METAL_WALL_8_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_9 = BLOCKS.register("generated/metal/metal_wall_9_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_9_ITEM = ITEMS.register("generated/metal/metal_wall_9", () -> new BlockItem(METAL_WALL_9.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_9_SLAB = BLOCKS.register("generated/metal/metal_wall_9_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_9.get()))); public static final RegistryObject<Item> METAL_WALL_9_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_9_slab", () -> new BlockItem(METAL_WALL_9_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_9_STAIRS = BLOCKS.register("generated/metal/metal_wall_9_stairs", () -> new ModStairs(METAL_WALL_9.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_9.get()))); public static final RegistryObject<Item> METAL_WALL_9_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_9_stairs", () -> new BlockItem(METAL_WALL_9_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_10 = BLOCKS.register("generated/metal/metal_wall_10_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_10_ITEM = ITEMS.register("generated/metal/metal_wall_10", () -> new BlockItem(METAL_WALL_10.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_10_SLAB = BLOCKS.register("generated/metal/metal_wall_10_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_10.get()))); public static final RegistryObject<Item> METAL_WALL_10_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_10_slab", () -> new BlockItem(METAL_WALL_10_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_10_STAIRS = BLOCKS.register("generated/metal/metal_wall_10_stairs", () -> new ModStairs(METAL_WALL_10.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_10.get()))); public static final RegistryObject<Item> METAL_WALL_10_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_10_stairs", () -> new BlockItem(METAL_WALL_10_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_11 = BLOCKS.register("generated/metal/metal_wall_11_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_11_ITEM = ITEMS.register("generated/metal/metal_wall_11", () -> new BlockItem(METAL_WALL_11.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_11_SLAB = BLOCKS.register("generated/metal/metal_wall_11_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_11.get()))); public static final RegistryObject<Item> METAL_WALL_11_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_11_slab", () -> new BlockItem(METAL_WALL_11_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_11_STAIRS = BLOCKS.register("generated/metal/metal_wall_11_stairs", () -> new ModStairs(METAL_WALL_11.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_11.get()))); public static final RegistryObject<Item> METAL_WALL_11_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_11_stairs", () -> new BlockItem(METAL_WALL_11_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_12 = BLOCKS.register("generated/metal/metal_wall_12_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_12_ITEM = ITEMS.register("generated/metal/metal_wall_12", () -> new BlockItem(METAL_WALL_12.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_12_SLAB = BLOCKS.register("generated/metal/metal_wall_12_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_12.get()))); public static final RegistryObject<Item> METAL_WALL_12_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_12_slab", () -> new BlockItem(METAL_WALL_12_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_12_STAIRS = BLOCKS.register("generated/metal/metal_wall_12_stairs", () -> new ModStairs(METAL_WALL_12.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_12.get()))); public static final RegistryObject<Item> METAL_WALL_12_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_12_stairs", () -> new BlockItem(METAL_WALL_12_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_13 = BLOCKS.register("generated/metal/metal_wall_13_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_13_ITEM = ITEMS.register("generated/metal/metal_wall_13", () -> new BlockItem(METAL_WALL_13.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_13_SLAB = BLOCKS.register("generated/metal/metal_wall_13_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_13.get()))); public static final RegistryObject<Item> METAL_WALL_13_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_13_slab", () -> new BlockItem(METAL_WALL_13_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_13_STAIRS = BLOCKS.register("generated/metal/metal_wall_13_stairs", () -> new ModStairs(METAL_WALL_13.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_13.get()))); public static final RegistryObject<Item> METAL_WALL_13_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_13_stairs", () -> new BlockItem(METAL_WALL_13_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_14 = BLOCKS.register("generated/metal/metal_wall_14_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_14_ITEM = ITEMS.register("generated/metal/metal_wall_14", () -> new BlockItem(METAL_WALL_14.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_14_SLAB = BLOCKS.register("generated/metal/metal_wall_14_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_14.get()))); public static final RegistryObject<Item> METAL_WALL_14_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_14_slab", () -> new BlockItem(METAL_WALL_14_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_14_STAIRS = BLOCKS.register("generated/metal/metal_wall_14_stairs", () -> new ModStairs(METAL_WALL_14.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_14.get()))); public static final RegistryObject<Item> METAL_WALL_14_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_14_stairs", () -> new BlockItem(METAL_WALL_14_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_15 = BLOCKS.register("generated/metal/metal_wall_15_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_15_ITEM = ITEMS.register("generated/metal/metal_wall_15", () -> new BlockItem(METAL_WALL_15.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_15_SLAB = BLOCKS.register("generated/metal/metal_wall_15_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_15.get()))); public static final RegistryObject<Item> METAL_WALL_15_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_15_slab", () -> new BlockItem(METAL_WALL_15_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_15_STAIRS = BLOCKS.register("generated/metal/metal_wall_15_stairs", () -> new ModStairs(METAL_WALL_15.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_15.get()))); public static final RegistryObject<Item> METAL_WALL_15_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_15_stairs", () -> new BlockItem(METAL_WALL_15_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> RED_STRIPES = BLOCKS.register("generated/stone/red_stripes_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> RED_STRIPES_ITEM = ITEMS.register("generated/stone/red_stripes", () -> new BlockItem(RED_STRIPES.get(), itemBuilder())); public static final RegistryObject<Block> RED_STRIPES_SLAB = BLOCKS.register("generated/stone/red_stripes_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(RED_STRIPES.get()))); public static final RegistryObject<Item> RED_STRIPES_SLAB_ITEM = ITEMS.register("generated/stone/red_stripes_slab", () -> new BlockItem(RED_STRIPES_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> RED_STRIPES_STAIRS = BLOCKS.register("generated/stone/red_stripes_stairs", () -> new ModStairs(RED_STRIPES.get().defaultBlockState(), BlockBehaviour.Properties.copy(RED_STRIPES.get()))); public static final RegistryObject<Item> RED_STRIPES_STAIRS_ITEM = ITEMS.register("generated/stone/red_stripes_stairs", () -> new BlockItem(RED_STRIPES_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_1 = BLOCKS.register("generated/wool/carpet_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.WOOL).sound(SoundType.WOOL).strength(4f, 4f).lightLevel(state -> 0).explosionResistance(0f))); public static final RegistryObject<Item> CARPET_1_ITEM = ITEMS.register("generated/wool/carpet_1", () -> new BlockItem(CARPET_1.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_1_SLAB = BLOCKS.register("generated/wool/carpet_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CARPET_1.get()))); public static final RegistryObject<Item> CARPET_1_SLAB_ITEM = ITEMS.register("generated/wool/carpet_1_slab", () -> new BlockItem(CARPET_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_1_STAIRS = BLOCKS.register("generated/wool/carpet_1_stairs", () -> new ModStairs(CARPET_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(CARPET_1.get()))); public static final RegistryObject<Item> CARPET_1_STAIRS_ITEM = ITEMS.register("generated/wool/carpet_1_stairs", () -> new BlockItem(CARPET_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_2 = BLOCKS.register("generated/wool/carpet_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.WOOL).sound(SoundType.WOOL).strength(4f, 4f).lightLevel(state -> 0).explosionResistance(0f))); public static final RegistryObject<Item> CARPET_2_ITEM = ITEMS.register("generated/wool/carpet_2", () -> new BlockItem(CARPET_2.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_2_SLAB = BLOCKS.register("generated/wool/carpet_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CARPET_2.get()))); public static final RegistryObject<Item> CARPET_2_SLAB_ITEM = ITEMS.register("generated/wool/carpet_2_slab", () -> new BlockItem(CARPET_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_2_STAIRS = BLOCKS.register("generated/wool/carpet_2_stairs", () -> new ModStairs(CARPET_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(CARPET_2.get()))); public static final RegistryObject<Item> CARPET_2_STAIRS_ITEM = ITEMS.register("generated/wool/carpet_2_stairs", () -> new BlockItem(CARPET_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> TILES_1 = BLOCKS.register("generated/stone/tiles_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> TILES_1_ITEM = ITEMS.register("generated/stone/tiles_1", () -> new BlockItem(TILES_1.get(), itemBuilder())); public static final RegistryObject<Block> TILES_1_SLAB = BLOCKS.register("generated/stone/tiles_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(TILES_1.get()))); public static final RegistryObject<Item> TILES_1_SLAB_ITEM = ITEMS.register("generated/stone/tiles_1_slab", () -> new BlockItem(TILES_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> TILES_1_STAIRS = BLOCKS.register("generated/stone/tiles_1_stairs", () -> new ModStairs(TILES_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(TILES_1.get()))); public static final RegistryObject<Item> TILES_1_STAIRS_ITEM = ITEMS.register("generated/stone/tiles_1_stairs", () -> new BlockItem(TILES_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> TILES_2 = BLOCKS.register("generated/stone/tiles_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> TILES_2_ITEM = ITEMS.register("generated/stone/tiles_2", () -> new BlockItem(TILES_2.get(), itemBuilder())); public static final RegistryObject<Block> TILES_2_SLAB = BLOCKS.register("generated/stone/tiles_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(TILES_2.get()))); public static final RegistryObject<Item> TILES_2_SLAB_ITEM = ITEMS.register("generated/stone/tiles_2_slab", () -> new BlockItem(TILES_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> TILES_2_STAIRS = BLOCKS.register("generated/stone/tiles_2_stairs", () -> new ModStairs(TILES_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(TILES_2.get()))); public static final RegistryObject<Item> TILES_2_STAIRS_ITEM = ITEMS.register("generated/stone/tiles_2_stairs", () -> new BlockItem(TILES_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> TILES_3 = BLOCKS.register("generated/stone/tiles_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> TILES_3_ITEM = ITEMS.register("generated/stone/tiles_3", () -> new BlockItem(TILES_3.get(), itemBuilder())); public static final RegistryObject<Block> TILES_3_SLAB = BLOCKS.register("generated/stone/tiles_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(TILES_3.get()))); public static final RegistryObject<Item> TILES_3_SLAB_ITEM = ITEMS.register("generated/stone/tiles_3_slab", () -> new BlockItem(TILES_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> TILES_3_STAIRS = BLOCKS.register("generated/stone/tiles_3_stairs", () -> new ModStairs(TILES_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(TILES_3.get()))); public static final RegistryObject<Item> TILES_3_STAIRS_ITEM = ITEMS.register("generated/stone/tiles_3_stairs", () -> new BlockItem(TILES_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> TILES_4 = BLOCKS.register("generated/stone/tiles_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> TILES_4_ITEM = ITEMS.register("generated/stone/tiles_4", () -> new BlockItem(TILES_4.get(), itemBuilder())); public static final RegistryObject<Block> TILES_4_SLAB = BLOCKS.register("generated/stone/tiles_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(TILES_4.get()))); public static final RegistryObject<Item> TILES_4_SLAB_ITEM = ITEMS.register("generated/stone/tiles_4_slab", () -> new BlockItem(TILES_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> TILES_4_STAIRS = BLOCKS.register("generated/stone/tiles_4_stairs", () -> new ModStairs(TILES_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(TILES_4.get()))); public static final RegistryObject<Item> TILES_4_STAIRS_ITEM = ITEMS.register("generated/stone/tiles_4_stairs", () -> new BlockItem(TILES_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> TILES_5 = BLOCKS.register("generated/stone/tiles_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> TILES_5_ITEM = ITEMS.register("generated/stone/tiles_5", () -> new BlockItem(TILES_5.get(), itemBuilder())); public static final RegistryObject<Block> TILES_5_SLAB = BLOCKS.register("generated/stone/tiles_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(TILES_5.get()))); public static final RegistryObject<Item> TILES_5_SLAB_ITEM = ITEMS.register("generated/stone/tiles_5_slab", () -> new BlockItem(TILES_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> TILES_5_STAIRS = BLOCKS.register("generated/stone/tiles_5_stairs", () -> new ModStairs(TILES_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(TILES_5.get()))); public static final RegistryObject<Item> TILES_5_STAIRS_ITEM = ITEMS.register("generated/stone/tiles_5_stairs", () -> new BlockItem(TILES_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> WALLPAPER_1 = BLOCKS.register("generated/wood/wallpaper_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.WOOD).sound(SoundType.WOOD).strength(6f, 6f).lightLevel(state -> 0).explosionResistance(4f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> WALLPAPER_1_ITEM = ITEMS.register("generated/wood/wallpaper_1", () -> new BlockItem(WALLPAPER_1.get(), itemBuilder())); public static final RegistryObject<Block> WALLPAPER_1_SLAB = BLOCKS.register("generated/wood/wallpaper_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(WALLPAPER_1.get()))); public static final RegistryObject<Item> WALLPAPER_1_SLAB_ITEM = ITEMS.register("generated/wood/wallpaper_1_slab", () -> new BlockItem(WALLPAPER_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> WALLPAPER_1_STAIRS = BLOCKS.register("generated/wood/wallpaper_1_stairs", () -> new ModStairs(WALLPAPER_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(WALLPAPER_1.get()))); public static final RegistryObject<Item> WALLPAPER_1_STAIRS_ITEM = ITEMS.register("generated/wood/wallpaper_1_stairs", () -> new BlockItem(WALLPAPER_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_1 = BLOCKS.register("generated/stone/concrete_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_1_ITEM = ITEMS.register("generated/stone/concrete_1", () -> new BlockItem(CONCRETE_1.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_1_SLAB = BLOCKS.register("generated/stone/concrete_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_1.get()))); public static final RegistryObject<Item> CONCRETE_1_SLAB_ITEM = ITEMS.register("generated/stone/concrete_1_slab", () -> new BlockItem(CONCRETE_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_1_STAIRS = BLOCKS.register("generated/stone/concrete_1_stairs", () -> new ModStairs(CONCRETE_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_1.get()))); public static final RegistryObject<Item> CONCRETE_1_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_1_stairs", () -> new BlockItem(CONCRETE_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_2 = BLOCKS.register("generated/stone/concrete_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_2_ITEM = ITEMS.register("generated/stone/concrete_2", () -> new BlockItem(CONCRETE_2.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_2_SLAB = BLOCKS.register("generated/stone/concrete_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_2.get()))); public static final RegistryObject<Item> CONCRETE_2_SLAB_ITEM = ITEMS.register("generated/stone/concrete_2_slab", () -> new BlockItem(CONCRETE_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_2_STAIRS = BLOCKS.register("generated/stone/concrete_2_stairs", () -> new ModStairs(CONCRETE_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_2.get()))); public static final RegistryObject<Item> CONCRETE_2_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_2_stairs", () -> new BlockItem(CONCRETE_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_3 = BLOCKS.register("generated/stone/concrete_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_3_ITEM = ITEMS.register("generated/stone/concrete_3", () -> new BlockItem(CONCRETE_3.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_3_SLAB = BLOCKS.register("generated/stone/concrete_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_3.get()))); public static final RegistryObject<Item> CONCRETE_3_SLAB_ITEM = ITEMS.register("generated/stone/concrete_3_slab", () -> new BlockItem(CONCRETE_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_3_STAIRS = BLOCKS.register("generated/stone/concrete_3_stairs", () -> new ModStairs(CONCRETE_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_3.get()))); public static final RegistryObject<Item> CONCRETE_3_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_3_stairs", () -> new BlockItem(CONCRETE_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_4 = BLOCKS.register("generated/stone/concrete_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_4_ITEM = ITEMS.register("generated/stone/concrete_4", () -> new BlockItem(CONCRETE_4.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_4_SLAB = BLOCKS.register("generated/stone/concrete_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_4.get()))); public static final RegistryObject<Item> CONCRETE_4_SLAB_ITEM = ITEMS.register("generated/stone/concrete_4_slab", () -> new BlockItem(CONCRETE_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_4_STAIRS = BLOCKS.register("generated/stone/concrete_4_stairs", () -> new ModStairs(CONCRETE_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_4.get()))); public static final RegistryObject<Item> CONCRETE_4_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_4_stairs", () -> new BlockItem(CONCRETE_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_5 = BLOCKS.register("generated/stone/concrete_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_5_ITEM = ITEMS.register("generated/stone/concrete_5", () -> new BlockItem(CONCRETE_5.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_5_SLAB = BLOCKS.register("generated/stone/concrete_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_5.get()))); public static final RegistryObject<Item> CONCRETE_5_SLAB_ITEM = ITEMS.register("generated/stone/concrete_5_slab", () -> new BlockItem(CONCRETE_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_5_STAIRS = BLOCKS.register("generated/stone/concrete_5_stairs", () -> new ModStairs(CONCRETE_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_5.get()))); public static final RegistryObject<Item> CONCRETE_5_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_5_stairs", () -> new BlockItem(CONCRETE_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_6 = BLOCKS.register("generated/stone/concrete_6_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_6_ITEM = ITEMS.register("generated/stone/concrete_6", () -> new BlockItem(CONCRETE_6.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_6_SLAB = BLOCKS.register("generated/stone/concrete_6_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_6.get()))); public static final RegistryObject<Item> CONCRETE_6_SLAB_ITEM = ITEMS.register("generated/stone/concrete_6_slab", () -> new BlockItem(CONCRETE_6_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_6_STAIRS = BLOCKS.register("generated/stone/concrete_6_stairs", () -> new ModStairs(CONCRETE_6.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_6.get()))); public static final RegistryObject<Item> CONCRETE_6_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_6_stairs", () -> new BlockItem(CONCRETE_6_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_7 = BLOCKS.register("generated/stone/concrete_7_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_7_ITEM = ITEMS.register("generated/stone/concrete_7", () -> new BlockItem(CONCRETE_7.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_7_SLAB = BLOCKS.register("generated/stone/concrete_7_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_7.get()))); public static final RegistryObject<Item> CONCRETE_7_SLAB_ITEM = ITEMS.register("generated/stone/concrete_7_slab", () -> new BlockItem(CONCRETE_7_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_7_STAIRS = BLOCKS.register("generated/stone/concrete_7_stairs", () -> new ModStairs(CONCRETE_7.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_7.get()))); public static final RegistryObject<Item> CONCRETE_7_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_7_stairs", () -> new BlockItem(CONCRETE_7_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_1 = BLOCKS.register("generated/stone/stone_tiles_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> STONE_TILES_1_ITEM = ITEMS.register("generated/stone/stone_tiles_1", () -> new BlockItem(STONE_TILES_1.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_1_SLAB = BLOCKS.register("generated/stone/stone_tiles_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(STONE_TILES_1.get()))); public static final RegistryObject<Item> STONE_TILES_1_SLAB_ITEM = ITEMS.register("generated/stone/stone_tiles_1_slab", () -> new BlockItem(STONE_TILES_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_1_STAIRS = BLOCKS.register("generated/stone/stone_tiles_1_stairs", () -> new ModStairs(STONE_TILES_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(STONE_TILES_1.get()))); public static final RegistryObject<Item> STONE_TILES_1_STAIRS_ITEM = ITEMS.register("generated/stone/stone_tiles_1_stairs", () -> new BlockItem(STONE_TILES_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_2 = BLOCKS.register("generated/stone/stone_tiles_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> STONE_TILES_2_ITEM = ITEMS.register("generated/stone/stone_tiles_2", () -> new BlockItem(STONE_TILES_2.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_2_SLAB = BLOCKS.register("generated/stone/stone_tiles_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(STONE_TILES_2.get()))); public static final RegistryObject<Item> STONE_TILES_2_SLAB_ITEM = ITEMS.register("generated/stone/stone_tiles_2_slab", () -> new BlockItem(STONE_TILES_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_2_STAIRS = BLOCKS.register("generated/stone/stone_tiles_2_stairs", () -> new ModStairs(STONE_TILES_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(STONE_TILES_2.get()))); public static final RegistryObject<Item> STONE_TILES_2_STAIRS_ITEM = ITEMS.register("generated/stone/stone_tiles_2_stairs", () -> new BlockItem(STONE_TILES_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_3 = BLOCKS.register("generated/stone/stone_tiles_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> STONE_TILES_3_ITEM = ITEMS.register("generated/stone/stone_tiles_3", () -> new BlockItem(STONE_TILES_3.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_3_SLAB = BLOCKS.register("generated/stone/stone_tiles_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(STONE_TILES_3.get()))); public static final RegistryObject<Item> STONE_TILES_3_SLAB_ITEM = ITEMS.register("generated/stone/stone_tiles_3_slab", () -> new BlockItem(STONE_TILES_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_3_STAIRS = BLOCKS.register("generated/stone/stone_tiles_3_stairs", () -> new ModStairs(STONE_TILES_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(STONE_TILES_3.get()))); public static final RegistryObject<Item> STONE_TILES_3_STAIRS_ITEM = ITEMS.register("generated/stone/stone_tiles_3_stairs", () -> new BlockItem(STONE_TILES_3_STAIRS.get(), itemBuilder())); /*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###*/ private static Item.Properties itemBuilder() {
package de.griefed.addemall.block; @SuppressWarnings("unused") public class GeneratedModBlocks { public static final RegistrationProvider<Block> BLOCKS = RegistrationProvider.get(Registry.BLOCK_REGISTRY, Constants.MOD_ID); public static final RegistrationProvider<Item> ITEMS = RegistrationProvider.get(Registry.ITEM_REGISTRY, Constants.MOD_ID); /*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###*/ public static final RegistryObject<Block> GREEN_ZEN = BLOCKS.register("generated/dirt/green_zen_block", () -> new Block(BlockBehaviour.Properties.of(Material.DIRT).sound(SoundType.GRASS).strength(2f, 2f).lightLevel(state -> 4).explosionResistance(0f))); public static final RegistryObject<Item> GREEN_ZEN_ITEM = ITEMS.register("generated/dirt/green_zen", () -> new BlockItem(GREEN_ZEN.get(), itemBuilder())); public static final RegistryObject<Block> GREEN_ZEN_SLAB = BLOCKS.register("generated/dirt/green_zen_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(GREEN_ZEN.get()))); public static final RegistryObject<Item> GREEN_ZEN_SLAB_ITEM = ITEMS.register("generated/dirt/green_zen_slab", () -> new BlockItem(GREEN_ZEN_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> GREEN_ZEN_STAIRS = BLOCKS.register("generated/dirt/green_zen_stairs", () -> new ModStairs(GREEN_ZEN.get().defaultBlockState(), BlockBehaviour.Properties.copy(GREEN_ZEN.get()))); public static final RegistryObject<Item> GREEN_ZEN_STAIRS_ITEM = ITEMS.register("generated/dirt/green_zen_stairs", () -> new BlockItem(GREEN_ZEN_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> YELLOW_ZEN = BLOCKS.register("generated/dirt/yellow_zen_block", () -> new Block(BlockBehaviour.Properties.of(Material.DIRT).sound(SoundType.GRASS).strength(2f, 2f).lightLevel(state -> 4).explosionResistance(0f))); public static final RegistryObject<Item> YELLOW_ZEN_ITEM = ITEMS.register("generated/dirt/yellow_zen", () -> new BlockItem(YELLOW_ZEN.get(), itemBuilder())); public static final RegistryObject<Block> YELLOW_ZEN_SLAB = BLOCKS.register("generated/dirt/yellow_zen_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(YELLOW_ZEN.get()))); public static final RegistryObject<Item> YELLOW_ZEN_SLAB_ITEM = ITEMS.register("generated/dirt/yellow_zen_slab", () -> new BlockItem(YELLOW_ZEN_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> YELLOW_ZEN_STAIRS = BLOCKS.register("generated/dirt/yellow_zen_stairs", () -> new ModStairs(YELLOW_ZEN.get().defaultBlockState(), BlockBehaviour.Properties.copy(YELLOW_ZEN.get()))); public static final RegistryObject<Item> YELLOW_ZEN_STAIRS_ITEM = ITEMS.register("generated/dirt/yellow_zen_stairs", () -> new BlockItem(YELLOW_ZEN_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> BLUE_ZEN = BLOCKS.register("generated/dirt/blue_zen_block", () -> new Block(BlockBehaviour.Properties.of(Material.DIRT).sound(SoundType.GRASS).strength(2f, 2f).lightLevel(state -> 4).explosionResistance(0f))); public static final RegistryObject<Item> BLUE_ZEN_ITEM = ITEMS.register("generated/dirt/blue_zen", () -> new BlockItem(BLUE_ZEN.get(), itemBuilder())); public static final RegistryObject<Block> BLUE_ZEN_SLAB = BLOCKS.register("generated/dirt/blue_zen_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(BLUE_ZEN.get()))); public static final RegistryObject<Item> BLUE_ZEN_SLAB_ITEM = ITEMS.register("generated/dirt/blue_zen_slab", () -> new BlockItem(BLUE_ZEN_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> BLUE_ZEN_STAIRS = BLOCKS.register("generated/dirt/blue_zen_stairs", () -> new ModStairs(BLUE_ZEN.get().defaultBlockState(), BlockBehaviour.Properties.copy(BLUE_ZEN.get()))); public static final RegistryObject<Item> BLUE_ZEN_STAIRS_ITEM = ITEMS.register("generated/dirt/blue_zen_stairs", () -> new BlockItem(BLUE_ZEN_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> BROWN_ZEN = BLOCKS.register("generated/dirt/brown_zen_block", () -> new Block(BlockBehaviour.Properties.of(Material.DIRT).sound(SoundType.GRASS).strength(2f, 2f).lightLevel(state -> 4).explosionResistance(0f))); public static final RegistryObject<Item> BROWN_ZEN_ITEM = ITEMS.register("generated/dirt/brown_zen", () -> new BlockItem(BROWN_ZEN.get(), itemBuilder())); public static final RegistryObject<Block> BROWN_ZEN_SLAB = BLOCKS.register("generated/dirt/brown_zen_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(BROWN_ZEN.get()))); public static final RegistryObject<Item> BROWN_ZEN_SLAB_ITEM = ITEMS.register("generated/dirt/brown_zen_slab", () -> new BlockItem(BROWN_ZEN_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> BROWN_ZEN_STAIRS = BLOCKS.register("generated/dirt/brown_zen_stairs", () -> new ModStairs(BROWN_ZEN.get().defaultBlockState(), BlockBehaviour.Properties.copy(BROWN_ZEN.get()))); public static final RegistryObject<Item> BROWN_ZEN_STAIRS_ITEM = ITEMS.register("generated/dirt/brown_zen_stairs", () -> new BlockItem(BROWN_ZEN_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> RED_ZEN = BLOCKS.register("generated/dirt/red_zen_block", () -> new Block(BlockBehaviour.Properties.of(Material.DIRT).sound(SoundType.GRASS).strength(2f, 2f).lightLevel(state -> 4).explosionResistance(0f))); public static final RegistryObject<Item> RED_ZEN_ITEM = ITEMS.register("generated/dirt/red_zen", () -> new BlockItem(RED_ZEN.get(), itemBuilder())); public static final RegistryObject<Block> RED_ZEN_SLAB = BLOCKS.register("generated/dirt/red_zen_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(RED_ZEN.get()))); public static final RegistryObject<Item> RED_ZEN_SLAB_ITEM = ITEMS.register("generated/dirt/red_zen_slab", () -> new BlockItem(RED_ZEN_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> RED_ZEN_STAIRS = BLOCKS.register("generated/dirt/red_zen_stairs", () -> new ModStairs(RED_ZEN.get().defaultBlockState(), BlockBehaviour.Properties.copy(RED_ZEN.get()))); public static final RegistryObject<Item> RED_ZEN_STAIRS_ITEM = ITEMS.register("generated/dirt/red_zen_stairs", () -> new BlockItem(RED_ZEN_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_1 = BLOCKS.register("generated/metal/metal_floor_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_1_ITEM = ITEMS.register("generated/metal/metal_floor_1", () -> new BlockItem(METAL_FLOOR_1.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_1_SLAB = BLOCKS.register("generated/metal/metal_floor_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_1.get()))); public static final RegistryObject<Item> METAL_FLOOR_1_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_1_slab", () -> new BlockItem(METAL_FLOOR_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_1_STAIRS = BLOCKS.register("generated/metal/metal_floor_1_stairs", () -> new ModStairs(METAL_FLOOR_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_1.get()))); public static final RegistryObject<Item> METAL_FLOOR_1_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_1_stairs", () -> new BlockItem(METAL_FLOOR_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_2 = BLOCKS.register("generated/metal/metal_floor_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_2_ITEM = ITEMS.register("generated/metal/metal_floor_2", () -> new BlockItem(METAL_FLOOR_2.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_2_SLAB = BLOCKS.register("generated/metal/metal_floor_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_2.get()))); public static final RegistryObject<Item> METAL_FLOOR_2_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_2_slab", () -> new BlockItem(METAL_FLOOR_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_2_STAIRS = BLOCKS.register("generated/metal/metal_floor_2_stairs", () -> new ModStairs(METAL_FLOOR_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_2.get()))); public static final RegistryObject<Item> METAL_FLOOR_2_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_2_stairs", () -> new BlockItem(METAL_FLOOR_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_3 = BLOCKS.register("generated/metal/metal_floor_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_3_ITEM = ITEMS.register("generated/metal/metal_floor_3", () -> new BlockItem(METAL_FLOOR_3.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_3_SLAB = BLOCKS.register("generated/metal/metal_floor_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_3.get()))); public static final RegistryObject<Item> METAL_FLOOR_3_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_3_slab", () -> new BlockItem(METAL_FLOOR_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_3_STAIRS = BLOCKS.register("generated/metal/metal_floor_3_stairs", () -> new ModStairs(METAL_FLOOR_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_3.get()))); public static final RegistryObject<Item> METAL_FLOOR_3_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_3_stairs", () -> new BlockItem(METAL_FLOOR_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_4 = BLOCKS.register("generated/metal/metal_floor_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_4_ITEM = ITEMS.register("generated/metal/metal_floor_4", () -> new BlockItem(METAL_FLOOR_4.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_4_SLAB = BLOCKS.register("generated/metal/metal_floor_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_4.get()))); public static final RegistryObject<Item> METAL_FLOOR_4_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_4_slab", () -> new BlockItem(METAL_FLOOR_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_4_STAIRS = BLOCKS.register("generated/metal/metal_floor_4_stairs", () -> new ModStairs(METAL_FLOOR_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_4.get()))); public static final RegistryObject<Item> METAL_FLOOR_4_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_4_stairs", () -> new BlockItem(METAL_FLOOR_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_5 = BLOCKS.register("generated/metal/metal_floor_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_5_ITEM = ITEMS.register("generated/metal/metal_floor_5", () -> new BlockItem(METAL_FLOOR_5.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_5_SLAB = BLOCKS.register("generated/metal/metal_floor_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_5.get()))); public static final RegistryObject<Item> METAL_FLOOR_5_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_5_slab", () -> new BlockItem(METAL_FLOOR_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_5_STAIRS = BLOCKS.register("generated/metal/metal_floor_5_stairs", () -> new ModStairs(METAL_FLOOR_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_5.get()))); public static final RegistryObject<Item> METAL_FLOOR_5_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_5_stairs", () -> new BlockItem(METAL_FLOOR_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_6 = BLOCKS.register("generated/metal/metal_floor_6_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_FLOOR_6_ITEM = ITEMS.register("generated/metal/metal_floor_6", () -> new BlockItem(METAL_FLOOR_6.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_6_SLAB = BLOCKS.register("generated/metal/metal_floor_6_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_FLOOR_6.get()))); public static final RegistryObject<Item> METAL_FLOOR_6_SLAB_ITEM = ITEMS.register("generated/metal/metal_floor_6_slab", () -> new BlockItem(METAL_FLOOR_6_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_FLOOR_6_STAIRS = BLOCKS.register("generated/metal/metal_floor_6_stairs", () -> new ModStairs(METAL_FLOOR_6.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_FLOOR_6.get()))); public static final RegistryObject<Item> METAL_FLOOR_6_STAIRS_ITEM = ITEMS.register("generated/metal/metal_floor_6_stairs", () -> new BlockItem(METAL_FLOOR_6_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_1 = BLOCKS.register("generated/metal/metal_plating_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_PLATING_1_ITEM = ITEMS.register("generated/metal/metal_plating_1", () -> new BlockItem(METAL_PLATING_1.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_1_SLAB = BLOCKS.register("generated/metal/metal_plating_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_PLATING_1.get()))); public static final RegistryObject<Item> METAL_PLATING_1_SLAB_ITEM = ITEMS.register("generated/metal/metal_plating_1_slab", () -> new BlockItem(METAL_PLATING_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_1_STAIRS = BLOCKS.register("generated/metal/metal_plating_1_stairs", () -> new ModStairs(METAL_PLATING_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_PLATING_1.get()))); public static final RegistryObject<Item> METAL_PLATING_1_STAIRS_ITEM = ITEMS.register("generated/metal/metal_plating_1_stairs", () -> new BlockItem(METAL_PLATING_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_2 = BLOCKS.register("generated/metal/metal_plating_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_PLATING_2_ITEM = ITEMS.register("generated/metal/metal_plating_2", () -> new BlockItem(METAL_PLATING_2.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_2_SLAB = BLOCKS.register("generated/metal/metal_plating_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_PLATING_2.get()))); public static final RegistryObject<Item> METAL_PLATING_2_SLAB_ITEM = ITEMS.register("generated/metal/metal_plating_2_slab", () -> new BlockItem(METAL_PLATING_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_2_STAIRS = BLOCKS.register("generated/metal/metal_plating_2_stairs", () -> new ModStairs(METAL_PLATING_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_PLATING_2.get()))); public static final RegistryObject<Item> METAL_PLATING_2_STAIRS_ITEM = ITEMS.register("generated/metal/metal_plating_2_stairs", () -> new BlockItem(METAL_PLATING_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_3 = BLOCKS.register("generated/metal/metal_plating_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_PLATING_3_ITEM = ITEMS.register("generated/metal/metal_plating_3", () -> new BlockItem(METAL_PLATING_3.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_3_SLAB = BLOCKS.register("generated/metal/metal_plating_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_PLATING_3.get()))); public static final RegistryObject<Item> METAL_PLATING_3_SLAB_ITEM = ITEMS.register("generated/metal/metal_plating_3_slab", () -> new BlockItem(METAL_PLATING_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_3_STAIRS = BLOCKS.register("generated/metal/metal_plating_3_stairs", () -> new ModStairs(METAL_PLATING_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_PLATING_3.get()))); public static final RegistryObject<Item> METAL_PLATING_3_STAIRS_ITEM = ITEMS.register("generated/metal/metal_plating_3_stairs", () -> new BlockItem(METAL_PLATING_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_4 = BLOCKS.register("generated/metal/metal_plating_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_PLATING_4_ITEM = ITEMS.register("generated/metal/metal_plating_4", () -> new BlockItem(METAL_PLATING_4.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_4_SLAB = BLOCKS.register("generated/metal/metal_plating_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_PLATING_4.get()))); public static final RegistryObject<Item> METAL_PLATING_4_SLAB_ITEM = ITEMS.register("generated/metal/metal_plating_4_slab", () -> new BlockItem(METAL_PLATING_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_4_STAIRS = BLOCKS.register("generated/metal/metal_plating_4_stairs", () -> new ModStairs(METAL_PLATING_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_PLATING_4.get()))); public static final RegistryObject<Item> METAL_PLATING_4_STAIRS_ITEM = ITEMS.register("generated/metal/metal_plating_4_stairs", () -> new BlockItem(METAL_PLATING_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_5 = BLOCKS.register("generated/metal/metal_plating_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_PLATING_5_ITEM = ITEMS.register("generated/metal/metal_plating_5", () -> new BlockItem(METAL_PLATING_5.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_5_SLAB = BLOCKS.register("generated/metal/metal_plating_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_PLATING_5.get()))); public static final RegistryObject<Item> METAL_PLATING_5_SLAB_ITEM = ITEMS.register("generated/metal/metal_plating_5_slab", () -> new BlockItem(METAL_PLATING_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_PLATING_5_STAIRS = BLOCKS.register("generated/metal/metal_plating_5_stairs", () -> new ModStairs(METAL_PLATING_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_PLATING_5.get()))); public static final RegistryObject<Item> METAL_PLATING_5_STAIRS_ITEM = ITEMS.register("generated/metal/metal_plating_5_stairs", () -> new BlockItem(METAL_PLATING_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_1 = BLOCKS.register("generated/metal/metal_roof_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_ROOF_1_ITEM = ITEMS.register("generated/metal/metal_roof_1", () -> new BlockItem(METAL_ROOF_1.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_1_SLAB = BLOCKS.register("generated/metal/metal_roof_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_ROOF_1.get()))); public static final RegistryObject<Item> METAL_ROOF_1_SLAB_ITEM = ITEMS.register("generated/metal/metal_roof_1_slab", () -> new BlockItem(METAL_ROOF_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_1_STAIRS = BLOCKS.register("generated/metal/metal_roof_1_stairs", () -> new ModStairs(METAL_ROOF_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_ROOF_1.get()))); public static final RegistryObject<Item> METAL_ROOF_1_STAIRS_ITEM = ITEMS.register("generated/metal/metal_roof_1_stairs", () -> new BlockItem(METAL_ROOF_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_2 = BLOCKS.register("generated/metal/metal_roof_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_ROOF_2_ITEM = ITEMS.register("generated/metal/metal_roof_2", () -> new BlockItem(METAL_ROOF_2.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_2_SLAB = BLOCKS.register("generated/metal/metal_roof_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_ROOF_2.get()))); public static final RegistryObject<Item> METAL_ROOF_2_SLAB_ITEM = ITEMS.register("generated/metal/metal_roof_2_slab", () -> new BlockItem(METAL_ROOF_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_2_STAIRS = BLOCKS.register("generated/metal/metal_roof_2_stairs", () -> new ModStairs(METAL_ROOF_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_ROOF_2.get()))); public static final RegistryObject<Item> METAL_ROOF_2_STAIRS_ITEM = ITEMS.register("generated/metal/metal_roof_2_stairs", () -> new BlockItem(METAL_ROOF_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_3 = BLOCKS.register("generated/metal/metal_roof_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_ROOF_3_ITEM = ITEMS.register("generated/metal/metal_roof_3", () -> new BlockItem(METAL_ROOF_3.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_3_SLAB = BLOCKS.register("generated/metal/metal_roof_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_ROOF_3.get()))); public static final RegistryObject<Item> METAL_ROOF_3_SLAB_ITEM = ITEMS.register("generated/metal/metal_roof_3_slab", () -> new BlockItem(METAL_ROOF_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_3_STAIRS = BLOCKS.register("generated/metal/metal_roof_3_stairs", () -> new ModStairs(METAL_ROOF_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_ROOF_3.get()))); public static final RegistryObject<Item> METAL_ROOF_3_STAIRS_ITEM = ITEMS.register("generated/metal/metal_roof_3_stairs", () -> new BlockItem(METAL_ROOF_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_4 = BLOCKS.register("generated/metal/metal_roof_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_ROOF_4_ITEM = ITEMS.register("generated/metal/metal_roof_4", () -> new BlockItem(METAL_ROOF_4.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_4_SLAB = BLOCKS.register("generated/metal/metal_roof_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_ROOF_4.get()))); public static final RegistryObject<Item> METAL_ROOF_4_SLAB_ITEM = ITEMS.register("generated/metal/metal_roof_4_slab", () -> new BlockItem(METAL_ROOF_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_4_STAIRS = BLOCKS.register("generated/metal/metal_roof_4_stairs", () -> new ModStairs(METAL_ROOF_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_ROOF_4.get()))); public static final RegistryObject<Item> METAL_ROOF_4_STAIRS_ITEM = ITEMS.register("generated/metal/metal_roof_4_stairs", () -> new BlockItem(METAL_ROOF_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_5 = BLOCKS.register("generated/metal/metal_roof_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_ROOF_5_ITEM = ITEMS.register("generated/metal/metal_roof_5", () -> new BlockItem(METAL_ROOF_5.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_5_SLAB = BLOCKS.register("generated/metal/metal_roof_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_ROOF_5.get()))); public static final RegistryObject<Item> METAL_ROOF_5_SLAB_ITEM = ITEMS.register("generated/metal/metal_roof_5_slab", () -> new BlockItem(METAL_ROOF_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_ROOF_5_STAIRS = BLOCKS.register("generated/metal/metal_roof_5_stairs", () -> new ModStairs(METAL_ROOF_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_ROOF_5.get()))); public static final RegistryObject<Item> METAL_ROOF_5_STAIRS_ITEM = ITEMS.register("generated/metal/metal_roof_5_stairs", () -> new BlockItem(METAL_ROOF_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_VENT_1 = BLOCKS.register("generated/metal/metal_vent_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_VENT_1_ITEM = ITEMS.register("generated/metal/metal_vent_1", () -> new BlockItem(METAL_VENT_1.get(), itemBuilder())); public static final RegistryObject<Block> METAL_VENT_1_SLAB = BLOCKS.register("generated/metal/metal_vent_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_VENT_1.get()))); public static final RegistryObject<Item> METAL_VENT_1_SLAB_ITEM = ITEMS.register("generated/metal/metal_vent_1_slab", () -> new BlockItem(METAL_VENT_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_VENT_1_STAIRS = BLOCKS.register("generated/metal/metal_vent_1_stairs", () -> new ModStairs(METAL_VENT_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_VENT_1.get()))); public static final RegistryObject<Item> METAL_VENT_1_STAIRS_ITEM = ITEMS.register("generated/metal/metal_vent_1_stairs", () -> new BlockItem(METAL_VENT_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_1 = BLOCKS.register("generated/metal/metal_wall_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_1_ITEM = ITEMS.register("generated/metal/metal_wall_1", () -> new BlockItem(METAL_WALL_1.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_1_SLAB = BLOCKS.register("generated/metal/metal_wall_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_1.get()))); public static final RegistryObject<Item> METAL_WALL_1_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_1_slab", () -> new BlockItem(METAL_WALL_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_1_STAIRS = BLOCKS.register("generated/metal/metal_wall_1_stairs", () -> new ModStairs(METAL_WALL_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_1.get()))); public static final RegistryObject<Item> METAL_WALL_1_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_1_stairs", () -> new BlockItem(METAL_WALL_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_2 = BLOCKS.register("generated/metal/metal_wall_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_2_ITEM = ITEMS.register("generated/metal/metal_wall_2", () -> new BlockItem(METAL_WALL_2.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_2_SLAB = BLOCKS.register("generated/metal/metal_wall_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_2.get()))); public static final RegistryObject<Item> METAL_WALL_2_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_2_slab", () -> new BlockItem(METAL_WALL_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_2_STAIRS = BLOCKS.register("generated/metal/metal_wall_2_stairs", () -> new ModStairs(METAL_WALL_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_2.get()))); public static final RegistryObject<Item> METAL_WALL_2_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_2_stairs", () -> new BlockItem(METAL_WALL_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_3 = BLOCKS.register("generated/metal/metal_wall_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_3_ITEM = ITEMS.register("generated/metal/metal_wall_3", () -> new BlockItem(METAL_WALL_3.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_3_SLAB = BLOCKS.register("generated/metal/metal_wall_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_3.get()))); public static final RegistryObject<Item> METAL_WALL_3_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_3_slab", () -> new BlockItem(METAL_WALL_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_3_STAIRS = BLOCKS.register("generated/metal/metal_wall_3_stairs", () -> new ModStairs(METAL_WALL_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_3.get()))); public static final RegistryObject<Item> METAL_WALL_3_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_3_stairs", () -> new BlockItem(METAL_WALL_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_4 = BLOCKS.register("generated/metal/metal_wall_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_4_ITEM = ITEMS.register("generated/metal/metal_wall_4", () -> new BlockItem(METAL_WALL_4.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_4_SLAB = BLOCKS.register("generated/metal/metal_wall_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_4.get()))); public static final RegistryObject<Item> METAL_WALL_4_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_4_slab", () -> new BlockItem(METAL_WALL_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_4_STAIRS = BLOCKS.register("generated/metal/metal_wall_4_stairs", () -> new ModStairs(METAL_WALL_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_4.get()))); public static final RegistryObject<Item> METAL_WALL_4_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_4_stairs", () -> new BlockItem(METAL_WALL_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_5 = BLOCKS.register("generated/metal/metal_wall_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_5_ITEM = ITEMS.register("generated/metal/metal_wall_5", () -> new BlockItem(METAL_WALL_5.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_5_SLAB = BLOCKS.register("generated/metal/metal_wall_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_5.get()))); public static final RegistryObject<Item> METAL_WALL_5_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_5_slab", () -> new BlockItem(METAL_WALL_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_5_STAIRS = BLOCKS.register("generated/metal/metal_wall_5_stairs", () -> new ModStairs(METAL_WALL_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_5.get()))); public static final RegistryObject<Item> METAL_WALL_5_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_5_stairs", () -> new BlockItem(METAL_WALL_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_6 = BLOCKS.register("generated/metal/metal_wall_6_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_6_ITEM = ITEMS.register("generated/metal/metal_wall_6", () -> new BlockItem(METAL_WALL_6.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_6_SLAB = BLOCKS.register("generated/metal/metal_wall_6_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_6.get()))); public static final RegistryObject<Item> METAL_WALL_6_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_6_slab", () -> new BlockItem(METAL_WALL_6_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_6_STAIRS = BLOCKS.register("generated/metal/metal_wall_6_stairs", () -> new ModStairs(METAL_WALL_6.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_6.get()))); public static final RegistryObject<Item> METAL_WALL_6_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_6_stairs", () -> new BlockItem(METAL_WALL_6_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_7 = BLOCKS.register("generated/metal/metal_wall_7_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_7_ITEM = ITEMS.register("generated/metal/metal_wall_7", () -> new BlockItem(METAL_WALL_7.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_7_SLAB = BLOCKS.register("generated/metal/metal_wall_7_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_7.get()))); public static final RegistryObject<Item> METAL_WALL_7_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_7_slab", () -> new BlockItem(METAL_WALL_7_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_7_STAIRS = BLOCKS.register("generated/metal/metal_wall_7_stairs", () -> new ModStairs(METAL_WALL_7.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_7.get()))); public static final RegistryObject<Item> METAL_WALL_7_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_7_stairs", () -> new BlockItem(METAL_WALL_7_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_8 = BLOCKS.register("generated/metal/metal_wall_8_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_8_ITEM = ITEMS.register("generated/metal/metal_wall_8", () -> new BlockItem(METAL_WALL_8.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_8_SLAB = BLOCKS.register("generated/metal/metal_wall_8_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_8.get()))); public static final RegistryObject<Item> METAL_WALL_8_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_8_slab", () -> new BlockItem(METAL_WALL_8_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_8_STAIRS = BLOCKS.register("generated/metal/metal_wall_8_stairs", () -> new ModStairs(METAL_WALL_8.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_8.get()))); public static final RegistryObject<Item> METAL_WALL_8_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_8_stairs", () -> new BlockItem(METAL_WALL_8_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_9 = BLOCKS.register("generated/metal/metal_wall_9_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_9_ITEM = ITEMS.register("generated/metal/metal_wall_9", () -> new BlockItem(METAL_WALL_9.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_9_SLAB = BLOCKS.register("generated/metal/metal_wall_9_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_9.get()))); public static final RegistryObject<Item> METAL_WALL_9_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_9_slab", () -> new BlockItem(METAL_WALL_9_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_9_STAIRS = BLOCKS.register("generated/metal/metal_wall_9_stairs", () -> new ModStairs(METAL_WALL_9.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_9.get()))); public static final RegistryObject<Item> METAL_WALL_9_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_9_stairs", () -> new BlockItem(METAL_WALL_9_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_10 = BLOCKS.register("generated/metal/metal_wall_10_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_10_ITEM = ITEMS.register("generated/metal/metal_wall_10", () -> new BlockItem(METAL_WALL_10.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_10_SLAB = BLOCKS.register("generated/metal/metal_wall_10_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_10.get()))); public static final RegistryObject<Item> METAL_WALL_10_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_10_slab", () -> new BlockItem(METAL_WALL_10_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_10_STAIRS = BLOCKS.register("generated/metal/metal_wall_10_stairs", () -> new ModStairs(METAL_WALL_10.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_10.get()))); public static final RegistryObject<Item> METAL_WALL_10_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_10_stairs", () -> new BlockItem(METAL_WALL_10_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_11 = BLOCKS.register("generated/metal/metal_wall_11_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_11_ITEM = ITEMS.register("generated/metal/metal_wall_11", () -> new BlockItem(METAL_WALL_11.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_11_SLAB = BLOCKS.register("generated/metal/metal_wall_11_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_11.get()))); public static final RegistryObject<Item> METAL_WALL_11_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_11_slab", () -> new BlockItem(METAL_WALL_11_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_11_STAIRS = BLOCKS.register("generated/metal/metal_wall_11_stairs", () -> new ModStairs(METAL_WALL_11.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_11.get()))); public static final RegistryObject<Item> METAL_WALL_11_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_11_stairs", () -> new BlockItem(METAL_WALL_11_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_12 = BLOCKS.register("generated/metal/metal_wall_12_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_12_ITEM = ITEMS.register("generated/metal/metal_wall_12", () -> new BlockItem(METAL_WALL_12.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_12_SLAB = BLOCKS.register("generated/metal/metal_wall_12_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_12.get()))); public static final RegistryObject<Item> METAL_WALL_12_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_12_slab", () -> new BlockItem(METAL_WALL_12_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_12_STAIRS = BLOCKS.register("generated/metal/metal_wall_12_stairs", () -> new ModStairs(METAL_WALL_12.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_12.get()))); public static final RegistryObject<Item> METAL_WALL_12_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_12_stairs", () -> new BlockItem(METAL_WALL_12_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_13 = BLOCKS.register("generated/metal/metal_wall_13_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_13_ITEM = ITEMS.register("generated/metal/metal_wall_13", () -> new BlockItem(METAL_WALL_13.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_13_SLAB = BLOCKS.register("generated/metal/metal_wall_13_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_13.get()))); public static final RegistryObject<Item> METAL_WALL_13_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_13_slab", () -> new BlockItem(METAL_WALL_13_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_13_STAIRS = BLOCKS.register("generated/metal/metal_wall_13_stairs", () -> new ModStairs(METAL_WALL_13.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_13.get()))); public static final RegistryObject<Item> METAL_WALL_13_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_13_stairs", () -> new BlockItem(METAL_WALL_13_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_14 = BLOCKS.register("generated/metal/metal_wall_14_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_14_ITEM = ITEMS.register("generated/metal/metal_wall_14", () -> new BlockItem(METAL_WALL_14.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_14_SLAB = BLOCKS.register("generated/metal/metal_wall_14_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_14.get()))); public static final RegistryObject<Item> METAL_WALL_14_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_14_slab", () -> new BlockItem(METAL_WALL_14_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_14_STAIRS = BLOCKS.register("generated/metal/metal_wall_14_stairs", () -> new ModStairs(METAL_WALL_14.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_14.get()))); public static final RegistryObject<Item> METAL_WALL_14_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_14_stairs", () -> new BlockItem(METAL_WALL_14_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_15 = BLOCKS.register("generated/metal/metal_wall_15_block", () -> new Block(BlockBehaviour.Properties.of(Material.METAL).sound(SoundType.METAL).strength(12f, 12f).lightLevel(state -> 0).explosionResistance(12f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> METAL_WALL_15_ITEM = ITEMS.register("generated/metal/metal_wall_15", () -> new BlockItem(METAL_WALL_15.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_15_SLAB = BLOCKS.register("generated/metal/metal_wall_15_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(METAL_WALL_15.get()))); public static final RegistryObject<Item> METAL_WALL_15_SLAB_ITEM = ITEMS.register("generated/metal/metal_wall_15_slab", () -> new BlockItem(METAL_WALL_15_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> METAL_WALL_15_STAIRS = BLOCKS.register("generated/metal/metal_wall_15_stairs", () -> new ModStairs(METAL_WALL_15.get().defaultBlockState(), BlockBehaviour.Properties.copy(METAL_WALL_15.get()))); public static final RegistryObject<Item> METAL_WALL_15_STAIRS_ITEM = ITEMS.register("generated/metal/metal_wall_15_stairs", () -> new BlockItem(METAL_WALL_15_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> RED_STRIPES = BLOCKS.register("generated/stone/red_stripes_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> RED_STRIPES_ITEM = ITEMS.register("generated/stone/red_stripes", () -> new BlockItem(RED_STRIPES.get(), itemBuilder())); public static final RegistryObject<Block> RED_STRIPES_SLAB = BLOCKS.register("generated/stone/red_stripes_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(RED_STRIPES.get()))); public static final RegistryObject<Item> RED_STRIPES_SLAB_ITEM = ITEMS.register("generated/stone/red_stripes_slab", () -> new BlockItem(RED_STRIPES_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> RED_STRIPES_STAIRS = BLOCKS.register("generated/stone/red_stripes_stairs", () -> new ModStairs(RED_STRIPES.get().defaultBlockState(), BlockBehaviour.Properties.copy(RED_STRIPES.get()))); public static final RegistryObject<Item> RED_STRIPES_STAIRS_ITEM = ITEMS.register("generated/stone/red_stripes_stairs", () -> new BlockItem(RED_STRIPES_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_1 = BLOCKS.register("generated/wool/carpet_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.WOOL).sound(SoundType.WOOL).strength(4f, 4f).lightLevel(state -> 0).explosionResistance(0f))); public static final RegistryObject<Item> CARPET_1_ITEM = ITEMS.register("generated/wool/carpet_1", () -> new BlockItem(CARPET_1.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_1_SLAB = BLOCKS.register("generated/wool/carpet_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CARPET_1.get()))); public static final RegistryObject<Item> CARPET_1_SLAB_ITEM = ITEMS.register("generated/wool/carpet_1_slab", () -> new BlockItem(CARPET_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_1_STAIRS = BLOCKS.register("generated/wool/carpet_1_stairs", () -> new ModStairs(CARPET_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(CARPET_1.get()))); public static final RegistryObject<Item> CARPET_1_STAIRS_ITEM = ITEMS.register("generated/wool/carpet_1_stairs", () -> new BlockItem(CARPET_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_2 = BLOCKS.register("generated/wool/carpet_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.WOOL).sound(SoundType.WOOL).strength(4f, 4f).lightLevel(state -> 0).explosionResistance(0f))); public static final RegistryObject<Item> CARPET_2_ITEM = ITEMS.register("generated/wool/carpet_2", () -> new BlockItem(CARPET_2.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_2_SLAB = BLOCKS.register("generated/wool/carpet_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CARPET_2.get()))); public static final RegistryObject<Item> CARPET_2_SLAB_ITEM = ITEMS.register("generated/wool/carpet_2_slab", () -> new BlockItem(CARPET_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CARPET_2_STAIRS = BLOCKS.register("generated/wool/carpet_2_stairs", () -> new ModStairs(CARPET_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(CARPET_2.get()))); public static final RegistryObject<Item> CARPET_2_STAIRS_ITEM = ITEMS.register("generated/wool/carpet_2_stairs", () -> new BlockItem(CARPET_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> TILES_1 = BLOCKS.register("generated/stone/tiles_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> TILES_1_ITEM = ITEMS.register("generated/stone/tiles_1", () -> new BlockItem(TILES_1.get(), itemBuilder())); public static final RegistryObject<Block> TILES_1_SLAB = BLOCKS.register("generated/stone/tiles_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(TILES_1.get()))); public static final RegistryObject<Item> TILES_1_SLAB_ITEM = ITEMS.register("generated/stone/tiles_1_slab", () -> new BlockItem(TILES_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> TILES_1_STAIRS = BLOCKS.register("generated/stone/tiles_1_stairs", () -> new ModStairs(TILES_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(TILES_1.get()))); public static final RegistryObject<Item> TILES_1_STAIRS_ITEM = ITEMS.register("generated/stone/tiles_1_stairs", () -> new BlockItem(TILES_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> TILES_2 = BLOCKS.register("generated/stone/tiles_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> TILES_2_ITEM = ITEMS.register("generated/stone/tiles_2", () -> new BlockItem(TILES_2.get(), itemBuilder())); public static final RegistryObject<Block> TILES_2_SLAB = BLOCKS.register("generated/stone/tiles_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(TILES_2.get()))); public static final RegistryObject<Item> TILES_2_SLAB_ITEM = ITEMS.register("generated/stone/tiles_2_slab", () -> new BlockItem(TILES_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> TILES_2_STAIRS = BLOCKS.register("generated/stone/tiles_2_stairs", () -> new ModStairs(TILES_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(TILES_2.get()))); public static final RegistryObject<Item> TILES_2_STAIRS_ITEM = ITEMS.register("generated/stone/tiles_2_stairs", () -> new BlockItem(TILES_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> TILES_3 = BLOCKS.register("generated/stone/tiles_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> TILES_3_ITEM = ITEMS.register("generated/stone/tiles_3", () -> new BlockItem(TILES_3.get(), itemBuilder())); public static final RegistryObject<Block> TILES_3_SLAB = BLOCKS.register("generated/stone/tiles_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(TILES_3.get()))); public static final RegistryObject<Item> TILES_3_SLAB_ITEM = ITEMS.register("generated/stone/tiles_3_slab", () -> new BlockItem(TILES_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> TILES_3_STAIRS = BLOCKS.register("generated/stone/tiles_3_stairs", () -> new ModStairs(TILES_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(TILES_3.get()))); public static final RegistryObject<Item> TILES_3_STAIRS_ITEM = ITEMS.register("generated/stone/tiles_3_stairs", () -> new BlockItem(TILES_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> TILES_4 = BLOCKS.register("generated/stone/tiles_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> TILES_4_ITEM = ITEMS.register("generated/stone/tiles_4", () -> new BlockItem(TILES_4.get(), itemBuilder())); public static final RegistryObject<Block> TILES_4_SLAB = BLOCKS.register("generated/stone/tiles_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(TILES_4.get()))); public static final RegistryObject<Item> TILES_4_SLAB_ITEM = ITEMS.register("generated/stone/tiles_4_slab", () -> new BlockItem(TILES_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> TILES_4_STAIRS = BLOCKS.register("generated/stone/tiles_4_stairs", () -> new ModStairs(TILES_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(TILES_4.get()))); public static final RegistryObject<Item> TILES_4_STAIRS_ITEM = ITEMS.register("generated/stone/tiles_4_stairs", () -> new BlockItem(TILES_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> TILES_5 = BLOCKS.register("generated/stone/tiles_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> TILES_5_ITEM = ITEMS.register("generated/stone/tiles_5", () -> new BlockItem(TILES_5.get(), itemBuilder())); public static final RegistryObject<Block> TILES_5_SLAB = BLOCKS.register("generated/stone/tiles_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(TILES_5.get()))); public static final RegistryObject<Item> TILES_5_SLAB_ITEM = ITEMS.register("generated/stone/tiles_5_slab", () -> new BlockItem(TILES_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> TILES_5_STAIRS = BLOCKS.register("generated/stone/tiles_5_stairs", () -> new ModStairs(TILES_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(TILES_5.get()))); public static final RegistryObject<Item> TILES_5_STAIRS_ITEM = ITEMS.register("generated/stone/tiles_5_stairs", () -> new BlockItem(TILES_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> WALLPAPER_1 = BLOCKS.register("generated/wood/wallpaper_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.WOOD).sound(SoundType.WOOD).strength(6f, 6f).lightLevel(state -> 0).explosionResistance(4f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> WALLPAPER_1_ITEM = ITEMS.register("generated/wood/wallpaper_1", () -> new BlockItem(WALLPAPER_1.get(), itemBuilder())); public static final RegistryObject<Block> WALLPAPER_1_SLAB = BLOCKS.register("generated/wood/wallpaper_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(WALLPAPER_1.get()))); public static final RegistryObject<Item> WALLPAPER_1_SLAB_ITEM = ITEMS.register("generated/wood/wallpaper_1_slab", () -> new BlockItem(WALLPAPER_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> WALLPAPER_1_STAIRS = BLOCKS.register("generated/wood/wallpaper_1_stairs", () -> new ModStairs(WALLPAPER_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(WALLPAPER_1.get()))); public static final RegistryObject<Item> WALLPAPER_1_STAIRS_ITEM = ITEMS.register("generated/wood/wallpaper_1_stairs", () -> new BlockItem(WALLPAPER_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_1 = BLOCKS.register("generated/stone/concrete_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_1_ITEM = ITEMS.register("generated/stone/concrete_1", () -> new BlockItem(CONCRETE_1.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_1_SLAB = BLOCKS.register("generated/stone/concrete_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_1.get()))); public static final RegistryObject<Item> CONCRETE_1_SLAB_ITEM = ITEMS.register("generated/stone/concrete_1_slab", () -> new BlockItem(CONCRETE_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_1_STAIRS = BLOCKS.register("generated/stone/concrete_1_stairs", () -> new ModStairs(CONCRETE_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_1.get()))); public static final RegistryObject<Item> CONCRETE_1_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_1_stairs", () -> new BlockItem(CONCRETE_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_2 = BLOCKS.register("generated/stone/concrete_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_2_ITEM = ITEMS.register("generated/stone/concrete_2", () -> new BlockItem(CONCRETE_2.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_2_SLAB = BLOCKS.register("generated/stone/concrete_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_2.get()))); public static final RegistryObject<Item> CONCRETE_2_SLAB_ITEM = ITEMS.register("generated/stone/concrete_2_slab", () -> new BlockItem(CONCRETE_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_2_STAIRS = BLOCKS.register("generated/stone/concrete_2_stairs", () -> new ModStairs(CONCRETE_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_2.get()))); public static final RegistryObject<Item> CONCRETE_2_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_2_stairs", () -> new BlockItem(CONCRETE_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_3 = BLOCKS.register("generated/stone/concrete_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_3_ITEM = ITEMS.register("generated/stone/concrete_3", () -> new BlockItem(CONCRETE_3.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_3_SLAB = BLOCKS.register("generated/stone/concrete_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_3.get()))); public static final RegistryObject<Item> CONCRETE_3_SLAB_ITEM = ITEMS.register("generated/stone/concrete_3_slab", () -> new BlockItem(CONCRETE_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_3_STAIRS = BLOCKS.register("generated/stone/concrete_3_stairs", () -> new ModStairs(CONCRETE_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_3.get()))); public static final RegistryObject<Item> CONCRETE_3_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_3_stairs", () -> new BlockItem(CONCRETE_3_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_4 = BLOCKS.register("generated/stone/concrete_4_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_4_ITEM = ITEMS.register("generated/stone/concrete_4", () -> new BlockItem(CONCRETE_4.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_4_SLAB = BLOCKS.register("generated/stone/concrete_4_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_4.get()))); public static final RegistryObject<Item> CONCRETE_4_SLAB_ITEM = ITEMS.register("generated/stone/concrete_4_slab", () -> new BlockItem(CONCRETE_4_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_4_STAIRS = BLOCKS.register("generated/stone/concrete_4_stairs", () -> new ModStairs(CONCRETE_4.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_4.get()))); public static final RegistryObject<Item> CONCRETE_4_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_4_stairs", () -> new BlockItem(CONCRETE_4_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_5 = BLOCKS.register("generated/stone/concrete_5_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_5_ITEM = ITEMS.register("generated/stone/concrete_5", () -> new BlockItem(CONCRETE_5.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_5_SLAB = BLOCKS.register("generated/stone/concrete_5_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_5.get()))); public static final RegistryObject<Item> CONCRETE_5_SLAB_ITEM = ITEMS.register("generated/stone/concrete_5_slab", () -> new BlockItem(CONCRETE_5_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_5_STAIRS = BLOCKS.register("generated/stone/concrete_5_stairs", () -> new ModStairs(CONCRETE_5.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_5.get()))); public static final RegistryObject<Item> CONCRETE_5_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_5_stairs", () -> new BlockItem(CONCRETE_5_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_6 = BLOCKS.register("generated/stone/concrete_6_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_6_ITEM = ITEMS.register("generated/stone/concrete_6", () -> new BlockItem(CONCRETE_6.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_6_SLAB = BLOCKS.register("generated/stone/concrete_6_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_6.get()))); public static final RegistryObject<Item> CONCRETE_6_SLAB_ITEM = ITEMS.register("generated/stone/concrete_6_slab", () -> new BlockItem(CONCRETE_6_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_6_STAIRS = BLOCKS.register("generated/stone/concrete_6_stairs", () -> new ModStairs(CONCRETE_6.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_6.get()))); public static final RegistryObject<Item> CONCRETE_6_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_6_stairs", () -> new BlockItem(CONCRETE_6_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_7 = BLOCKS.register("generated/stone/concrete_7_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> CONCRETE_7_ITEM = ITEMS.register("generated/stone/concrete_7", () -> new BlockItem(CONCRETE_7.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_7_SLAB = BLOCKS.register("generated/stone/concrete_7_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(CONCRETE_7.get()))); public static final RegistryObject<Item> CONCRETE_7_SLAB_ITEM = ITEMS.register("generated/stone/concrete_7_slab", () -> new BlockItem(CONCRETE_7_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> CONCRETE_7_STAIRS = BLOCKS.register("generated/stone/concrete_7_stairs", () -> new ModStairs(CONCRETE_7.get().defaultBlockState(), BlockBehaviour.Properties.copy(CONCRETE_7.get()))); public static final RegistryObject<Item> CONCRETE_7_STAIRS_ITEM = ITEMS.register("generated/stone/concrete_7_stairs", () -> new BlockItem(CONCRETE_7_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_1 = BLOCKS.register("generated/stone/stone_tiles_1_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> STONE_TILES_1_ITEM = ITEMS.register("generated/stone/stone_tiles_1", () -> new BlockItem(STONE_TILES_1.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_1_SLAB = BLOCKS.register("generated/stone/stone_tiles_1_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(STONE_TILES_1.get()))); public static final RegistryObject<Item> STONE_TILES_1_SLAB_ITEM = ITEMS.register("generated/stone/stone_tiles_1_slab", () -> new BlockItem(STONE_TILES_1_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_1_STAIRS = BLOCKS.register("generated/stone/stone_tiles_1_stairs", () -> new ModStairs(STONE_TILES_1.get().defaultBlockState(), BlockBehaviour.Properties.copy(STONE_TILES_1.get()))); public static final RegistryObject<Item> STONE_TILES_1_STAIRS_ITEM = ITEMS.register("generated/stone/stone_tiles_1_stairs", () -> new BlockItem(STONE_TILES_1_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_2 = BLOCKS.register("generated/stone/stone_tiles_2_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> STONE_TILES_2_ITEM = ITEMS.register("generated/stone/stone_tiles_2", () -> new BlockItem(STONE_TILES_2.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_2_SLAB = BLOCKS.register("generated/stone/stone_tiles_2_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(STONE_TILES_2.get()))); public static final RegistryObject<Item> STONE_TILES_2_SLAB_ITEM = ITEMS.register("generated/stone/stone_tiles_2_slab", () -> new BlockItem(STONE_TILES_2_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_2_STAIRS = BLOCKS.register("generated/stone/stone_tiles_2_stairs", () -> new ModStairs(STONE_TILES_2.get().defaultBlockState(), BlockBehaviour.Properties.copy(STONE_TILES_2.get()))); public static final RegistryObject<Item> STONE_TILES_2_STAIRS_ITEM = ITEMS.register("generated/stone/stone_tiles_2_stairs", () -> new BlockItem(STONE_TILES_2_STAIRS.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_3 = BLOCKS.register("generated/stone/stone_tiles_3_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(8f, 8f).lightLevel(state -> 0).explosionResistance(8f).requiresCorrectToolForDrops())); public static final RegistryObject<Item> STONE_TILES_3_ITEM = ITEMS.register("generated/stone/stone_tiles_3", () -> new BlockItem(STONE_TILES_3.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_3_SLAB = BLOCKS.register("generated/stone/stone_tiles_3_slab", () -> new SlabBlock(BlockBehaviour.Properties.copy(STONE_TILES_3.get()))); public static final RegistryObject<Item> STONE_TILES_3_SLAB_ITEM = ITEMS.register("generated/stone/stone_tiles_3_slab", () -> new BlockItem(STONE_TILES_3_SLAB.get(), itemBuilder())); public static final RegistryObject<Block> STONE_TILES_3_STAIRS = BLOCKS.register("generated/stone/stone_tiles_3_stairs", () -> new ModStairs(STONE_TILES_3.get().defaultBlockState(), BlockBehaviour.Properties.copy(STONE_TILES_3.get()))); public static final RegistryObject<Item> STONE_TILES_3_STAIRS_ITEM = ITEMS.register("generated/stone/stone_tiles_3_stairs", () -> new BlockItem(STONE_TILES_3_STAIRS.get(), itemBuilder())); /*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###*/ private static Item.Properties itemBuilder() {
return new Item.Properties().tab(Services.PLATFORM.getCreativeTab());
1
2023-11-06 12:50:10+00:00
24k
dingodb/dingo-expr
test/src/test/java/io/dingodb/expr/test/cases/EvalConstProvider.java
[ { "identifier": "Types", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/Types.java", "snippet": "public final class Types {\n public static final NullType NULL = new NullType();\n public static final IntType INT = new IntType();\n public static final LongType LONG = new LongType();...
import com.google.common.collect.ImmutableMap; import io.dingodb.expr.runtime.type.Types; import io.dingodb.expr.runtime.utils.DateTimeUtils; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static io.dingodb.expr.runtime.expr.Exprs.ABS; import static io.dingodb.expr.runtime.expr.Exprs.ABS_C; import static io.dingodb.expr.runtime.expr.Exprs.ACOS; import static io.dingodb.expr.runtime.expr.Exprs.ADD; import static io.dingodb.expr.runtime.expr.Exprs.AND; import static io.dingodb.expr.runtime.expr.Exprs.AND_FUN; import static io.dingodb.expr.runtime.expr.Exprs.ARRAY; import static io.dingodb.expr.runtime.expr.Exprs.ASIN; import static io.dingodb.expr.runtime.expr.Exprs.ATAN; import static io.dingodb.expr.runtime.expr.Exprs.CASE; import static io.dingodb.expr.runtime.expr.Exprs.CEIL; import static io.dingodb.expr.runtime.expr.Exprs.CHAR_LENGTH; import static io.dingodb.expr.runtime.expr.Exprs.CONCAT; import static io.dingodb.expr.runtime.expr.Exprs.COS; import static io.dingodb.expr.runtime.expr.Exprs.COSH; import static io.dingodb.expr.runtime.expr.Exprs.DATEDIFF; import static io.dingodb.expr.runtime.expr.Exprs.DATE_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.DATE_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.DIV; import static io.dingodb.expr.runtime.expr.Exprs.EQ; import static io.dingodb.expr.runtime.expr.Exprs.EXP; import static io.dingodb.expr.runtime.expr.Exprs.FLOOR; import static io.dingodb.expr.runtime.expr.Exprs.FORMAT; import static io.dingodb.expr.runtime.expr.Exprs.FROM_UNIXTIME; import static io.dingodb.expr.runtime.expr.Exprs.GE; import static io.dingodb.expr.runtime.expr.Exprs.GT; import static io.dingodb.expr.runtime.expr.Exprs.HEX; import static io.dingodb.expr.runtime.expr.Exprs.INDEX; import static io.dingodb.expr.runtime.expr.Exprs.IS_FALSE; import static io.dingodb.expr.runtime.expr.Exprs.IS_NULL; import static io.dingodb.expr.runtime.expr.Exprs.IS_TRUE; import static io.dingodb.expr.runtime.expr.Exprs.LE; import static io.dingodb.expr.runtime.expr.Exprs.LEFT; import static io.dingodb.expr.runtime.expr.Exprs.LIST; import static io.dingodb.expr.runtime.expr.Exprs.LOCATE2; import static io.dingodb.expr.runtime.expr.Exprs.LOCATE3; import static io.dingodb.expr.runtime.expr.Exprs.LOG; import static io.dingodb.expr.runtime.expr.Exprs.LOWER; import static io.dingodb.expr.runtime.expr.Exprs.LT; import static io.dingodb.expr.runtime.expr.Exprs.LTRIM1; import static io.dingodb.expr.runtime.expr.Exprs.LTRIM2; import static io.dingodb.expr.runtime.expr.Exprs.MAP; import static io.dingodb.expr.runtime.expr.Exprs.MATCHES; import static io.dingodb.expr.runtime.expr.Exprs.MATCHES_NC; import static io.dingodb.expr.runtime.expr.Exprs.MAX; import static io.dingodb.expr.runtime.expr.Exprs.MID2; import static io.dingodb.expr.runtime.expr.Exprs.MID3; import static io.dingodb.expr.runtime.expr.Exprs.MIN; import static io.dingodb.expr.runtime.expr.Exprs.MOD; import static io.dingodb.expr.runtime.expr.Exprs.MUL; import static io.dingodb.expr.runtime.expr.Exprs.NE; import static io.dingodb.expr.runtime.expr.Exprs.NEG; import static io.dingodb.expr.runtime.expr.Exprs.NOT; import static io.dingodb.expr.runtime.expr.Exprs.OR; import static io.dingodb.expr.runtime.expr.Exprs.OR_FUN; import static io.dingodb.expr.runtime.expr.Exprs.POS; import static io.dingodb.expr.runtime.expr.Exprs.POW; import static io.dingodb.expr.runtime.expr.Exprs.REPEAT; import static io.dingodb.expr.runtime.expr.Exprs.REPLACE; import static io.dingodb.expr.runtime.expr.Exprs.REVERSE; import static io.dingodb.expr.runtime.expr.Exprs.RIGHT; import static io.dingodb.expr.runtime.expr.Exprs.ROUND1; import static io.dingodb.expr.runtime.expr.Exprs.ROUND2; import static io.dingodb.expr.runtime.expr.Exprs.RTRIM1; import static io.dingodb.expr.runtime.expr.Exprs.RTRIM2; import static io.dingodb.expr.runtime.expr.Exprs.SIN; import static io.dingodb.expr.runtime.expr.Exprs.SINH; import static io.dingodb.expr.runtime.expr.Exprs.SLICE; import static io.dingodb.expr.runtime.expr.Exprs.SUB; import static io.dingodb.expr.runtime.expr.Exprs.SUBSTR2; import static io.dingodb.expr.runtime.expr.Exprs.SUBSTR3; import static io.dingodb.expr.runtime.expr.Exprs.TAN; import static io.dingodb.expr.runtime.expr.Exprs.TANH; import static io.dingodb.expr.runtime.expr.Exprs.TIMESTAMP_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.TIMESTAMP_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.TIME_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.TIME_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TO_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TO_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TRIM1; import static io.dingodb.expr.runtime.expr.Exprs.TRIM2; import static io.dingodb.expr.runtime.expr.Exprs.UNIX_TIMESTAMP1; import static io.dingodb.expr.runtime.expr.Exprs.UPPER; import static io.dingodb.expr.runtime.expr.Exprs._CP1; import static io.dingodb.expr.runtime.expr.Exprs._CP2; import static io.dingodb.expr.runtime.expr.Exprs._CTF; import static io.dingodb.expr.runtime.expr.Exprs.op; import static io.dingodb.expr.runtime.expr.Exprs.val; import static io.dingodb.expr.runtime.expr.Val.NULL; import static io.dingodb.expr.runtime.expr.Val.NULL_BOOL; import static io.dingodb.expr.runtime.expr.Val.NULL_BYTES; import static io.dingodb.expr.runtime.expr.Val.NULL_DATE; import static io.dingodb.expr.runtime.expr.Val.NULL_DECIMAL; import static io.dingodb.expr.runtime.expr.Val.NULL_DOUBLE; import static io.dingodb.expr.runtime.expr.Val.NULL_FLOAT; import static io.dingodb.expr.runtime.expr.Val.NULL_INT; import static io.dingodb.expr.runtime.expr.Val.NULL_LONG; import static io.dingodb.expr.runtime.expr.Val.NULL_STRING; import static io.dingodb.expr.runtime.expr.Val.NULL_TIME; import static io.dingodb.expr.runtime.expr.Val.NULL_TIMESTAMP; import static io.dingodb.expr.test.ExprsHelper.bytes; import static io.dingodb.expr.test.ExprsHelper.date; import static io.dingodb.expr.test.ExprsHelper.dec; import static io.dingodb.expr.test.ExprsHelper.sec; import static io.dingodb.expr.test.ExprsHelper.time; import static io.dingodb.expr.test.ExprsHelper.ts; import static org.junit.jupiter.params.provider.Arguments.arguments;
16,011
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.test.cases; public class EvalConstProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Stream.of( // Values arguments(val(1), 1), arguments(val(2L), 2L), arguments(val(3.3f), 3.3f), arguments(val(4.4), 4.4), arguments(val(true), true), arguments(val(false), false), arguments(dec(5.5), BigDecimal.valueOf(5.5)), arguments(val("abc"), "abc"), arguments(bytes("123"), "123".getBytes(StandardCharsets.UTF_8)), arguments(date(1L), new Date(sec(1L))), arguments(time(2L), new Time(sec(2L))), arguments(ts(3L), new Timestamp(sec(3L))), arguments(val(null), null), // Castings arguments(op(TO_INT, 1), 1), arguments(op(TO_INT, 1L), 1), arguments(op(TO_INT_C, 1L), 1), arguments(op(TO_INT, 1.4f), 1), arguments(op(TO_INT_C, 1.4f), 1), arguments(op(TO_INT, 1.5f), 2), arguments(op(TO_INT_C, 1.5f), 2), arguments(op(TO_INT, 1.4), 1), arguments(op(TO_INT, 1.5), 2), arguments(op(TO_INT, true), 1), arguments(op(TO_INT, false), 0), arguments(op(TO_INT, dec(1.4)), 1), arguments(op(TO_INT_C, dec(1.4)), 1), arguments(op(TO_INT, dec(1.5)), 2), arguments(op(TO_INT_C, dec(1.5)), 2), arguments(op(TO_INT, "10"), 10), arguments(op(TO_LONG, 1), 1L), arguments(op(TO_LONG, 1L), 1L), arguments(op(TO_LONG, 1.4f), 1L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.5f), 2L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.4), 1L), arguments(op(TO_LONG, 1.5), 2L), arguments(op(TO_LONG, true), 1L), arguments(op(TO_LONG, false), 0L), arguments(op(TO_LONG, dec(1.4)), 1L), arguments(op(TO_LONG, dec(1.5)), 2L), arguments(op(TO_LONG, "10"), 10L), arguments(op(TO_FLOAT, 1), 1.0f), arguments(op(TO_FLOAT, 1L), 1.0f), arguments(op(TO_FLOAT, 1.4f), 1.4f), arguments(op(TO_FLOAT, 1.4), 1.4f), arguments(op(TO_FLOAT, true), 1.0f), arguments(op(TO_FLOAT, false), 0.0f), arguments(op(TO_FLOAT, dec(1.4)), 1.4f), arguments(op(TO_FLOAT, "12.3"), 12.3f), arguments(op(TO_DOUBLE, 1), 1.0), arguments(op(TO_DOUBLE, 1L), 1.0), arguments(op(TO_DOUBLE, 1.4f), 1.4), arguments(op(TO_DOUBLE, 1.4), 1.4), arguments(op(TO_DOUBLE, true), 1.0), arguments(op(TO_DOUBLE, false), 0.0), arguments(op(TO_DOUBLE, dec(1.4)), 1.4), arguments(op(TO_DOUBLE, "12.3"), 12.3), arguments(op(TO_BOOL, 1), true), arguments(op(TO_BOOL, 0), false), arguments(op(TO_BOOL, 1L), true), arguments(op(TO_BOOL, 0L), false), arguments(op(TO_BOOL, 1.4f), true), arguments(op(TO_BOOL, 0.0f), false), arguments(op(TO_BOOL, 1.4), true), arguments(op(TO_BOOL, 0.0), false), arguments(op(TO_BOOL, true), true), arguments(op(TO_BOOL, false), false), arguments(op(TO_BOOL, val(BigDecimal.ONE)), true), arguments(op(TO_BOOL, val(BigDecimal.ZERO)), false), arguments(op(TO_DECIMAL, 1), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1L), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1.4f), BigDecimal.valueOf(1.4f)), arguments(op(TO_DECIMAL, 1.4), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, true), BigDecimal.ONE), arguments(op(TO_DECIMAL, false), BigDecimal.ZERO), arguments(op(TO_DECIMAL, dec(1.4)), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, "12.3"), BigDecimal.valueOf(12.3)), arguments(op(TO_STRING, 1), "1"), arguments(op(TO_STRING, 1L), "1"), arguments(op(TO_STRING, 1.4f), "1.4"), arguments(op(TO_STRING, 1.4), "1.4"), arguments(op(TO_STRING, true), "true"), arguments(op(TO_STRING, false), "false"), arguments(op(TO_STRING, dec(12.3)), "12.3"), arguments(op(TO_STRING, "abc"), "abc"), arguments(op(TO_BYTES, bytes("abc")), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_BYTES, "abc"), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_DATE, 1), new Date(sec(1L))), arguments(op(TO_DATE, 1L), new Date(sec(1L))), arguments(op(TO_DATE, "1970-01-01"), new Date(sec(0L))), arguments(op(TO_DATE, date(1L)), new Date(sec(1L))), arguments(op(TO_TIME, 1), new Time(sec(1L))), arguments(op(TO_TIME, 1L), new Time(sec(1L))), arguments(op(TO_TIME, "00:00:00"), new Time(sec(0L))), arguments(op(TO_TIME, time(1L)), new Time(sec(1L))), arguments(op(TO_TIMESTAMP, 1), new Timestamp(sec(1L))), arguments(op(TO_TIMESTAMP, 1L), new Timestamp(sec(1L))), arguments( op(TO_TIMESTAMP, "1970-01-01 00:00:00"), DateTimeUtils.parseTimestamp("1970-01-01 00:00:00") ), arguments(op(TO_TIMESTAMP, ts(1L)), new Timestamp(sec(1L))), // Arithmetics arguments(op(POS, 1), 1), arguments(op(POS, 1L), 1L), arguments(op(POS, 1.1f), 1.1f), arguments(op(POS, 1.1), 1.1), arguments(op(POS, dec(1.1)), BigDecimal.valueOf(1.1)),
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.test.cases; public class EvalConstProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Stream.of( // Values arguments(val(1), 1), arguments(val(2L), 2L), arguments(val(3.3f), 3.3f), arguments(val(4.4), 4.4), arguments(val(true), true), arguments(val(false), false), arguments(dec(5.5), BigDecimal.valueOf(5.5)), arguments(val("abc"), "abc"), arguments(bytes("123"), "123".getBytes(StandardCharsets.UTF_8)), arguments(date(1L), new Date(sec(1L))), arguments(time(2L), new Time(sec(2L))), arguments(ts(3L), new Timestamp(sec(3L))), arguments(val(null), null), // Castings arguments(op(TO_INT, 1), 1), arguments(op(TO_INT, 1L), 1), arguments(op(TO_INT_C, 1L), 1), arguments(op(TO_INT, 1.4f), 1), arguments(op(TO_INT_C, 1.4f), 1), arguments(op(TO_INT, 1.5f), 2), arguments(op(TO_INT_C, 1.5f), 2), arguments(op(TO_INT, 1.4), 1), arguments(op(TO_INT, 1.5), 2), arguments(op(TO_INT, true), 1), arguments(op(TO_INT, false), 0), arguments(op(TO_INT, dec(1.4)), 1), arguments(op(TO_INT_C, dec(1.4)), 1), arguments(op(TO_INT, dec(1.5)), 2), arguments(op(TO_INT_C, dec(1.5)), 2), arguments(op(TO_INT, "10"), 10), arguments(op(TO_LONG, 1), 1L), arguments(op(TO_LONG, 1L), 1L), arguments(op(TO_LONG, 1.4f), 1L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.5f), 2L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.4), 1L), arguments(op(TO_LONG, 1.5), 2L), arguments(op(TO_LONG, true), 1L), arguments(op(TO_LONG, false), 0L), arguments(op(TO_LONG, dec(1.4)), 1L), arguments(op(TO_LONG, dec(1.5)), 2L), arguments(op(TO_LONG, "10"), 10L), arguments(op(TO_FLOAT, 1), 1.0f), arguments(op(TO_FLOAT, 1L), 1.0f), arguments(op(TO_FLOAT, 1.4f), 1.4f), arguments(op(TO_FLOAT, 1.4), 1.4f), arguments(op(TO_FLOAT, true), 1.0f), arguments(op(TO_FLOAT, false), 0.0f), arguments(op(TO_FLOAT, dec(1.4)), 1.4f), arguments(op(TO_FLOAT, "12.3"), 12.3f), arguments(op(TO_DOUBLE, 1), 1.0), arguments(op(TO_DOUBLE, 1L), 1.0), arguments(op(TO_DOUBLE, 1.4f), 1.4), arguments(op(TO_DOUBLE, 1.4), 1.4), arguments(op(TO_DOUBLE, true), 1.0), arguments(op(TO_DOUBLE, false), 0.0), arguments(op(TO_DOUBLE, dec(1.4)), 1.4), arguments(op(TO_DOUBLE, "12.3"), 12.3), arguments(op(TO_BOOL, 1), true), arguments(op(TO_BOOL, 0), false), arguments(op(TO_BOOL, 1L), true), arguments(op(TO_BOOL, 0L), false), arguments(op(TO_BOOL, 1.4f), true), arguments(op(TO_BOOL, 0.0f), false), arguments(op(TO_BOOL, 1.4), true), arguments(op(TO_BOOL, 0.0), false), arguments(op(TO_BOOL, true), true), arguments(op(TO_BOOL, false), false), arguments(op(TO_BOOL, val(BigDecimal.ONE)), true), arguments(op(TO_BOOL, val(BigDecimal.ZERO)), false), arguments(op(TO_DECIMAL, 1), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1L), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1.4f), BigDecimal.valueOf(1.4f)), arguments(op(TO_DECIMAL, 1.4), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, true), BigDecimal.ONE), arguments(op(TO_DECIMAL, false), BigDecimal.ZERO), arguments(op(TO_DECIMAL, dec(1.4)), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, "12.3"), BigDecimal.valueOf(12.3)), arguments(op(TO_STRING, 1), "1"), arguments(op(TO_STRING, 1L), "1"), arguments(op(TO_STRING, 1.4f), "1.4"), arguments(op(TO_STRING, 1.4), "1.4"), arguments(op(TO_STRING, true), "true"), arguments(op(TO_STRING, false), "false"), arguments(op(TO_STRING, dec(12.3)), "12.3"), arguments(op(TO_STRING, "abc"), "abc"), arguments(op(TO_BYTES, bytes("abc")), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_BYTES, "abc"), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_DATE, 1), new Date(sec(1L))), arguments(op(TO_DATE, 1L), new Date(sec(1L))), arguments(op(TO_DATE, "1970-01-01"), new Date(sec(0L))), arguments(op(TO_DATE, date(1L)), new Date(sec(1L))), arguments(op(TO_TIME, 1), new Time(sec(1L))), arguments(op(TO_TIME, 1L), new Time(sec(1L))), arguments(op(TO_TIME, "00:00:00"), new Time(sec(0L))), arguments(op(TO_TIME, time(1L)), new Time(sec(1L))), arguments(op(TO_TIMESTAMP, 1), new Timestamp(sec(1L))), arguments(op(TO_TIMESTAMP, 1L), new Timestamp(sec(1L))), arguments( op(TO_TIMESTAMP, "1970-01-01 00:00:00"), DateTimeUtils.parseTimestamp("1970-01-01 00:00:00") ), arguments(op(TO_TIMESTAMP, ts(1L)), new Timestamp(sec(1L))), // Arithmetics arguments(op(POS, 1), 1), arguments(op(POS, 1L), 1L), arguments(op(POS, 1.1f), 1.1f), arguments(op(POS, 1.1), 1.1), arguments(op(POS, dec(1.1)), BigDecimal.valueOf(1.1)),
arguments(op(NEG, 1), -1),
53
2023-11-04 08:43:49+00:00
24k
conductor-oss/conductor
es6-persistence/src/main/java/com/netflix/conductor/es6/dao/index/ElasticSearchRestDAOV6.java
[ { "identifier": "EventExecution", "path": "common/src/main/java/com/netflix/conductor/common/metadata/events/EventExecution.java", "snippet": "@ProtoMessage\npublic class EventExecution {\n\n @ProtoEnum\n public enum Status {\n IN_PROGRESS,\n COMPLETED,\n FAILED,\n SKIP...
import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.util.*; import java.util.concurrent.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; import org.apache.http.nio.entity.NByteArrayEntity; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.util.EntityUtils; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.*; import org.elasticsearch.client.core.CountRequest; import org.elasticsearch.client.core.CountResponse; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.retry.support.RetryTemplate; import com.netflix.conductor.annotations.Trace; import com.netflix.conductor.common.metadata.events.EventExecution; import com.netflix.conductor.common.metadata.tasks.TaskExecLog; import com.netflix.conductor.common.run.SearchResult; import com.netflix.conductor.common.run.TaskSummary; import com.netflix.conductor.common.run.WorkflowSummary; import com.netflix.conductor.core.events.queue.Message; import com.netflix.conductor.core.exception.NonTransientException; import com.netflix.conductor.core.exception.TransientException; import com.netflix.conductor.dao.IndexDAO; import com.netflix.conductor.es6.config.ElasticSearchProperties; import com.netflix.conductor.es6.dao.query.parser.internal.ParserException; import com.netflix.conductor.metrics.Monitors; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.type.MapType; import com.fasterxml.jackson.databind.type.TypeFactory; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy;
18,539
} catch (Exception e) { Monitors.error(className, "indexWorkflow"); LOGGER.error("Failed to index workflow: {}", workflow.getWorkflowId(), e); } } @Override public CompletableFuture<Void> asyncIndexWorkflow(WorkflowSummary workflow) { return CompletableFuture.runAsync(() -> indexWorkflow(workflow), executorService); } @Override public void indexTask(TaskSummary task) { try { long startTime = Instant.now().toEpochMilli(); String taskId = task.getTaskId(); String docType = StringUtils.isBlank(docTypeOverride) ? TASK_DOC_TYPE : docTypeOverride; indexObject(taskIndexName, docType, taskId, task); long endTime = Instant.now().toEpochMilli(); LOGGER.debug( "Time taken {} for indexing task:{} in workflow: {}", endTime - startTime, taskId, task.getWorkflowId()); Monitors.recordESIndexTime("index_task", TASK_DOC_TYPE, endTime - startTime); Monitors.recordWorkerQueueSize( "indexQueue", ((ThreadPoolExecutor) executorService).getQueue().size()); } catch (Exception e) { LOGGER.error("Failed to index task: {}", task.getTaskId(), e); } } @Override public CompletableFuture<Void> asyncIndexTask(TaskSummary task) { return CompletableFuture.runAsync(() -> indexTask(task), executorService); } @Override public void addTaskExecutionLogs(List<TaskExecLog> taskExecLogs) { if (taskExecLogs.isEmpty()) { return; } long startTime = Instant.now().toEpochMilli(); BulkRequest bulkRequest = new BulkRequest(); for (TaskExecLog log : taskExecLogs) { byte[] docBytes; try { docBytes = objectMapper.writeValueAsBytes(log); } catch (JsonProcessingException e) { LOGGER.error("Failed to convert task log to JSON for task {}", log.getTaskId()); continue; } String docType = StringUtils.isBlank(docTypeOverride) ? LOG_DOC_TYPE : docTypeOverride; IndexRequest request = new IndexRequest(logIndexName, docType); request.source(docBytes, XContentType.JSON); bulkRequest.add(request); } try { elasticSearchClient.bulk(bulkRequest, RequestOptions.DEFAULT); long endTime = Instant.now().toEpochMilli(); LOGGER.debug("Time taken {} for indexing taskExecutionLogs", endTime - startTime); Monitors.recordESIndexTime( "index_task_execution_logs", LOG_DOC_TYPE, endTime - startTime); Monitors.recordWorkerQueueSize( "logQueue", ((ThreadPoolExecutor) logExecutorService).getQueue().size()); } catch (Exception e) { List<String> taskIds = taskExecLogs.stream().map(TaskExecLog::getTaskId).collect(Collectors.toList()); LOGGER.error("Failed to index task execution logs for tasks: {}", taskIds, e); } } @Override public CompletableFuture<Void> asyncAddTaskExecutionLogs(List<TaskExecLog> logs) { return CompletableFuture.runAsync(() -> addTaskExecutionLogs(logs), logExecutorService); } @Override public List<TaskExecLog> getTaskExecutionLogs(String taskId) { try { BoolQueryBuilder query = boolQueryBuilder("taskId='" + taskId + "'", "*"); // Create the searchObjectIdsViaExpression source SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(query); searchSourceBuilder.sort(new FieldSortBuilder("createdTime").order(SortOrder.ASC)); searchSourceBuilder.size(properties.getTaskLogResultLimit()); // Generate the actual request to send to ES. String docType = StringUtils.isBlank(docTypeOverride) ? LOG_DOC_TYPE : docTypeOverride; SearchRequest searchRequest = new SearchRequest(logIndexPrefix + "*"); searchRequest.types(docType); searchRequest.source(searchSourceBuilder); SearchResponse response = elasticSearchClient.search(searchRequest); return mapTaskExecLogsResponse(response); } catch (Exception e) { LOGGER.error("Failed to get task execution logs for task: {}", taskId, e); } return null; } private List<TaskExecLog> mapTaskExecLogsResponse(SearchResponse response) throws IOException { SearchHit[] hits = response.getHits().getHits(); List<TaskExecLog> logs = new ArrayList<>(hits.length); for (SearchHit hit : hits) { String source = hit.getSourceAsString(); TaskExecLog tel = objectMapper.readValue(source, TaskExecLog.class); logs.add(tel); } return logs; } @Override
/* * Copyright 2022 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.es6.dao.index; @Trace public class ElasticSearchRestDAOV6 extends ElasticSearchBaseDAO implements IndexDAO { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchRestDAOV6.class); private static final int CORE_POOL_SIZE = 6; private static final long KEEP_ALIVE_TIME = 1L; private static final String WORKFLOW_DOC_TYPE = "workflow"; private static final String TASK_DOC_TYPE = "task"; private static final String LOG_DOC_TYPE = "task_log"; private static final String EVENT_DOC_TYPE = "event"; private static final String MSG_DOC_TYPE = "message"; private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMWW"); private @interface HttpMethod { String GET = "GET"; String POST = "POST"; String PUT = "PUT"; String HEAD = "HEAD"; } private static final String className = ElasticSearchRestDAOV6.class.getSimpleName(); private final String workflowIndexName; private final String taskIndexName; private final String eventIndexPrefix; private String eventIndexName; private final String messageIndexPrefix; private String messageIndexName; private String logIndexName; private final String logIndexPrefix; private final String docTypeOverride; private final String clusterHealthColor; private final ObjectMapper objectMapper; private final RestHighLevelClient elasticSearchClient; private final RestClient elasticSearchAdminClient; private final ExecutorService executorService; private final ExecutorService logExecutorService; private final ConcurrentHashMap<String, BulkRequests> bulkRequests; private final int indexBatchSize; private final long asyncBufferFlushTimeout; private final ElasticSearchProperties properties; private final RetryTemplate retryTemplate; static { SIMPLE_DATE_FORMAT.setTimeZone(GMT); } public ElasticSearchRestDAOV6( RestClientBuilder restClientBuilder, RetryTemplate retryTemplate, ElasticSearchProperties properties, ObjectMapper objectMapper) { this.objectMapper = objectMapper; this.elasticSearchAdminClient = restClientBuilder.build(); this.elasticSearchClient = new RestHighLevelClient(restClientBuilder); this.clusterHealthColor = properties.getClusterHealthColor(); this.bulkRequests = new ConcurrentHashMap<>(); this.indexBatchSize = properties.getIndexBatchSize(); this.asyncBufferFlushTimeout = properties.getAsyncBufferFlushTimeout().toMillis(); this.properties = properties; this.indexPrefix = properties.getIndexPrefix(); if (!properties.isAutoIndexManagementEnabled() && StringUtils.isNotBlank(properties.getDocumentTypeOverride())) { docTypeOverride = properties.getDocumentTypeOverride(); } else { docTypeOverride = ""; } this.workflowIndexName = getIndexName(WORKFLOW_DOC_TYPE); this.taskIndexName = getIndexName(TASK_DOC_TYPE); this.logIndexPrefix = this.indexPrefix + "_" + LOG_DOC_TYPE; this.messageIndexPrefix = this.indexPrefix + "_" + MSG_DOC_TYPE; this.eventIndexPrefix = this.indexPrefix + "_" + EVENT_DOC_TYPE; int workerQueueSize = properties.getAsyncWorkerQueueSize(); int maximumPoolSize = properties.getAsyncMaxPoolSize(); // Set up a workerpool for performing async operations. this.executorService = new ThreadPoolExecutor( CORE_POOL_SIZE, maximumPoolSize, KEEP_ALIVE_TIME, TimeUnit.MINUTES, new LinkedBlockingQueue<>(workerQueueSize), (runnable, executor) -> { LOGGER.warn( "Request {} to async dao discarded in executor {}", runnable, executor); Monitors.recordDiscardedIndexingCount("indexQueue"); }); // Set up a workerpool for performing async operations for task_logs, event_executions, // message int corePoolSize = 1; maximumPoolSize = 2; long keepAliveTime = 30L; this.logExecutorService = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<>(workerQueueSize), (runnable, executor) -> { LOGGER.warn( "Request {} to async log dao discarded in executor {}", runnable, executor); Monitors.recordDiscardedIndexingCount("logQueue"); }); Executors.newSingleThreadScheduledExecutor() .scheduleAtFixedRate(this::flushBulkRequests, 60, 30, TimeUnit.SECONDS); this.retryTemplate = retryTemplate; } @PreDestroy private void shutdown() { LOGGER.info("Gracefully shutdown executor service"); shutdownExecutorService(logExecutorService); shutdownExecutorService(executorService); } private void shutdownExecutorService(ExecutorService execService) { try { execService.shutdown(); if (execService.awaitTermination(30, TimeUnit.SECONDS)) { LOGGER.debug("tasks completed, shutting down"); } else { LOGGER.warn("Forcing shutdown after waiting for 30 seconds"); execService.shutdownNow(); } } catch (InterruptedException ie) { LOGGER.warn( "Shutdown interrupted, invoking shutdownNow on scheduledThreadPoolExecutor for delay queue"); execService.shutdownNow(); Thread.currentThread().interrupt(); } } @Override @PostConstruct public void setup() throws Exception { waitForHealthyCluster(); if (properties.isAutoIndexManagementEnabled()) { createIndexesTemplates(); createWorkflowIndex(); createTaskIndex(); } } private void createIndexesTemplates() { try { initIndexesTemplates(); updateIndexesNames(); Executors.newScheduledThreadPool(1) .scheduleAtFixedRate(this::updateIndexesNames, 0, 1, TimeUnit.HOURS); } catch (Exception e) { LOGGER.error("Error creating index templates!", e); } } private void initIndexesTemplates() { initIndexTemplate(LOG_DOC_TYPE); initIndexTemplate(EVENT_DOC_TYPE); initIndexTemplate(MSG_DOC_TYPE); } /** Initializes the index with the required templates and mappings. */ private void initIndexTemplate(String type) { String template = "template_" + type; try { if (doesResourceNotExist("/_template/" + template)) { LOGGER.info("Creating the index template '" + template + "'"); InputStream stream = ElasticSearchDAOV6.class.getResourceAsStream("/" + template + ".json"); byte[] templateSource = IOUtils.toByteArray(stream); HttpEntity entity = new NByteArrayEntity(templateSource, ContentType.APPLICATION_JSON); elasticSearchAdminClient.performRequest( HttpMethod.PUT, "/_template/" + template, Collections.emptyMap(), entity); } } catch (Exception e) { LOGGER.error("Failed to init " + template, e); } } private void updateIndexesNames() { logIndexName = updateIndexName(LOG_DOC_TYPE); eventIndexName = updateIndexName(EVENT_DOC_TYPE); messageIndexName = updateIndexName(MSG_DOC_TYPE); } private String updateIndexName(String type) { String indexName = this.indexPrefix + "_" + type + "_" + SIMPLE_DATE_FORMAT.format(new Date()); try { addIndex(indexName); return indexName; } catch (IOException e) { LOGGER.error("Failed to update log index name: {}", indexName, e); throw new NonTransientException("Failed to update log index name: " + indexName, e); } } private void createWorkflowIndex() { String indexName = getIndexName(WORKFLOW_DOC_TYPE); try { addIndex(indexName); } catch (IOException e) { LOGGER.error("Failed to initialize index '{}'", indexName, e); } try { addMappingToIndex(indexName, WORKFLOW_DOC_TYPE, "/mappings_docType_workflow.json"); } catch (IOException e) { LOGGER.error("Failed to add {} mapping", WORKFLOW_DOC_TYPE); } } private void createTaskIndex() { String indexName = getIndexName(TASK_DOC_TYPE); try { addIndex(indexName); } catch (IOException e) { LOGGER.error("Failed to initialize index '{}'", indexName, e); } try { addMappingToIndex(indexName, TASK_DOC_TYPE, "/mappings_docType_task.json"); } catch (IOException e) { LOGGER.error("Failed to add {} mapping", TASK_DOC_TYPE); } } /** * Waits for the ES cluster to become green. * * @throws Exception If there is an issue connecting with the ES cluster. */ private void waitForHealthyCluster() throws Exception { Map<String, String> params = new HashMap<>(); params.put("wait_for_status", this.clusterHealthColor); params.put("timeout", "30s"); elasticSearchAdminClient.performRequest("GET", "/_cluster/health", params); } /** * Adds an index to elasticsearch if it does not exist. * * @param index The name of the index to create. * @throws IOException If an error occurred during requests to ES. */ private void addIndex(final String index) throws IOException { LOGGER.info("Adding index '{}'...", index); String resourcePath = "/" + index; if (doesResourceNotExist(resourcePath)) { try { ObjectNode setting = objectMapper.createObjectNode(); ObjectNode indexSetting = objectMapper.createObjectNode(); indexSetting.put("number_of_shards", properties.getIndexShardCount()); indexSetting.put("number_of_replicas", properties.getIndexReplicasCount()); setting.set("index", indexSetting); elasticSearchAdminClient.performRequest( HttpMethod.PUT, resourcePath, Collections.emptyMap(), new NStringEntity(setting.toString(), ContentType.APPLICATION_JSON)); LOGGER.info("Added '{}' index", index); } catch (ResponseException e) { boolean errorCreatingIndex = true; Response errorResponse = e.getResponse(); if (errorResponse.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) { JsonNode root = objectMapper.readTree(EntityUtils.toString(errorResponse.getEntity())); String errorCode = root.get("error").get("type").asText(); if ("index_already_exists_exception".equals(errorCode)) { errorCreatingIndex = false; } } if (errorCreatingIndex) { throw e; } } } else { LOGGER.info("Index '{}' already exists", index); } } /** * Adds a mapping type to an index if it does not exist. * * @param index The name of the index. * @param mappingType The name of the mapping type. * @param mappingFilename The name of the mapping file to use to add the mapping if it does not * exist. * @throws IOException If an error occurred during requests to ES. */ private void addMappingToIndex( final String index, final String mappingType, final String mappingFilename) throws IOException { LOGGER.info("Adding '{}' mapping to index '{}'...", mappingType, index); String resourcePath = "/" + index + "/_mapping/" + mappingType; if (doesResourceNotExist(resourcePath)) { HttpEntity entity = new NByteArrayEntity( loadTypeMappingSource(mappingFilename).getBytes(), ContentType.APPLICATION_JSON); elasticSearchAdminClient.performRequest( HttpMethod.PUT, resourcePath, Collections.emptyMap(), entity); LOGGER.info("Added '{}' mapping", mappingType); } else { LOGGER.info("Mapping '{}' already exists", mappingType); } } /** * Determines whether a resource exists in ES. This will call a GET method to a particular path * and return true if status 200; false otherwise. * * @param resourcePath The path of the resource to get. * @return True if it exists; false otherwise. * @throws IOException If an error occurred during requests to ES. */ public boolean doesResourceExist(final String resourcePath) throws IOException { Response response = elasticSearchAdminClient.performRequest(HttpMethod.HEAD, resourcePath); return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } /** * The inverse of doesResourceExist. * * @param resourcePath The path of the resource to check. * @return True if it does not exist; false otherwise. * @throws IOException If an error occurred during requests to ES. */ public boolean doesResourceNotExist(final String resourcePath) throws IOException { return !doesResourceExist(resourcePath); } @Override public void indexWorkflow(WorkflowSummary workflow) { try { long startTime = Instant.now().toEpochMilli(); String workflowId = workflow.getWorkflowId(); byte[] docBytes = objectMapper.writeValueAsBytes(workflow); String docType = StringUtils.isBlank(docTypeOverride) ? WORKFLOW_DOC_TYPE : docTypeOverride; IndexRequest request = new IndexRequest(workflowIndexName, docType, workflowId); request.source(docBytes, XContentType.JSON); elasticSearchClient.index(request, RequestOptions.DEFAULT); long endTime = Instant.now().toEpochMilli(); LOGGER.debug( "Time taken {} for indexing workflow: {}", endTime - startTime, workflowId); Monitors.recordESIndexTime("index_workflow", WORKFLOW_DOC_TYPE, endTime - startTime); Monitors.recordWorkerQueueSize( "indexQueue", ((ThreadPoolExecutor) executorService).getQueue().size()); } catch (Exception e) { Monitors.error(className, "indexWorkflow"); LOGGER.error("Failed to index workflow: {}", workflow.getWorkflowId(), e); } } @Override public CompletableFuture<Void> asyncIndexWorkflow(WorkflowSummary workflow) { return CompletableFuture.runAsync(() -> indexWorkflow(workflow), executorService); } @Override public void indexTask(TaskSummary task) { try { long startTime = Instant.now().toEpochMilli(); String taskId = task.getTaskId(); String docType = StringUtils.isBlank(docTypeOverride) ? TASK_DOC_TYPE : docTypeOverride; indexObject(taskIndexName, docType, taskId, task); long endTime = Instant.now().toEpochMilli(); LOGGER.debug( "Time taken {} for indexing task:{} in workflow: {}", endTime - startTime, taskId, task.getWorkflowId()); Monitors.recordESIndexTime("index_task", TASK_DOC_TYPE, endTime - startTime); Monitors.recordWorkerQueueSize( "indexQueue", ((ThreadPoolExecutor) executorService).getQueue().size()); } catch (Exception e) { LOGGER.error("Failed to index task: {}", task.getTaskId(), e); } } @Override public CompletableFuture<Void> asyncIndexTask(TaskSummary task) { return CompletableFuture.runAsync(() -> indexTask(task), executorService); } @Override public void addTaskExecutionLogs(List<TaskExecLog> taskExecLogs) { if (taskExecLogs.isEmpty()) { return; } long startTime = Instant.now().toEpochMilli(); BulkRequest bulkRequest = new BulkRequest(); for (TaskExecLog log : taskExecLogs) { byte[] docBytes; try { docBytes = objectMapper.writeValueAsBytes(log); } catch (JsonProcessingException e) { LOGGER.error("Failed to convert task log to JSON for task {}", log.getTaskId()); continue; } String docType = StringUtils.isBlank(docTypeOverride) ? LOG_DOC_TYPE : docTypeOverride; IndexRequest request = new IndexRequest(logIndexName, docType); request.source(docBytes, XContentType.JSON); bulkRequest.add(request); } try { elasticSearchClient.bulk(bulkRequest, RequestOptions.DEFAULT); long endTime = Instant.now().toEpochMilli(); LOGGER.debug("Time taken {} for indexing taskExecutionLogs", endTime - startTime); Monitors.recordESIndexTime( "index_task_execution_logs", LOG_DOC_TYPE, endTime - startTime); Monitors.recordWorkerQueueSize( "logQueue", ((ThreadPoolExecutor) logExecutorService).getQueue().size()); } catch (Exception e) { List<String> taskIds = taskExecLogs.stream().map(TaskExecLog::getTaskId).collect(Collectors.toList()); LOGGER.error("Failed to index task execution logs for tasks: {}", taskIds, e); } } @Override public CompletableFuture<Void> asyncAddTaskExecutionLogs(List<TaskExecLog> logs) { return CompletableFuture.runAsync(() -> addTaskExecutionLogs(logs), logExecutorService); } @Override public List<TaskExecLog> getTaskExecutionLogs(String taskId) { try { BoolQueryBuilder query = boolQueryBuilder("taskId='" + taskId + "'", "*"); // Create the searchObjectIdsViaExpression source SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(query); searchSourceBuilder.sort(new FieldSortBuilder("createdTime").order(SortOrder.ASC)); searchSourceBuilder.size(properties.getTaskLogResultLimit()); // Generate the actual request to send to ES. String docType = StringUtils.isBlank(docTypeOverride) ? LOG_DOC_TYPE : docTypeOverride; SearchRequest searchRequest = new SearchRequest(logIndexPrefix + "*"); searchRequest.types(docType); searchRequest.source(searchSourceBuilder); SearchResponse response = elasticSearchClient.search(searchRequest); return mapTaskExecLogsResponse(response); } catch (Exception e) { LOGGER.error("Failed to get task execution logs for task: {}", taskId, e); } return null; } private List<TaskExecLog> mapTaskExecLogsResponse(SearchResponse response) throws IOException { SearchHit[] hits = response.getHits().getHits(); List<TaskExecLog> logs = new ArrayList<>(hits.length); for (SearchHit hit : hits) { String source = hit.getSourceAsString(); TaskExecLog tel = objectMapper.readValue(source, TaskExecLog.class); logs.add(tel); } return logs; } @Override
public List<Message> getMessages(String queue) {
5
2023-12-08 06:06:09+00:00
24k
10cks/fofaEX
src/main/java/Main.java
[ { "identifier": "CommonExecute", "path": "src/main/java/plugins/CommonExecute.java", "snippet": "public class CommonExecute {\n\n public static JTable table = new JTable(); // 表格\n\n public static void exportTableToExcel(JTable table) {\n XSSFWorkbook workbook = new XSSFWorkbook();\n\n ...
import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import javax.swing.BorderFactory; import javax.swing.event.*; import java.awt.Color; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import plugins.CommonExecute; import plugins.CommonTemplate; import plugins.FofaHack; import tableInit.HighlightRenderer; import tableInit.RightClickFunctions; import javax.swing.table.*; import javax.swing.text.Document; import javax.swing.undo.UndoManager; import static java.awt.BorderLayout.*; import static java.lang.Thread.sleep; import static plugins.CommonTemplate.saveTableData; import static plugins.CommonTemplate.switchTab; import static tableInit.GetjTableHeader.adjustColumnWidths; import static tableInit.GetjTableHeader.getjTableHeader; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors;
15,155
public class Main { // 创建输入框 private static JTextField fofaUrl = createTextField("https://fofa.info"); private static JTextField fofaEmail = createTextField("当前版本不需要输入邮箱"); private static JTextField fofaKey = createTextField("请输入API key"); private static String rulesPath = "rules.txt"; private static String accountsPath = "accounts.json"; // 设置 field 规则 private static boolean hostMark = true; private static boolean ipMark = true; private static boolean portMark = true; private static boolean protocolMark = true; private static boolean titleMark = true; private static boolean domainMark = true; private static boolean linkMark = true; private static boolean icpMark = false; private static boolean cityMark = false; private static boolean countryMark = false; /* 下面未完成 */ private static boolean country_nameMark = false; private static boolean regionMark = false; private static boolean longitudeMark = false; private static boolean latitudeMark = false; private static boolean asNumberMark = false; private static boolean asOrganizationMark = false; private static boolean osMark = false; private static boolean serverMark = false; private static boolean jarmMark = false; private static boolean headerMark = false; private static boolean bannerMark = false; private static boolean baseProtocolMark = false; private static boolean certsIssuerOrgMark = false; private static boolean certsIssuerCnMark = false; private static boolean certsSubjectOrgMark = false; private static boolean certsSubjectCnMark = false; private static boolean tlsJa3sMark = false; private static boolean tlsVersionMark = false; private static boolean productMark = false; private static boolean productCategoryMark = false; private static boolean versionMark = false; private static boolean lastupdatetimeMark = false; private static boolean cnameMark = false; private static boolean iconHashMark = false; private static boolean certsValidMark = false; private static boolean cnameDomainMark = false; private static boolean bodyMark = false; private static boolean iconMark = false; private static boolean fidMark = false; private static boolean structinfoMark = false; private static boolean scrollPaneMark = true; // 标记 private static boolean exportButtonAdded = false; private static boolean timeAdded = false; private static JLabel timeLabel; private static int queryTotalNumber; private static int numberOfItems; private static int currentPage = 1; private static boolean setFull = true; private static int sizeSetting = 10000; private static boolean openFileMark = false; // 创建全局数据表 private static JTable table; // 在类的成员变量中创建弹出菜单 private static JPopupMenu popupMenu = new JPopupMenu(); private static JMenuItem itemSelectColumn = new JMenuItem("选择当前整列"); private static JMenuItem itemDeselectColumn = new JMenuItem("取消选择整列"); private static JMenuItem itemOpenLink = new JMenuItem("打开链接"); static JMenuItem itemCopy = new JMenuItem("复制"); private static JMenuItem itemSearch = new JMenuItem("表格搜索"); private static File lastOpenedPath; // 添加一个成员变量来保存上次打开的文件路径 static TableCellRenderer highlightRenderer = new HighlightRenderer(); private static TableCellRenderer defaultRenderer; private static JTabbedPane tabbedPane0; public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, FileNotFoundException { JFrame jFrame = new JFrame("fofaEX"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try { URL resource = Main.class.getResource("icon.png"); jFrame.setIconImage((new ImageIcon(resource).getImage())); //给Frame设置图标 } catch (Exception e) { System.out.println(e); } // 设置外观风格 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // 创建 CardLayout 布局管理器 CardLayout cardLayout = new CardLayout(); jFrame.setLayout(cardLayout); // 创建 tab 面板 tabbedPane0 = new JTabbedPane(); // 创建菜单栏 JMenuBar menuBar = new JMenuBar(); // 在JFrame中添加菜单栏 jFrame.setJMenuBar(menuBar); // 创建"账户设置"菜单项 JMenu settingsMenu = new JMenu("账户设置"); JMenuItem changePasswordMenuItem = new JMenuItem("FOFA API"); settingsMenu.add(changePasswordMenuItem); menuBar.add(settingsMenu); // 创建"搜索设置"菜单项 JMenu configureMenu = new JMenu("查询设置"); JMenuItem configureMenuItem = new JMenuItem("默认查询数量"); JMenuItem configureFullItem = new JMenuItem("默认查询区间"); JCheckBox defaultCheckFullBox = new JCheckBox("是否默认仅查询近一年数据?", false); defaultCheckFullBox.setFocusPainted(false); configureMenu.add(configureMenuItem); configureMenu.add(configureFullItem); menuBar.add(configureMenu); // 创建 “实验功能” 菜单项 JMenu labMenu = new JMenu("实验功能"); JMenuItem openFileMenuItem = new JMenuItem("打开文件"); JMenuItem iconHashLabMenuItem = new JMenuItem("iconHash 计算"); JMenu pluginMenu = new JMenu("插件模式"); JMenu fofaHackMenu = new JMenu("Fofa-Hack"); JMenuItem fofaHackMenuItemRun = new JMenuItem("运行"); JMenuItem fofaHackMenuItemSetting = new JMenuItem("设置"); JMenuItem fofaHackMenuItemAbout = new JMenuItem("关于");
public class Main { // 创建输入框 private static JTextField fofaUrl = createTextField("https://fofa.info"); private static JTextField fofaEmail = createTextField("当前版本不需要输入邮箱"); private static JTextField fofaKey = createTextField("请输入API key"); private static String rulesPath = "rules.txt"; private static String accountsPath = "accounts.json"; // 设置 field 规则 private static boolean hostMark = true; private static boolean ipMark = true; private static boolean portMark = true; private static boolean protocolMark = true; private static boolean titleMark = true; private static boolean domainMark = true; private static boolean linkMark = true; private static boolean icpMark = false; private static boolean cityMark = false; private static boolean countryMark = false; /* 下面未完成 */ private static boolean country_nameMark = false; private static boolean regionMark = false; private static boolean longitudeMark = false; private static boolean latitudeMark = false; private static boolean asNumberMark = false; private static boolean asOrganizationMark = false; private static boolean osMark = false; private static boolean serverMark = false; private static boolean jarmMark = false; private static boolean headerMark = false; private static boolean bannerMark = false; private static boolean baseProtocolMark = false; private static boolean certsIssuerOrgMark = false; private static boolean certsIssuerCnMark = false; private static boolean certsSubjectOrgMark = false; private static boolean certsSubjectCnMark = false; private static boolean tlsJa3sMark = false; private static boolean tlsVersionMark = false; private static boolean productMark = false; private static boolean productCategoryMark = false; private static boolean versionMark = false; private static boolean lastupdatetimeMark = false; private static boolean cnameMark = false; private static boolean iconHashMark = false; private static boolean certsValidMark = false; private static boolean cnameDomainMark = false; private static boolean bodyMark = false; private static boolean iconMark = false; private static boolean fidMark = false; private static boolean structinfoMark = false; private static boolean scrollPaneMark = true; // 标记 private static boolean exportButtonAdded = false; private static boolean timeAdded = false; private static JLabel timeLabel; private static int queryTotalNumber; private static int numberOfItems; private static int currentPage = 1; private static boolean setFull = true; private static int sizeSetting = 10000; private static boolean openFileMark = false; // 创建全局数据表 private static JTable table; // 在类的成员变量中创建弹出菜单 private static JPopupMenu popupMenu = new JPopupMenu(); private static JMenuItem itemSelectColumn = new JMenuItem("选择当前整列"); private static JMenuItem itemDeselectColumn = new JMenuItem("取消选择整列"); private static JMenuItem itemOpenLink = new JMenuItem("打开链接"); static JMenuItem itemCopy = new JMenuItem("复制"); private static JMenuItem itemSearch = new JMenuItem("表格搜索"); private static File lastOpenedPath; // 添加一个成员变量来保存上次打开的文件路径 static TableCellRenderer highlightRenderer = new HighlightRenderer(); private static TableCellRenderer defaultRenderer; private static JTabbedPane tabbedPane0; public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, FileNotFoundException { JFrame jFrame = new JFrame("fofaEX"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try { URL resource = Main.class.getResource("icon.png"); jFrame.setIconImage((new ImageIcon(resource).getImage())); //给Frame设置图标 } catch (Exception e) { System.out.println(e); } // 设置外观风格 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // 创建 CardLayout 布局管理器 CardLayout cardLayout = new CardLayout(); jFrame.setLayout(cardLayout); // 创建 tab 面板 tabbedPane0 = new JTabbedPane(); // 创建菜单栏 JMenuBar menuBar = new JMenuBar(); // 在JFrame中添加菜单栏 jFrame.setJMenuBar(menuBar); // 创建"账户设置"菜单项 JMenu settingsMenu = new JMenu("账户设置"); JMenuItem changePasswordMenuItem = new JMenuItem("FOFA API"); settingsMenu.add(changePasswordMenuItem); menuBar.add(settingsMenu); // 创建"搜索设置"菜单项 JMenu configureMenu = new JMenu("查询设置"); JMenuItem configureMenuItem = new JMenuItem("默认查询数量"); JMenuItem configureFullItem = new JMenuItem("默认查询区间"); JCheckBox defaultCheckFullBox = new JCheckBox("是否默认仅查询近一年数据?", false); defaultCheckFullBox.setFocusPainted(false); configureMenu.add(configureMenuItem); configureMenu.add(configureFullItem); menuBar.add(configureMenu); // 创建 “实验功能” 菜单项 JMenu labMenu = new JMenu("实验功能"); JMenuItem openFileMenuItem = new JMenuItem("打开文件"); JMenuItem iconHashLabMenuItem = new JMenuItem("iconHash 计算"); JMenu pluginMenu = new JMenu("插件模式"); JMenu fofaHackMenu = new JMenu("Fofa-Hack"); JMenuItem fofaHackMenuItemRun = new JMenuItem("运行"); JMenuItem fofaHackMenuItemSetting = new JMenuItem("设置"); JMenuItem fofaHackMenuItemAbout = new JMenuItem("关于");
CommonTemplate.addMenuItemsFromFile(pluginMenu, tabbedPane0);
1
2023-12-07 13:46:27+00:00
24k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/ui/fragments/ColorsFragment.java
[ { "identifier": "MANUAL_OVERRIDE_COLORS", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MANUAL_OVERRIDE_COLORS = \"manualOverrideColors\";" }, { "identifier": "MONET_ACCENT_SATURATION", "path": "app/src/main/java/com/drdisagr...
import static com.drdisagree.colorblendr.common.Const.MANUAL_OVERRIDE_COLORS; import static com.drdisagree.colorblendr.common.Const.MONET_ACCENT_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_ACCURATE_SHADES; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_LIGHTNESS; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_LAST_UPDATED; import static com.drdisagree.colorblendr.common.Const.MONET_PITCH_BLACK_THEME; import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR; import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR_ENABLED; import static com.drdisagree.colorblendr.common.Const.MONET_STYLE; import static com.drdisagree.colorblendr.common.Const.WALLPAPER_COLOR_LIST; import android.content.BroadcastReceiver; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.drdisagree.colorblendr.R; import com.drdisagree.colorblendr.common.Const; import com.drdisagree.colorblendr.config.RPrefs; import com.drdisagree.colorblendr.databinding.FragmentColorsBinding; import com.drdisagree.colorblendr.ui.viewmodels.SharedViewModel; import com.drdisagree.colorblendr.ui.views.WallColorPreview; import com.drdisagree.colorblendr.utils.ColorSchemeUtil; import com.drdisagree.colorblendr.utils.ColorUtil; import com.drdisagree.colorblendr.utils.MiscUtil; import com.drdisagree.colorblendr.utils.OverlayManager; import com.drdisagree.colorblendr.utils.WallpaperUtil; import com.google.android.material.snackbar.Snackbar; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import me.jfenn.colorpickerdialog.dialogs.ColorPickerDialog; import me.jfenn.colorpickerdialog.views.picker.ImagePickerView;
18,908
package com.drdisagree.colorblendr.ui.fragments; @SuppressWarnings("deprecation") public class ColorsFragment extends Fragment { private static final String TAG = ColorsFragment.class.getSimpleName(); private FragmentColorsBinding binding; private int[] monetSeedColor; private LinearLayout[] colorTableRows; private SharedViewModel sharedViewModel; private final String[][] colorNames = ColorUtil.getColorNames(); private static final int[] colorCodes = { 0, 10, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; private final BroadcastReceiver wallpaperChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, android.content.Intent intent) { if (binding.colorsToggleGroup.getCheckedButtonId() == R.id.wallpaper_colors_button) { addWallpaperColorItems(); } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentColorsBinding.inflate(inflater, container, false); MiscUtil.setToolbarTitle(requireContext(), R.string.app_name, false, binding.header.toolbar); monetSeedColor = new int[]{RPrefs.getInt( MONET_SEED_COLOR, WallpaperUtil.getWallpaperColor(requireContext()) )}; colorTableRows = new LinearLayout[]{ binding.colorPreview.systemAccent1, binding.colorPreview.systemAccent2, binding.colorPreview.systemAccent3, binding.colorPreview.systemNeutral1, binding.colorPreview.systemNeutral2 }; return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); sharedViewModel.getBooleanStates().observe(getViewLifecycleOwner(), this::updateBooleanStates); sharedViewModel.getVisibilityStates().observe(getViewLifecycleOwner(), this::updateViewVisibility); // Color codes binding.colorsToggleGroup.check(
package com.drdisagree.colorblendr.ui.fragments; @SuppressWarnings("deprecation") public class ColorsFragment extends Fragment { private static final String TAG = ColorsFragment.class.getSimpleName(); private FragmentColorsBinding binding; private int[] monetSeedColor; private LinearLayout[] colorTableRows; private SharedViewModel sharedViewModel; private final String[][] colorNames = ColorUtil.getColorNames(); private static final int[] colorCodes = { 0, 10, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; private final BroadcastReceiver wallpaperChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, android.content.Intent intent) { if (binding.colorsToggleGroup.getCheckedButtonId() == R.id.wallpaper_colors_button) { addWallpaperColorItems(); } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentColorsBinding.inflate(inflater, container, false); MiscUtil.setToolbarTitle(requireContext(), R.string.app_name, false, binding.header.toolbar); monetSeedColor = new int[]{RPrefs.getInt( MONET_SEED_COLOR, WallpaperUtil.getWallpaperColor(requireContext()) )}; colorTableRows = new LinearLayout[]{ binding.colorPreview.systemAccent1, binding.colorPreview.systemAccent2, binding.colorPreview.systemAccent3, binding.colorPreview.systemNeutral1, binding.colorPreview.systemNeutral2 }; return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); sharedViewModel.getBooleanStates().observe(getViewLifecycleOwner(), this::updateBooleanStates); sharedViewModel.getVisibilityStates().observe(getViewLifecycleOwner(), this::updateViewVisibility); // Color codes binding.colorsToggleGroup.check(
RPrefs.getBoolean(MONET_SEED_COLOR_ENABLED, false) ?
8
2023-12-06 13:20:16+00:00
24k
lxs2601055687/contextAdminRuoYi
ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java
[ { "identifier": "Constants", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/Constants.java", "snippet": "public interface Constants {\n\n /**\n * UTF-8 字符集\n */\n String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n String GBK = \"GBK\";\n\n /**\n * www主域...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.io.IoUtil; import cn.hutool.core.lang.Dict; import cn.hutool.core.util.ObjectUtil; import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.core.domain.PageQuery; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.helper.LoginHelper; import com.ruoyi.common.utils.JsonUtils; import com.ruoyi.common.utils.StreamUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.file.FileUtils; import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; import com.ruoyi.generator.mapper.GenTableColumnMapper; import com.ruoyi.generator.mapper.GenTableMapper; import com.ruoyi.generator.util.GenUtils; import com.ruoyi.generator.util.VelocityInitializer; import com.ruoyi.generator.util.VelocityUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
20,618
package com.ruoyi.generator.service; /** * 业务 服务层实现 * * @author Lion Li */ @DS("#header.datasource") @Slf4j @RequiredArgsConstructor @Service public class GenTableServiceImpl implements IGenTableService { private final GenTableMapper baseMapper; private final GenTableColumnMapper genTableColumnMapper; private final IdentifierGenerator identifierGenerator; /** * 查询业务字段列表 * * @param tableId 业务字段编号 * @return 业务字段集合 */ @Override public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) { return genTableColumnMapper.selectList(new LambdaQueryWrapper<GenTableColumn>() .eq(GenTableColumn::getTableId, tableId) .orderByAsc(GenTableColumn::getSort)); } /** * 查询业务信息 * * @param id 业务ID * @return 业务信息 */ @Override public GenTable selectGenTableById(Long id) { GenTable genTable = baseMapper.selectGenTableById(id); setTableFromOptions(genTable); return genTable; } @Override public TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable, PageQuery pageQuery) { Page<GenTable> page = baseMapper.selectPage(pageQuery.build(), this.buildGenTableQueryWrapper(genTable)); return TableDataInfo.build(page); } private QueryWrapper<GenTable> buildGenTableQueryWrapper(GenTable genTable) { Map<String, Object> params = genTable.getParams(); QueryWrapper<GenTable> wrapper = Wrappers.query(); wrapper.like(StringUtils.isNotBlank(genTable.getTableName()), "lower(table_name)", StringUtils.lowerCase(genTable.getTableName())) .like(StringUtils.isNotBlank(genTable.getTableComment()), "lower(table_comment)", StringUtils.lowerCase(genTable.getTableComment())) .between(params.get("beginTime") != null && params.get("endTime") != null, "create_time", params.get("beginTime"), params.get("endTime")); return wrapper; } @Override public TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable, PageQuery pageQuery) { Page<GenTable> page = baseMapper.selectPageDbTableList(pageQuery.build(), genTable); return TableDataInfo.build(page); } /** * 查询据库列表 * * @param tableNames 表名称组 * @return 数据库表集合 */ @Override public List<GenTable> selectDbTableListByNames(String[] tableNames) { return baseMapper.selectDbTableListByNames(tableNames); } /** * 查询所有表信息 * * @return 表信息集合 */ @Override public List<GenTable> selectGenTableAll() { return baseMapper.selectGenTableAll(); } /** * 修改业务 * * @param genTable 业务信息 * @return 结果 */ @Transactional(rollbackFor = Exception.class) @Override public void updateGenTable(GenTable genTable) { String options = JsonUtils.toJsonString(genTable.getParams()); genTable.setOptions(options); int row = baseMapper.updateById(genTable); if (row > 0) { for (GenTableColumn cenTableColumn : genTable.getColumns()) { genTableColumnMapper.updateById(cenTableColumn); } } } /** * 删除业务对象 * * @param tableIds 需要删除的数据ID * @return 结果 */ @Transactional(rollbackFor = Exception.class) @Override public void deleteGenTableByIds(Long[] tableIds) { List<Long> ids = Arrays.asList(tableIds); baseMapper.deleteBatchIds(ids); genTableColumnMapper.delete(new LambdaQueryWrapper<GenTableColumn>().in(GenTableColumn::getTableId, ids)); } /** * 导入表结构 * * @param tableList 导入表列表 */ @Transactional(rollbackFor = Exception.class) @Override public void importGenTable(List<GenTable> tableList) { String operName = LoginHelper.getUsername(); try { for (GenTable table : tableList) { String tableName = table.getTableName();
package com.ruoyi.generator.service; /** * 业务 服务层实现 * * @author Lion Li */ @DS("#header.datasource") @Slf4j @RequiredArgsConstructor @Service public class GenTableServiceImpl implements IGenTableService { private final GenTableMapper baseMapper; private final GenTableColumnMapper genTableColumnMapper; private final IdentifierGenerator identifierGenerator; /** * 查询业务字段列表 * * @param tableId 业务字段编号 * @return 业务字段集合 */ @Override public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) { return genTableColumnMapper.selectList(new LambdaQueryWrapper<GenTableColumn>() .eq(GenTableColumn::getTableId, tableId) .orderByAsc(GenTableColumn::getSort)); } /** * 查询业务信息 * * @param id 业务ID * @return 业务信息 */ @Override public GenTable selectGenTableById(Long id) { GenTable genTable = baseMapper.selectGenTableById(id); setTableFromOptions(genTable); return genTable; } @Override public TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable, PageQuery pageQuery) { Page<GenTable> page = baseMapper.selectPage(pageQuery.build(), this.buildGenTableQueryWrapper(genTable)); return TableDataInfo.build(page); } private QueryWrapper<GenTable> buildGenTableQueryWrapper(GenTable genTable) { Map<String, Object> params = genTable.getParams(); QueryWrapper<GenTable> wrapper = Wrappers.query(); wrapper.like(StringUtils.isNotBlank(genTable.getTableName()), "lower(table_name)", StringUtils.lowerCase(genTable.getTableName())) .like(StringUtils.isNotBlank(genTable.getTableComment()), "lower(table_comment)", StringUtils.lowerCase(genTable.getTableComment())) .between(params.get("beginTime") != null && params.get("endTime") != null, "create_time", params.get("beginTime"), params.get("endTime")); return wrapper; } @Override public TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable, PageQuery pageQuery) { Page<GenTable> page = baseMapper.selectPageDbTableList(pageQuery.build(), genTable); return TableDataInfo.build(page); } /** * 查询据库列表 * * @param tableNames 表名称组 * @return 数据库表集合 */ @Override public List<GenTable> selectDbTableListByNames(String[] tableNames) { return baseMapper.selectDbTableListByNames(tableNames); } /** * 查询所有表信息 * * @return 表信息集合 */ @Override public List<GenTable> selectGenTableAll() { return baseMapper.selectGenTableAll(); } /** * 修改业务 * * @param genTable 业务信息 * @return 结果 */ @Transactional(rollbackFor = Exception.class) @Override public void updateGenTable(GenTable genTable) { String options = JsonUtils.toJsonString(genTable.getParams()); genTable.setOptions(options); int row = baseMapper.updateById(genTable); if (row > 0) { for (GenTableColumn cenTableColumn : genTable.getColumns()) { genTableColumnMapper.updateById(cenTableColumn); } } } /** * 删除业务对象 * * @param tableIds 需要删除的数据ID * @return 结果 */ @Transactional(rollbackFor = Exception.class) @Override public void deleteGenTableByIds(Long[] tableIds) { List<Long> ids = Arrays.asList(tableIds); baseMapper.deleteBatchIds(ids); genTableColumnMapper.delete(new LambdaQueryWrapper<GenTableColumn>().in(GenTableColumn::getTableId, ids)); } /** * 导入表结构 * * @param tableList 导入表列表 */ @Transactional(rollbackFor = Exception.class) @Override public void importGenTable(List<GenTable> tableList) { String operName = LoginHelper.getUsername(); try { for (GenTable table : tableList) { String tableName = table.getTableName();
GenUtils.initTable(table, operName);
14
2023-12-07 12:06:21+00:00
24k
DantSu/studio
web-ui/src/main/java/studio/webui/MainVerticle.java
[ { "identifier": "StudioConfig", "path": "metadata/src/main/java/studio/config/StudioConfig.java", "snippet": "public enum StudioConfig {\n\n // auto open browser (studio.open.browser)\n STUDIO_OPEN_BROWSER(\"true\"),\n // http listen host (studio.host)\n STUDIO_HOST(\"localhost\"),\n // h...
import java.awt.Desktop; import java.net.URI; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.netty.handler.codec.http.HttpHeaderNames; import io.vertx.core.AbstractVerticle; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpMethod; import io.vertx.ext.bridge.BridgeEventType; import io.vertx.ext.bridge.PermittedOptions; import io.vertx.ext.web.Router; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.handler.CorsHandler; import io.vertx.ext.web.handler.ErrorHandler; import io.vertx.ext.web.handler.StaticHandler; import io.vertx.ext.web.handler.sockjs.SockJSBridgeOptions; import io.vertx.ext.web.handler.sockjs.SockJSHandler; import studio.config.StudioConfig; import studio.metadata.DatabaseMetadataService; import studio.webui.api.DeviceController; import studio.webui.api.EvergreenController; import studio.webui.api.LibraryController; import studio.webui.service.EvergreenService; import studio.webui.service.IStoryTellerService; import studio.webui.service.LibraryService; import studio.webui.service.StoryTellerService; import studio.webui.service.mock.MockStoryTellerService;
15,076
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.webui; public class MainVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(MainVerticle.class); public static final String MIME_JSON = "application/json";
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.webui; public class MainVerticle extends AbstractVerticle { private static final Logger LOGGER = LogManager.getLogger(MainVerticle.class); public static final String MIME_JSON = "application/json";
private LibraryService libraryService;
7
2023-12-14 15:08:35+00:00
24k
conductor-oss/conductor-community
persistence/postgres-persistence/src/main/java/com/netflix/conductor/postgres/config/PostgresConfiguration.java
[ { "identifier": "PostgresExecutionDAO", "path": "persistence/postgres-persistence/src/main/java/com/netflix/conductor/postgres/dao/PostgresExecutionDAO.java", "snippet": "public class PostgresExecutionDAO extends PostgresBaseDAO\n implements ExecutionDAO, RateLimitingDAO, PollDataDAO, ConcurrentE...
import java.sql.SQLException; import java.util.Optional; import javax.annotation.PostConstruct; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.*; import org.springframework.retry.RetryContext; import org.springframework.retry.backoff.NoBackOffPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import com.netflix.conductor.postgres.dao.PostgresExecutionDAO; import com.netflix.conductor.postgres.dao.PostgresIndexDAO; import com.netflix.conductor.postgres.dao.PostgresMetadataDAO; import com.netflix.conductor.postgres.dao.PostgresQueueDAO; import com.fasterxml.jackson.databind.ObjectMapper;
19,943
/* * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.postgres.config; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(PostgresProperties.class) @ConditionalOnProperty(name = "conductor.db.type", havingValue = "postgres") // Import the DataSourceAutoConfiguration when postgres database is selected. // By default, the datasource configuration is excluded in the main module. @Import(DataSourceAutoConfiguration.class) public class PostgresConfiguration { DataSource dataSource; private final PostgresProperties properties; public PostgresConfiguration(DataSource dataSource, PostgresProperties properties) { this.dataSource = dataSource; this.properties = properties; } @Bean(initMethod = "migrate") @PostConstruct public Flyway flywayForPrimaryDb() { return Flyway.configure() .locations("classpath:db/migration_postgres") .schemas(properties.getSchema()) .dataSource(dataSource) .baselineOnMigrate(true) .load(); } @Bean @DependsOn({"flywayForPrimaryDb"}) public PostgresMetadataDAO postgresMetadataDAO( @Qualifier("postgresRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper, PostgresProperties properties) { return new PostgresMetadataDAO(retryTemplate, objectMapper, dataSource, properties); } @Bean @DependsOn({"flywayForPrimaryDb"}) public PostgresExecutionDAO postgresExecutionDAO( @Qualifier("postgresRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper) { return new PostgresExecutionDAO(retryTemplate, objectMapper, dataSource); } @Bean @DependsOn({"flywayForPrimaryDb"}) public PostgresQueueDAO postgresQueueDAO( @Qualifier("postgresRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper) { return new PostgresQueueDAO(retryTemplate, objectMapper, dataSource); } @Bean @DependsOn({"flywayForPrimaryDb"}) @ConditionalOnProperty(name = "conductor.indexing.type", havingValue = "postgres")
/* * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.postgres.config; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(PostgresProperties.class) @ConditionalOnProperty(name = "conductor.db.type", havingValue = "postgres") // Import the DataSourceAutoConfiguration when postgres database is selected. // By default, the datasource configuration is excluded in the main module. @Import(DataSourceAutoConfiguration.class) public class PostgresConfiguration { DataSource dataSource; private final PostgresProperties properties; public PostgresConfiguration(DataSource dataSource, PostgresProperties properties) { this.dataSource = dataSource; this.properties = properties; } @Bean(initMethod = "migrate") @PostConstruct public Flyway flywayForPrimaryDb() { return Flyway.configure() .locations("classpath:db/migration_postgres") .schemas(properties.getSchema()) .dataSource(dataSource) .baselineOnMigrate(true) .load(); } @Bean @DependsOn({"flywayForPrimaryDb"}) public PostgresMetadataDAO postgresMetadataDAO( @Qualifier("postgresRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper, PostgresProperties properties) { return new PostgresMetadataDAO(retryTemplate, objectMapper, dataSource, properties); } @Bean @DependsOn({"flywayForPrimaryDb"}) public PostgresExecutionDAO postgresExecutionDAO( @Qualifier("postgresRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper) { return new PostgresExecutionDAO(retryTemplate, objectMapper, dataSource); } @Bean @DependsOn({"flywayForPrimaryDb"}) public PostgresQueueDAO postgresQueueDAO( @Qualifier("postgresRetryTemplate") RetryTemplate retryTemplate, ObjectMapper objectMapper) { return new PostgresQueueDAO(retryTemplate, objectMapper, dataSource); } @Bean @DependsOn({"flywayForPrimaryDb"}) @ConditionalOnProperty(name = "conductor.indexing.type", havingValue = "postgres")
public PostgresIndexDAO postgresIndexDAO(
1
2023-12-08 06:06:20+00:00
24k
Ispirer/COBOL-to-Java-Conversion-Samples
IspirerFramework/com/ispirer/sw/file/FileDescription.java
[ { "identifier": "FileComparator", "path": "IspirerFramework/com/ispirer/sw/file/sort/FileComparator.java", "snippet": "public class FileComparator implements Comparator<Object> {\r\n\r\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(FileComparator.class);\r\n\r\n\t@Override\r\n\tpublic i...
import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import com.ispirer.sw.file.sort.FileComparator; import com.ispirer.sw.file.sort.SortKeys; import com.ispirer.sw.types.PictureType; import com.ispirer.sw.types.StructureModel; import com.opencsv.CSVReader; import org.apache.commons.lang3.StringUtils;
17,035
streamOutput.write(newStructure); } streamOutput.flush(); } /** * writes StructureModel objects to file * * @param model object to write * @throws IOException */ public void write(StructureModel model) throws IOException { if (this.type.compareTo(TypeOrganization.LINE_SEQUENTIAL) == 0) { if (this.advancing) { streamOutput.write(" ".getBytes()); streamOutput.write(model.toFile()); streamOutput.write(lineSeparator.getBytes()); } else { streamOutput.write(model.toFile()); streamOutput.write(lineSeparator.getBytes()); } } else if (this.advancing) { streamOutput.write(" ".getBytes()); streamOutput.write(model.toFile()); } else { streamOutput.write(model.toFile()); } streamOutput.flush(); } /** * closes file * * @throws IOException */ public void close() throws IOException { if (streamInput != null) { streamInput.close(); buffReader.close(); } if (streamOutput != null) { streamOutput.close(); } } public static byte[] transcodeField(byte[] source, Charset from, Charset to) { byte[] result = new String(source, from).getBytes(to); if (result.length != source.length) { throw new AssertionError(result.length + "!=" + source.length); } return result; } public boolean hasNext() throws IOException { return streamInput.available() > 0; } public String readIO(StructureModel strRec) throws IOException { strRec.setData(new String(Files.readAllBytes(Paths.get(this.name))).toCharArray()); return strRec.toString(); } public List<String> readTextFileByLines(String fileName) throws IOException { List<String> lines = Files.readAllLines(Paths.get(fileName)); return lines; } public void rewrite(String fileName, String content) throws IOException { List<String> lines = Files.readAllLines(file.toPath()); lines.set(recordCounter - 1, content); Files.write(file.toPath(), lines, StandardOpenOption.WRITE); } public void rewrite(String fileName, StructureModel model) throws IOException { List<String> lines = Files.readAllLines(file.toPath()); lines.set(recordCounter - 1, model.toString()); Files.write(file.toPath(), lines, StandardOpenOption.WRITE); } public String getName() { return this.name; } /** * Sort file * * @param sortKeys collection of keys to sort * @param record specify Type of records in file * @return */ @SuppressWarnings("unchecked") public List<T> sortFile(List<SortKeys> sortKeys, T record) {// }, int[] sizes){ this.record = record; List<String> listTempFile = new ArrayList<>(); try { listTempFile = Files.readAllLines(Paths.get(name), StandardCharsets.UTF_8); // reads all lines into List } catch (IOException e) { LOGGER.info(String.valueOf(e)); } // This loop fills list of records by strings that was read List<T> listSFile = new ArrayList<>(); for (String line : listTempFile) { try { this.record = (T) this.record.getClass().newInstance(); this.record.getClass().getMethod("setData", line.toCharArray().getClass()).invoke(this.record, line.toCharArray()); } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | InstantiationException e) { LOGGER.info(String.valueOf(e)); } listSFile.add(this.record); } listField = new ArrayList<>(); for (int i = 0; i < sortKeys.size(); i++) { listField.add(getField(this.record, sortKeys.get(i).getField())); } // collect fields for sorting
/* © 2021, Ispirer Systems OÜ. All rights reserved. NOTICE OF LICENSE This file\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only. IF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY! PLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS. Redistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes. If you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com */ package com.ispirer.sw.file; /** * FileDescription is a class that implements work with files * * @param <T> is a type of record that file work with at the moment. This type * is using for sorting files and will by specified automatically */ public class FileDescription<T> { private final Logger LOGGER = Logger.getLogger(FileDescription.class.getName()); protected int recordSize; protected int block; protected File file; protected FileInputStream streamInput; protected FileOutputStream streamOutput; protected BufferedReader buffReader; private String name = ""; private Boolean csv = false; private CSVReader csvReader; private T record; private HashMap<String, Object> keys = new HashMap<>(); private TypeOrganization type = TypeOrganization.LINE_SEQUENTIAL; private Boolean advancing = false; private int codeError = 0; private int recordCounter = 0; private boolean isEBCDIC = false; public static String lineSeparator = "\r\n"; // You can specify Line separator that is fit to you public static List<Field> listField = new ArrayList<>(); public boolean isInvalidKey; /** * enum with types of Organization of files * * There are 4 types of Organization in Cobol * * LINE_SEQUENTIAL Line Sequential files are a special type of sequential file. * They correspond to simple text files as produced by the standard editor * provided with your operating system. * * RECORD_SEQUENTIAL Sequential files are the simplest form of COBOL file. * Records are placed in the file in the order they are written, and can only be * read back in the same order. * * RELATIVE_FILES Every record in a relative file can be accessed directly * without having to read through any other records. Each record is identified * by a unique ordinal number both when it is written and when it is read back. * * INDEXED Indexed files are the most complex form of COBOL file which can be * handled directly by COBOL syntax. Records in an indexed file are identified * by a unique user-defined key when written. Each record can contain any number * of user-defined keys which can be used to read the record, either directly or * in key sequence. * * Now is implemented work with LINE_SEQUENTIAL and INDEXED files by default * organization of files is LINE_SEQUENTIAL */ public enum TypeOrganization { LINE_SEQUENTIAL, RECORD_SEQUENTIAL, RELATIVE_FILES, INDEXED } /** * FileDescription Constructor * * @param name path to the file * @param record length of record * @param block count of records in a block * @param isNotEBCDIC indicates file format. True value means ASCII and false * means EBCDIC */ public FileDescription(String name, int record, int block, boolean isNotEBCDIC) { this.name = name; file = new File(this.name); this.recordSize = record; this.block = block; this.isEBCDIC = !isNotEBCDIC; this.csv = false; } /** * FileDescription Constructor * * @param name path to the file * @param record length of record * @param block count of records in a block * @param isNotEBCDIC indicates file format. True value means ASCII and false * means EBCDIC * @param csv indicates file type. True value means CSV file type, false * means another type */ public FileDescription(String name, int record, int block, boolean isNotEBCDIC, boolean csv) { this.name = name; file = new File(this.name); this.recordSize = record; this.block = block; this.isEBCDIC = !isNotEBCDIC; this.csv = csv; } /** * FileDescription Constructor * * @param name path to the file * @param record length of record * @param block count of records in a block * @param isNotEBCDIC indicates file format. True value means ASCII and false * means EBCDIC * @param keys keys (for INDEXED files) */ public FileDescription(String name, int record, int block, boolean isNotEBCDIC, boolean csv, String... keys) { this.name = name; file = new File(this.name); this.recordSize = record; this.block = block; this.isEBCDIC = !isNotEBCDIC; this.csv = csv; for (String key : keys) { this.keys.put(key, new Object()); } } /** * This method opens file for writing. * * @param status status structure. use null value if you don't have this * structure * @param append if <code>true</code>, then bytes will be written to the end of * the file rather than the beginning * @throws IOException */ public void openOutput(StructureModel status, boolean append) throws IOException { try { recordCounter = 0; streamOutput = new FileOutputStream(file, append); // file is opened for writing if (status != null) { status.setData("00".toCharArray()); } } catch (FileNotFoundException exc) { LOGGER.log(Level.WARNING, exc.getMessage()); if (status != null) { status.setData("37".toCharArray()); } } } /** * This method opens file for reading * * @param status status structure. use null value if you don't have this * structure * @throws IOException */ public void openInput(StructureModel status) throws IOException { try { recordCounter = 0; if(csv){ csvReader = new CSVReader(new FileReader(file.getName())); } else{ streamInput = new FileInputStream(file); // file is opened for reading buffReader = // Here BufferedReader object creates. Need for reading file by lines isEBCDIC ? Files.newBufferedReader(file.toPath(), Charset.forName("IBM1047")) : // If File in // EBCIDIC need to // create // BufferedReader // object with // encoding new BufferedReader(new InputStreamReader(streamInput)); if (status != null) { status.setData("00".toCharArray()); } } } catch (FileNotFoundException exc) { LOGGER.log(Level.WARNING, exc.getMessage()); if (status != null) { status.setData("35".toCharArray()); } } } /** * reads one record from file * * @param strRec record object * @return record that was read * @throws IOException when file is finished or some error occurs during reading * when file is finished codeError = 0 if codeError != 0 * there is some error in reading this file */ public String read(StructureModel strRec) throws IOException { recordCounter++; if (!csv && streamInput == null) { // check if file is opened this.codeError = 1; throw new IOException(); } String line; int lineNum = 0; if(csv){ String[] values = null; values = csvReader.readNext(); strRec.setData(values); // set data to record object return strRec.toString(); } else{ if (isEBCDIC) {// need to read line for EBCIDIC file other way PictureType.isEBSDIC = true; char[] buff = new char[recordSize]; lineNum = buffReader.read(buff); // reading line line = new String(buff); } else { PictureType.isEBSDIC = false; line = buffReader.readLine(); // reading line } } if (lineNum == -1 || line == null) { // check if EOF this.codeError = 0; throw new IOException(); } strRec.setData(line.toCharArray()); // set data to record object return strRec.toString(); } public String readIndexed(StructureModel strRec, String key) throws IOException { byte[] data = new byte[strRec.getSize()]; if (streamInput == null) { throw new IOException(); } int sizeRead = streamInput.read(data); int sizeReadFinal = sizeRead; List<String> listFile = new ArrayList<>(); byte[] allData; allData = Files.readAllBytes(Paths.get(name)); if (Files.readAllLines(Paths.get(name), StandardCharsets.ISO_8859_1).get(0).length() > 130 && Files .readAllLines(Paths.get(name), StandardCharsets.ISO_8859_1).get(0).substring(0, 130).contains("@")) { String newLine = Files.readAllLines(Paths.get(name), StandardCharsets.ISO_8859_1).get(0).substring(131); allData = newLine.getBytes(); int i = 0; while (i < allData.length) { listFile.add(new String(allData).substring(i, sizeRead - 1)); i = sizeRead + 2; sizeRead = sizeRead + sizeReadFinal + 3; } } else { int i = 0; while (i < allData.length) { listFile.add(new String(allData).substring(i, sizeRead)); i = sizeRead; sizeRead += sizeReadFinal; } } if (key == null) { return listFile.get(listFile.size() - 1); } else { for (String record : listFile) { strRec.setData(record.toCharArray()); try { if (strRec.getClass().getField(key).get(strRec).toString().equals(keys.get(key))) { strRec.setDataFromFile(record.getBytes()); return strRec.toString(); } } catch (IllegalAccessException | NoSuchFieldException e) { LOGGER.info(String.valueOf(e)); } } } return null; } /** * writing data to file * * @param data to write * @throws IOException */ public void write(String data) throws IOException { if (this.type.compareTo(TypeOrganization.LINE_SEQUENTIAL) == 0) { if (this.advancing) { // if advancing need to add space in the begining of the record streamOutput.write((" " + data + lineSeparator).getBytes()); // in the end of record adding // lineSeparator } else { streamOutput.write((data + lineSeparator).getBytes()); } } else if (this.advancing) { streamOutput.write((" " + data).getBytes()); } else { streamOutput.write(data.getBytes()); } recordCounter++; streamOutput.flush(); } /** * immitate Cobol function write After Line * * @param data to write * @param line after that need to write. * @throws IOException */ public void writeAfterLine(Object data, int line) throws IOException { if (this.advancing) { // // left this code commented because we don't know why WRITE AFTER ADVANCING n // LINES doesn't add blank lines in COBOL. // The situation when it will add lines can be. // // if(recordCounter == 0){ // streamOutput.write(StringUtils.repeat(lineSeparator, line).getBytes()); // } else{ // streamOutput.write(StringUtils.repeat(lineSeparator, line-1).getBytes()); // } streamOutput.write(("0" + data.toString() + lineSeparator).getBytes()); // need to add zero on the begining // of the record if advancing } else { streamOutput.write((data.toString() + lineSeparator).getBytes()); streamOutput.write(StringUtils.repeat(lineSeparator, line).getBytes()); // writes line count of lines before // record } recordCounter++; streamOutput.flush(); } /** * immitate Cobol function write After Page * * @param data to write * @throws IOException */ public void writeAfterPage(Object data) throws IOException { if (data instanceof String) { if (this.advancing) { streamOutput.write(("1" + data.toString() + lineSeparator).getBytes());// need to add 1 on the begining // of the record if advancing } else { streamOutput.write((data.toString() + lineSeparator).getBytes()); } } else if (data instanceof StructureModel) { byte[] structure = ((StructureModel) data).toFile(); byte[] newStructure = new byte[structure.length + 2]; if (this.advancing) { newStructure[0] = "1".getBytes()[0]; } for (int i = 1; i <= structure.length; i++) { newStructure[i] = structure[i - 1]; } newStructure[newStructure.length - 1] = String.valueOf(lineSeparator).getBytes()[0]; streamOutput.write(newStructure); } streamOutput.flush(); } /** * writes StructureModel objects to file * * @param model object to write * @throws IOException */ public void write(StructureModel model) throws IOException { if (this.type.compareTo(TypeOrganization.LINE_SEQUENTIAL) == 0) { if (this.advancing) { streamOutput.write(" ".getBytes()); streamOutput.write(model.toFile()); streamOutput.write(lineSeparator.getBytes()); } else { streamOutput.write(model.toFile()); streamOutput.write(lineSeparator.getBytes()); } } else if (this.advancing) { streamOutput.write(" ".getBytes()); streamOutput.write(model.toFile()); } else { streamOutput.write(model.toFile()); } streamOutput.flush(); } /** * closes file * * @throws IOException */ public void close() throws IOException { if (streamInput != null) { streamInput.close(); buffReader.close(); } if (streamOutput != null) { streamOutput.close(); } } public static byte[] transcodeField(byte[] source, Charset from, Charset to) { byte[] result = new String(source, from).getBytes(to); if (result.length != source.length) { throw new AssertionError(result.length + "!=" + source.length); } return result; } public boolean hasNext() throws IOException { return streamInput.available() > 0; } public String readIO(StructureModel strRec) throws IOException { strRec.setData(new String(Files.readAllBytes(Paths.get(this.name))).toCharArray()); return strRec.toString(); } public List<String> readTextFileByLines(String fileName) throws IOException { List<String> lines = Files.readAllLines(Paths.get(fileName)); return lines; } public void rewrite(String fileName, String content) throws IOException { List<String> lines = Files.readAllLines(file.toPath()); lines.set(recordCounter - 1, content); Files.write(file.toPath(), lines, StandardOpenOption.WRITE); } public void rewrite(String fileName, StructureModel model) throws IOException { List<String> lines = Files.readAllLines(file.toPath()); lines.set(recordCounter - 1, model.toString()); Files.write(file.toPath(), lines, StandardOpenOption.WRITE); } public String getName() { return this.name; } /** * Sort file * * @param sortKeys collection of keys to sort * @param record specify Type of records in file * @return */ @SuppressWarnings("unchecked") public List<T> sortFile(List<SortKeys> sortKeys, T record) {// }, int[] sizes){ this.record = record; List<String> listTempFile = new ArrayList<>(); try { listTempFile = Files.readAllLines(Paths.get(name), StandardCharsets.UTF_8); // reads all lines into List } catch (IOException e) { LOGGER.info(String.valueOf(e)); } // This loop fills list of records by strings that was read List<T> listSFile = new ArrayList<>(); for (String line : listTempFile) { try { this.record = (T) this.record.getClass().newInstance(); this.record.getClass().getMethod("setData", line.toCharArray().getClass()).invoke(this.record, line.toCharArray()); } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | InstantiationException e) { LOGGER.info(String.valueOf(e)); } listSFile.add(this.record); } listField = new ArrayList<>(); for (int i = 0; i < sortKeys.size(); i++) { listField.add(getField(this.record, sortKeys.get(i).getField())); } // collect fields for sorting
Collections.sort(listSFile, new FileComparator()); // sorting
0
2023-12-13 14:56:32+00:00
24k
fiber-net-gateway/fiber-net-gateway
fiber-gateway-proxy/src/main/java/io/fiber/net/proxy/lib/HttpFunc.java
[ { "identifier": "FiberException", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/FiberException.java", "snippet": "public class FiberException extends Exception {\n private int code;\n private final String errorName;\n\n public FiberException(String message, int code, String er...
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.IntNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.fiber.net.common.FiberException; import io.fiber.net.common.HttpExchange; import io.fiber.net.common.HttpMethod; import io.fiber.net.common.async.internal.SerializeJsonObservable; import io.fiber.net.common.utils.ArrayUtils; import io.fiber.net.common.utils.Constant; import io.fiber.net.common.utils.JsonUtil; import io.fiber.net.common.utils.StringUtils; import io.fiber.net.http.ClientExchange; import io.fiber.net.http.HttpClient; import io.fiber.net.http.HttpHost; import io.fiber.net.http.util.UrlEncoded; import io.fiber.net.script.ExecutionContext; import io.fiber.net.script.Library; import io.fiber.net.script.ScriptExecException; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Iterator; import java.util.Map;
14,435
package io.fiber.net.proxy.lib; public class HttpFunc implements Library.DirectiveDef { private final HttpHost httpHost; private final HttpClient httpClient; private final Map<String, HttpDynamicFunc> fc = new HashMap<>(); public HttpFunc(HttpHost httpHost, HttpClient httpClient) { this.httpHost = httpHost; this.httpClient = httpClient; fc.put("request", new SendFunc()); fc.put("proxyPass", new ProxyFunc()); } @Override public Library.Function findFunc(String directive, String function) { return fc.get(function); } private class SendFunc implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) {
package io.fiber.net.proxy.lib; public class HttpFunc implements Library.DirectiveDef { private final HttpHost httpHost; private final HttpClient httpClient; private final Map<String, HttpDynamicFunc> fc = new HashMap<>(); public HttpFunc(HttpHost httpHost, HttpClient httpClient) { this.httpHost = httpHost; this.httpClient = httpClient; fc.put("request", new SendFunc()); fc.put("proxyPass", new ProxyFunc()); } @Override public Library.Function findFunc(String directive, String function) { return fc.get(function); } private class SendFunc implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) {
JsonNode param = ArrayUtils.isNotEmpty(args) ? args[0] : NullNode.getInstance();
4
2023-12-08 15:18:05+00:00
24k
lyswhut/react-native-local-media-metadata
android/src/main/java/com/localmediametadata/Metadata.java
[ { "identifier": "AudioFile", "path": "android/src/main/java/org/jaudiotagger/audio/AudioFile.java", "snippet": "public class AudioFile\n{\n //Logger\n public static Logger logger = Logger.getLogger(\"org.jaudiotagger.audio\");\n\n /**\n *\n * The physical file that this instance represe...
import android.os.Bundle; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.WritableMap; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.AudioHeader; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.TagField; import org.jaudiotagger.tag.flac.FlacTag; import org.jaudiotagger.tag.id3.valuepair.ImageFormats; import org.jaudiotagger.tag.images.Artwork; import org.jaudiotagger.tag.images.ArtworkFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream;
20,150
package com.localmediametadata; public class Metadata { private static WritableMap buildMetadata(MediaFile file, AudioHeader audioHeader, Tag tag) { WritableMap params = Arguments.createMap(); String name = tag.getFirst(FieldKey.TITLE); if ("".equals(name)) name = Utils.getName(file.getName()); params.putString("name", name); params.putString("singer", tag.getFirst(FieldKey.ARTIST).replaceAll("\\u0000", "、")); params.putString("albumName", tag.getFirst(FieldKey.ALBUM)); params.putDouble("interval", audioHeader.getTrackLength()); params.putString("bitrate", audioHeader.getBitRate()); params.putString("type", audioHeader.getEncodingType()); params.putString("ext", Utils.getFileExtension(file.getName())); params.putDouble("size", file.size()); return params; } static public WritableMap readMetadata(ReactApplicationContext context, String filePath) throws Exception { MediaFile mediaFile = new MediaFile(context, filePath); try { File file = mediaFile.getFile(false); AudioFile audioFile = AudioFileIO.read(file); return buildMetadata(mediaFile, audioFile.getAudioHeader(), audioFile.getTagOrCreateDefault()); } finally { mediaFile.closeFile(); } } static public void writeMetadata(File file, Bundle metadata, boolean isOverwrite) throws Exception { AudioFile audioFile = AudioFileIO.read(file); Tag tag; if (isOverwrite) { tag = audioFile.createDefaultTag(); audioFile.setTag(tag); } else tag = audioFile.getTagOrCreateAndSetDefault(); tag.setField(FieldKey.TITLE, metadata.getString("name", "")); tag.setField(FieldKey.ARTIST, metadata.getString("singer", "")); tag.setField(FieldKey.ALBUM, metadata.getString("albumName", "")); audioFile.commit(); } static public void writeMetadata(ReactApplicationContext context, String filePath, Bundle metadata, boolean isOverwrite) throws Exception { MediaFile mediaFile = new MediaFile(context, filePath); try { try { File file = mediaFile.getFile(true); writeMetadata(file, metadata, isOverwrite); } catch (Exception e) { mediaFile.closeFile(); writeMetadata(mediaFile.getTempFile(), metadata, isOverwrite); } } finally { mediaFile.closeFile(); } } public static String readPic(ReactApplicationContext context, String filePath, String picDir) throws Exception { MediaFile mediaFile = new MediaFile(context, filePath); try { File file = mediaFile.getFile(false); AudioFile audioFile = AudioFileIO.read(file); Artwork artwork = audioFile.getTagOrCreateDefault().getFirstArtwork(); if (artwork == null) return ""; if (artwork.isLinked()) return artwork.getImageUrl(); File dir = new File(picDir); if (!dir.exists() && !dir.mkdirs()) throw new Exception("Directory does not exist"); File picFile = new File(picDir, Utils.getName(file.getName()) + "." + ImageFormats.getFormatForMimeType(artwork.getMimeType()).toLowerCase()); try (FileOutputStream fos = new FileOutputStream(picFile)) { fos.write(artwork.getBinaryData()); } return picFile.getPath(); } finally { mediaFile.closeFile(); } } public static void writeFlacPic(AudioFile audioFile, Artwork artwork) throws Exception { FlacTag tag = (FlacTag) audioFile.getTagOrCreateAndSetDefault(); TagField tagField = tag.createArtworkField(artwork.getBinaryData(), artwork.getPictureType(), artwork.getMimeType(), artwork.getDescription(), artwork.getWidth(), artwork.getHeight(), 0, "image/jpeg".equals(artwork.getMimeType()) ? 24 : 32 ); tag.setField(tagField); try { audioFile.commit(); } catch (Exception e) { if (e.getMessage().contains("permissions")) { tag.deleteArtworkField(); audioFile.commit(); tag.setField(tagField); audioFile.commit(); } else throw e; } } private static void writePic(File file, String picPath) throws Exception { AudioFile audioFile = AudioFileIO.read(file); if ("".equals(picPath)) { audioFile.getTagOrCreateAndSetDefault().deleteArtworkField(); audioFile.commit(); return; }
package com.localmediametadata; public class Metadata { private static WritableMap buildMetadata(MediaFile file, AudioHeader audioHeader, Tag tag) { WritableMap params = Arguments.createMap(); String name = tag.getFirst(FieldKey.TITLE); if ("".equals(name)) name = Utils.getName(file.getName()); params.putString("name", name); params.putString("singer", tag.getFirst(FieldKey.ARTIST).replaceAll("\\u0000", "、")); params.putString("albumName", tag.getFirst(FieldKey.ALBUM)); params.putDouble("interval", audioHeader.getTrackLength()); params.putString("bitrate", audioHeader.getBitRate()); params.putString("type", audioHeader.getEncodingType()); params.putString("ext", Utils.getFileExtension(file.getName())); params.putDouble("size", file.size()); return params; } static public WritableMap readMetadata(ReactApplicationContext context, String filePath) throws Exception { MediaFile mediaFile = new MediaFile(context, filePath); try { File file = mediaFile.getFile(false); AudioFile audioFile = AudioFileIO.read(file); return buildMetadata(mediaFile, audioFile.getAudioHeader(), audioFile.getTagOrCreateDefault()); } finally { mediaFile.closeFile(); } } static public void writeMetadata(File file, Bundle metadata, boolean isOverwrite) throws Exception { AudioFile audioFile = AudioFileIO.read(file); Tag tag; if (isOverwrite) { tag = audioFile.createDefaultTag(); audioFile.setTag(tag); } else tag = audioFile.getTagOrCreateAndSetDefault(); tag.setField(FieldKey.TITLE, metadata.getString("name", "")); tag.setField(FieldKey.ARTIST, metadata.getString("singer", "")); tag.setField(FieldKey.ALBUM, metadata.getString("albumName", "")); audioFile.commit(); } static public void writeMetadata(ReactApplicationContext context, String filePath, Bundle metadata, boolean isOverwrite) throws Exception { MediaFile mediaFile = new MediaFile(context, filePath); try { try { File file = mediaFile.getFile(true); writeMetadata(file, metadata, isOverwrite); } catch (Exception e) { mediaFile.closeFile(); writeMetadata(mediaFile.getTempFile(), metadata, isOverwrite); } } finally { mediaFile.closeFile(); } } public static String readPic(ReactApplicationContext context, String filePath, String picDir) throws Exception { MediaFile mediaFile = new MediaFile(context, filePath); try { File file = mediaFile.getFile(false); AudioFile audioFile = AudioFileIO.read(file); Artwork artwork = audioFile.getTagOrCreateDefault().getFirstArtwork(); if (artwork == null) return ""; if (artwork.isLinked()) return artwork.getImageUrl(); File dir = new File(picDir); if (!dir.exists() && !dir.mkdirs()) throw new Exception("Directory does not exist"); File picFile = new File(picDir, Utils.getName(file.getName()) + "." + ImageFormats.getFormatForMimeType(artwork.getMimeType()).toLowerCase()); try (FileOutputStream fos = new FileOutputStream(picFile)) { fos.write(artwork.getBinaryData()); } return picFile.getPath(); } finally { mediaFile.closeFile(); } } public static void writeFlacPic(AudioFile audioFile, Artwork artwork) throws Exception { FlacTag tag = (FlacTag) audioFile.getTagOrCreateAndSetDefault(); TagField tagField = tag.createArtworkField(artwork.getBinaryData(), artwork.getPictureType(), artwork.getMimeType(), artwork.getDescription(), artwork.getWidth(), artwork.getHeight(), 0, "image/jpeg".equals(artwork.getMimeType()) ? 24 : 32 ); tag.setField(tagField); try { audioFile.commit(); } catch (Exception e) { if (e.getMessage().contains("permissions")) { tag.deleteArtworkField(); audioFile.commit(); tag.setField(tagField); audioFile.commit(); } else throw e; } } private static void writePic(File file, String picPath) throws Exception { AudioFile audioFile = AudioFileIO.read(file); if ("".equals(picPath)) { audioFile.getTagOrCreateAndSetDefault().deleteArtworkField(); audioFile.commit(); return; }
Artwork artwork = ArtworkFactory.createArtworkFromFile(new File(picPath));
9
2023-12-11 05:58:19+00:00
24k
xhtcode/xht-cloud-parent
xht-cloud-generate-service/src/main/java/com/xht/cloud/generate/module/table/service/impl/GenTableServiceImpl.java
[ { "identifier": "PageResponse", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java", "snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.xht.cloud.framework.core.api.response.PageResponse; import com.xht.cloud.framework.core.constant.CommonConstants; import com.xht.cloud.framework.core.support.StringUtils; import com.xht.cloud.framework.exception.business.BizException; import com.xht.cloud.framework.mybatis.tool.PageTool; import com.xht.cloud.generate.constant.GenerateConstant; import com.xht.cloud.generate.constant.enums.GenerateType; import com.xht.cloud.generate.constant.enums.HtmlTypeEnum; import com.xht.cloud.generate.constant.enums.QueryTypeEnum; import com.xht.cloud.generate.module.column.convert.GenTableColumnConvert; import com.xht.cloud.generate.module.column.dao.dataobject.GenTableColumnDO; import com.xht.cloud.generate.module.column.dao.mapper.GenTableColumnMapper; import com.xht.cloud.generate.module.config.dao.dataobject.GenCodeConfigDO; import com.xht.cloud.generate.module.config.dao.mapper.GenCodeConfigMapper; import com.xht.cloud.generate.module.database.dao.dataobject.GenDatabaseDO; import com.xht.cloud.generate.module.database.dao.mapper.GenDatabaseMapper; import com.xht.cloud.generate.module.table.controller.request.GenTableAddRequest; import com.xht.cloud.generate.module.table.controller.request.GenTableQueryRequest; import com.xht.cloud.generate.module.table.controller.request.GenTableUpdateRequest; import com.xht.cloud.generate.module.table.controller.request.ImportRequest; import com.xht.cloud.generate.module.table.controller.response.GenTableResponse; import com.xht.cloud.generate.module.table.controller.response.GenerateVo; import com.xht.cloud.generate.module.table.convert.GenTableConvert; import com.xht.cloud.generate.module.table.dao.dataobject.GenTableDO; import com.xht.cloud.generate.module.table.dao.mapper.GenTableMapper; import com.xht.cloud.generate.module.table.dao.wrapper.GenTableWrapper; import com.xht.cloud.generate.module.table.service.IGenTableService; import com.xht.cloud.generate.module.type.dao.dataobject.GenColumnTypeDO; import com.xht.cloud.generate.module.type.dao.mapper.GenColumnTypeMapper; import com.xht.cloud.generate.support.DataBaseQueryFactory; import com.xht.cloud.generate.support.IDataBaseQuery; import com.xht.cloud.generate.utils.GenerateTool; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.*;
15,615
package com.xht.cloud.generate.module.table.service.impl; /** * 描述 :代码生成器-数据库信息 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class GenTableServiceImpl implements IGenTableService, InitializingBean { private final GenCodeConfigMapper genCodeConfigMapper; private final GenTableMapper genTableMapper; private final GenDatabaseMapper genDatabaseMapper; private final GenTableConvert genTableConvert; private final DataBaseQueryFactory dataBaseQueryFactory; private final GenTableColumnMapper genTableColumnMapper; private final GenTableColumnConvert genTableColumnConvert; private final GenColumnTypeMapper genColumnTypeMapper; private static final Map<String, String> JAVA_TYPE = new HashMap<>(); private static final Map<String, String> TS_TYPE = new HashMap<>(); /** * 创建 * * @param addRequest {@link GenTableAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(GenTableAddRequest addRequest) { GenTableDO entity = genTableConvert.toDO(addRequest); genTableMapper.insert(entity); return entity.getId(); } /** * 根据id修改 * * @param updateRequest GenTableUpdateRequest */ @Override @Transactional(rollbackFor = Exception.class) public void update(GenTableUpdateRequest updateRequest) { if (Objects.isNull(genTableMapper.findById(updateRequest.getId()).orElse(null))) { throw new BizException("修改的对象不存在!"); } genTableMapper.updateById(genTableConvert.toDO(updateRequest)); } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) { genTableMapper.deleteBatchIds(ids); genTableColumnMapper.delete(new LambdaQueryWrapper<GenTableColumnDO>().in(GenTableColumnDO::getTableId, ids)); } /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link GenerateVo} */ @Override public GenerateVo findById(String id) { GenerateVo generateVo = new GenerateVo(); GenTableResponse tableResponse = genTableConvert.toResponse(genTableMapper.findById(id).orElse(null)); generateVo.setTable(tableResponse); if (Objects.nonNull(tableResponse)) { List<GenTableColumnDO> genTableColumnDOS = genTableColumnMapper.selectList(GenTableColumnDO::getTableId, tableResponse.getId()); generateVo.setColumns(genTableColumnConvert.toResponse(genTableColumnDOS)); } return generateVo; } /** * 分页查询 * * @param queryRequest {@link GenTableQueryRequest} * @return {@link PageResponse<GenTableResponse>} 分页详情 */ @Override
package com.xht.cloud.generate.module.table.service.impl; /** * 描述 :代码生成器-数据库信息 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class GenTableServiceImpl implements IGenTableService, InitializingBean { private final GenCodeConfigMapper genCodeConfigMapper; private final GenTableMapper genTableMapper; private final GenDatabaseMapper genDatabaseMapper; private final GenTableConvert genTableConvert; private final DataBaseQueryFactory dataBaseQueryFactory; private final GenTableColumnMapper genTableColumnMapper; private final GenTableColumnConvert genTableColumnConvert; private final GenColumnTypeMapper genColumnTypeMapper; private static final Map<String, String> JAVA_TYPE = new HashMap<>(); private static final Map<String, String> TS_TYPE = new HashMap<>(); /** * 创建 * * @param addRequest {@link GenTableAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(GenTableAddRequest addRequest) { GenTableDO entity = genTableConvert.toDO(addRequest); genTableMapper.insert(entity); return entity.getId(); } /** * 根据id修改 * * @param updateRequest GenTableUpdateRequest */ @Override @Transactional(rollbackFor = Exception.class) public void update(GenTableUpdateRequest updateRequest) { if (Objects.isNull(genTableMapper.findById(updateRequest.getId()).orElse(null))) { throw new BizException("修改的对象不存在!"); } genTableMapper.updateById(genTableConvert.toDO(updateRequest)); } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) { genTableMapper.deleteBatchIds(ids); genTableColumnMapper.delete(new LambdaQueryWrapper<GenTableColumnDO>().in(GenTableColumnDO::getTableId, ids)); } /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link GenerateVo} */ @Override public GenerateVo findById(String id) { GenerateVo generateVo = new GenerateVo(); GenTableResponse tableResponse = genTableConvert.toResponse(genTableMapper.findById(id).orElse(null)); generateVo.setTable(tableResponse); if (Objects.nonNull(tableResponse)) { List<GenTableColumnDO> genTableColumnDOS = genTableColumnMapper.selectList(GenTableColumnDO::getTableId, tableResponse.getId()); generateVo.setColumns(genTableColumnConvert.toResponse(genTableColumnDOS)); } return generateVo; } /** * 分页查询 * * @param queryRequest {@link GenTableQueryRequest} * @return {@link PageResponse<GenTableResponse>} 分页详情 */ @Override
public PageResponse<GenTableResponse> findPage(GenTableQueryRequest queryRequest) {
17
2023-12-12 08:16:30+00:00
24k
serendipitk/LunarCore
src/main/java/emu/lunarcore/server/packet/recv/HandlerGetAvatarDataCsReq.java
[ { "identifier": "GameSession", "path": "src/main/java/emu/lunarcore/server/game/GameSession.java", "snippet": "@Getter\npublic class GameSession {\n private final GameServer server;\n private final Int2LongMap packetCooldown;\n private InetSocketAddress address;\n\n private Account account;\...
import emu.lunarcore.server.game.GameSession; import emu.lunarcore.server.packet.CmdId; import emu.lunarcore.server.packet.Opcodes; import emu.lunarcore.server.packet.PacketHandler; import emu.lunarcore.server.packet.send.PacketGetAvatarDataScRsp;
20,064
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetAvatarDataCsReq) public class HandlerGetAvatarDataCsReq extends PacketHandler { @Override public void handle(GameSession session, byte[] data) throws Exception {
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetAvatarDataCsReq) public class HandlerGetAvatarDataCsReq extends PacketHandler { @Override public void handle(GameSession session, byte[] data) throws Exception {
session.send(new PacketGetAvatarDataScRsp(session.getPlayer()));
3
2023-12-08 14:13:04+00:00
24k
quentin452/Garden-Stuff-Continuation
src/main/resources/com/jaquadro/minecraft/gardencontainers/client/renderer/DecorativePotRenderer.java
[ { "identifier": "BlockDecorativePot", "path": "src/main/java/com/jaquadro/minecraft/gardencontainers/block/BlockDecorativePot.java", "snippet": "public class BlockDecorativePot extends BlockGardenContainer {\n\n public BlockDecorativePot(String blockName) {\n super(blockName, Material.rock);\n...
import com.jaquadro.minecraft.gardencontainers.block.BlockDecorativePot; import com.jaquadro.minecraft.gardencontainers.block.tile.TileEntityDecorativePot; import com.jaquadro.minecraft.gardencontainers.core.ClientProxy; import com.jaquadro.minecraft.gardencore.client.renderer.support.ModularBoxRenderer; import com.jaquadro.minecraft.gardencore.util.RenderHelper; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.ColorizerGrass; import net.minecraft.world.IBlockAccess; import org.lwjgl.opengl.GL11;
21,430
package com.jaquadro.minecraft.gardencontainers.client.renderer; public class DecorativePotRenderer implements ISimpleBlockRenderingHandler { private float[] baseColor = new float[3]; private float[] activeSubstrateColor = new float[3];
package com.jaquadro.minecraft.gardencontainers.client.renderer; public class DecorativePotRenderer implements ISimpleBlockRenderingHandler { private float[] baseColor = new float[3]; private float[] activeSubstrateColor = new float[3];
private ModularBoxRenderer boxRenderer = new ModularBoxRenderer();
3
2023-12-12 08:13:16+00:00
24k
muchfish/ruoyi-vue-pro-sample
yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java
[ { "identifier": "CommonStatusEnum", "path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/enums/CommonStatusEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum CommonStatusEnum implements IntArrayValuable {\n\n ENABLE(0, \"开启\"),\n DISABLE(1, \"关闭\");\...
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.tenant.config.TenantProperties; import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantPageReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantUpdateReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO; import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO; import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantPackageDO; import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantMapper; import cn.iocoder.yudao.module.system.enums.permission.RoleCodeEnum; import cn.iocoder.yudao.module.system.enums.permission.RoleTypeEnum; import cn.iocoder.yudao.module.system.service.permission.MenuService; import cn.iocoder.yudao.module.system.service.permission.PermissionService; import cn.iocoder.yudao.module.system.service.permission.RoleService; import cn.iocoder.yudao.module.system.service.tenant.handler.TenantInfoHandler; import cn.iocoder.yudao.module.system.service.tenant.handler.TenantMenuHandler; import cn.iocoder.yudao.module.system.service.user.AdminUserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO.PACKAGE_ID_SYSTEM; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*;
16,582
package cn.iocoder.yudao.module.system.service.tenant; /** * {@link TenantServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(TenantServiceImpl.class) public class TenantServiceImplTest extends BaseDbUnitTest { @Resource private TenantServiceImpl tenantService; @Resource private TenantMapper tenantMapper; @MockBean private TenantProperties tenantProperties; @MockBean private TenantPackageService tenantPackageService; @MockBean private AdminUserService userService; @MockBean private RoleService roleService; @MockBean private MenuService menuService; @MockBean private PermissionService permissionService; @BeforeEach public void setUp() { // 清理租户上下文 TenantContextHolder.clear(); } @Test public void testGetTenantIdList() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L)); tenantMapper.insert(tenant); // 调用,并断言业务异常 List<Long> result = tenantService.getTenantIdList(); assertEquals(Collections.singletonList(1L), result); } @Test public void testValidTenant_notExists() { assertServiceException(() -> tenantService.validTenant(randomLongId()), TENANT_NOT_EXISTS); } @Test public void testValidTenant_disable() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.DISABLE.getStatus())); tenantMapper.insert(tenant); // 调用,并断言业务异常 assertServiceException(() -> tenantService.validTenant(1L), TENANT_DISABLE, tenant.getName()); } @Test public void testValidTenant_expired() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus()) .setExpireTime(buildTime(2020, 2, 2))); tenantMapper.insert(tenant); // 调用,并断言业务异常 assertServiceException(() -> tenantService.validTenant(1L), TENANT_EXPIRE, tenant.getName()); } @Test public void testValidTenant_success() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus()) .setExpireTime(LocalDateTime.now().plusDays(1))); tenantMapper.insert(tenant); // 调用,并断言业务异常 tenantService.validTenant(1L); } @Test public void testCreateTenant() { // mock 套餐 100L TenantPackageDO tenantPackage = randomPojo(TenantPackageDO.class, o -> o.setId(100L)); when(tenantPackageService.validTenantPackage(eq(100L))).thenReturn(tenantPackage); // mock 角色 200L when(roleService.createRole(argThat(role -> { assertEquals(RoleCodeEnum.TENANT_ADMIN.getName(), role.getName()); assertEquals(RoleCodeEnum.TENANT_ADMIN.getCode(), role.getCode()); assertEquals(0, role.getSort()); assertEquals("系统自动生成", role.getRemark()); return true;
package cn.iocoder.yudao.module.system.service.tenant; /** * {@link TenantServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(TenantServiceImpl.class) public class TenantServiceImplTest extends BaseDbUnitTest { @Resource private TenantServiceImpl tenantService; @Resource private TenantMapper tenantMapper; @MockBean private TenantProperties tenantProperties; @MockBean private TenantPackageService tenantPackageService; @MockBean private AdminUserService userService; @MockBean private RoleService roleService; @MockBean private MenuService menuService; @MockBean private PermissionService permissionService; @BeforeEach public void setUp() { // 清理租户上下文 TenantContextHolder.clear(); } @Test public void testGetTenantIdList() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L)); tenantMapper.insert(tenant); // 调用,并断言业务异常 List<Long> result = tenantService.getTenantIdList(); assertEquals(Collections.singletonList(1L), result); } @Test public void testValidTenant_notExists() { assertServiceException(() -> tenantService.validTenant(randomLongId()), TENANT_NOT_EXISTS); } @Test public void testValidTenant_disable() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.DISABLE.getStatus())); tenantMapper.insert(tenant); // 调用,并断言业务异常 assertServiceException(() -> tenantService.validTenant(1L), TENANT_DISABLE, tenant.getName()); } @Test public void testValidTenant_expired() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus()) .setExpireTime(buildTime(2020, 2, 2))); tenantMapper.insert(tenant); // 调用,并断言业务异常 assertServiceException(() -> tenantService.validTenant(1L), TENANT_EXPIRE, tenant.getName()); } @Test public void testValidTenant_success() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus()) .setExpireTime(LocalDateTime.now().plusDays(1))); tenantMapper.insert(tenant); // 调用,并断言业务异常 tenantService.validTenant(1L); } @Test public void testCreateTenant() { // mock 套餐 100L TenantPackageDO tenantPackage = randomPojo(TenantPackageDO.class, o -> o.setId(100L)); when(tenantPackageService.validTenantPackage(eq(100L))).thenReturn(tenantPackage); // mock 角色 200L when(roleService.createRole(argThat(role -> { assertEquals(RoleCodeEnum.TENANT_ADMIN.getName(), role.getName()); assertEquals(RoleCodeEnum.TENANT_ADMIN.getCode(), role.getCode()); assertEquals(0, role.getSort()); assertEquals("系统自动生成", role.getRemark()); return true;
}), eq(RoleTypeEnum.SYSTEM.getType()))).thenReturn(200L);
15
2023-12-08 02:48:42+00:00
24k
mklemmingen/senet-boom
core/src/com/senetboom/game/frontend/stages/GameStage.java
[ { "identifier": "SenetBoom", "path": "core/src/com/senetboom/game/SenetBoom.java", "snippet": "public class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTextur...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.senetboom.game.SenetBoom; import com.senetboom.game.backend.Board; import com.senetboom.game.backend.Coordinate; import com.senetboom.game.backend.Piece; import com.senetboom.game.backend.Tile; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.utils.DragListener; import static com.senetboom.game.SenetBoom.*; import static com.senetboom.game.backend.Board.getBoard; import static com.senetboom.game.backend.Board.setAllowedTile;
20,783
System.out.println("Started dragging the Pawn!\n"); // Get the team color of the current tile Tile[] gameBoard = getBoard(); Piece.Color teamColor = gameBoard[i].getPiece().getColour(); // If it's not the current team's turn, cancel the drag and return if (!(teamColor == getTurn())) { event.cancel(); System.out.println("It's not your turn!\n"); renderBoard(); return; } System.out.println("Current Stick Value: " + currentStickValue + "\n"); System.out.println("Current Tile: " + board[i].getPosition() + "\n"); System.out.println("Current Team" + teamColor + "\n"); if(board[i].isMoveValid(board[i].getPosition(), currentStickValue)){ System.out.println("Move for this piece valid. Setting allowed tile."); setAllowedTile(board[i].getPosition()+currentStickValue); } else{ System.out.println("Move for this piece invalid"); } pawnStack.toFront(); // bring to the front Coordinate cd = calculatePXbyTile(board[i].getPosition()); // If it's the current team's turn, continue with the drag // show the current teams arm stage if (teamColor == Piece.Color.BLACK) { // draw a black arm to the stack showArmFromBelowStage = true; float armFromBelowY = cd.getY()-(tileSize*7.25f)-10; armFromBelow.setPosition(cd.getX()-tileSize*0.5f, armFromBelowY); } else { // draw a white arm to the stack showArmFromAboveStage = true; armFromAbove.setPosition(cd.getX()-tileSize*0.5f, cd.getY()+tileSize*1.5f); } } @Override public void drag(InputEvent event, float x, float y, int pointer) { // Code here will run during the dragging // move by the difference between the current position and the last position pawnStack.moveBy(x - pawnStack.getWidth() / 2, y - pawnStack.getHeight() / 2); // set the arm position to the current position of the pawn if (getTurn() == Piece.Color.BLACK) { // draw a black arm to the stack armFromBelow.moveBy(x - pawnStack.getWidth() / 2, y - pawnStack.getHeight() / 2); } else { // draw a white arm to the stack armFromAbove.moveBy(x - pawnStack.getWidth() / 2, y - pawnStack.getHeight() / 2); } } @Override public void dragStop(InputEvent event, float x, float y, int pointer) { // Code here will run when the player lets go of the actor // Get the position of the tileWidget relative to the parent actor (the gameBoard) Vector2 localCoords = new Vector2(x, y); // Convert the position to stage (screen) coordinates Vector2 screenCoords = pawnStack.localToStageCoordinates(localCoords); System.out.println("\n Drag stopped at screen position: " + screenCoords.x + ", " + screenCoords.y + "\n"); int endTile = calculateTilebyPx((int) screenCoords.x, (int) screenCoords.y); System.out.print("End Tile: " + endTile + "\n"); // for loop through validMoveTiles, at each tile we check for equality of currentCoord // with the Coordinate // in the ArrayList by using currentCoord.checkEqual(validMoveTiles[i]) and if true, // we set the // validMove Variable to true, call on the update method of the Board class and break // the for loop // then clear the Board. if(endTile == possibleMove){ // Board.update with oldX, oldY, newX, newY board[tile.getPosition()].movePiece(endTile); legitMove = true; System.out.println("Move valid as in check of tile to possibleMove"); } else { System.out.println("Move invalid as in check of tile to possibleMove"); } // and the possibleMove is cleared possibleMove = -1; // for turning off the Overlay // turn off the arm stage showArmFromBelowStage = false; showArmFromAboveStage = false; // board is rendered new renderBoard(); } }); // end of listener creation } pawnRoot.add(pawnStack); } public static void createMapStacks(final Tile[] board, Table root, int i){ final Tile tile = board[i]; // ----------------- Tile Stack ----------------- // for the stack below being the tile of the board final Stack stack = new Stack(); stack.setSize(tileSize, tileSize); // add a png of a tile texture to the stack
package com.senetboom.game.frontend.stages; public class GameStage { public static Stage drawMap() { Stage stage = new Stage(); // create a root table for the tiles Table root = new Table(); root.setFillParent(true); // iterate through the board, at each tile final Tile[] board = getBoard(); // first row for(int i=0; i<10; i++) { createMapStacks(board, root, i); } root.row(); // second row for(int i=19; i>=10; i--) { createMapStacks(board, root, i); } root.row(); // third row for(int i=20; i<30; i++) { createMapStacks(board, root, i); } stage.addActor(root); return stage; } public static Stage drawBoard() { inGame = true; Stage stage = new Stage(); // create a root table for the pawns Table pawnRoot = new Table(); pawnRoot.setFillParent(true); // iterate through the board, at each tile final Tile[] board = getBoard(); // first row for(int i=0; i<10; i++) { createStacks(board, pawnRoot, i); } pawnRoot.row(); // second row for(int i=19; i>=10; i--) { createStacks(board, pawnRoot, i); } pawnRoot.row(); // third row for(int i=20; i<30; i++) { createStacks(board, pawnRoot, i); } stage.addActor(pawnRoot); // add a Table with a single EXIT and OPTION Button Table exitTable = new Table(); // HELP BUTTON THAT SWITCHES THE BOOLEAN displayHelp TextButton helpButton = new TextButton("HELP", skin); helpButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { displayHelp = !displayHelp; } }); exitTable.add(helpButton).padBottom(tileSize/4); // in the same row, add a hint button TextButton hintButton = new TextButton("HINT", skin); hintButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { displayHint = !displayHint; needRender = true; } }); exitTable.add(hintButton).padBottom(tileSize/4).padLeft(tileSize/8); exitTable.row(); // add a skipTurn button TextButton skipTurnButton = new TextButton("END TURN", skin); skipTurnButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { skipTurn = true; } }); exitTable.add(skipTurnButton).padBottom(tileSize/4); exitTable.row(); // add the Options button TextButton optionsButton = new TextButton("OPTIONS", skin); optionsButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { // TODO } }); exitTable.add(optionsButton).padBottom(tileSize/4); exitTable.row(); // add the exit button TextButton exitButton = new TextButton("EXIT", skin); exitButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { createMenu(); } }); exitTable.add(exitButton).padBottom(tileSize/4); exitTable.setPosition(Gdx.graphics.getWidth()-tileSize*3, tileSize*1.5f); stage.addActor(exitTable); return stage; } public static void createStacks(final Tile[] board, Table pawnRoot, final int i){ final Tile tile = board[i]; // ----------------- Pawn Stack ----------------- // for the stack above being the pawn on the tile final Stack pawnStack = new Stack(); pawnStack.setSize(80, 80); // EMPTY Texture Image empty = new Image(emptyTexture); empty.setSize(80, 80); pawnStack.addActor(empty); // if the tile has a piece, draw the piece if(tile.hasPiece()) { if(!(emptyVariable == tile.getPosition())) { // if tile not the empty currently bot move pawn position Image piece; if(tile.getPiece().getColour() == Piece.Color.BLACK) { // draw a black piece to the stack piece = new Image(blackpiece); } else { // draw a white piece to the stack piece = new Image(whitepiece); } piece.setSize(80, 80); pawnStack.addActor(piece); } } // check if tile has protection if(tile.hasPiece() && tile.getPiece().hasProtection()) { // draw a protection to the stack Image protection = new Image(rebirthProtection); protection.setSize(80, 80); pawnStack.addActor(protection); } if(tile.hasPiece() && tile.getPiece().getColour() == getTurn()){ // drag and drop listeners pawnStack.addListener(new DragListener() { @Override public void dragStart(InputEvent event, float x, float y, int pointer) { // Code runs when dragging starts: System.out.println("Started dragging the Pawn!\n"); // Get the team color of the current tile Tile[] gameBoard = getBoard(); Piece.Color teamColor = gameBoard[i].getPiece().getColour(); // If it's not the current team's turn, cancel the drag and return if (!(teamColor == getTurn())) { event.cancel(); System.out.println("It's not your turn!\n"); renderBoard(); return; } System.out.println("Current Stick Value: " + currentStickValue + "\n"); System.out.println("Current Tile: " + board[i].getPosition() + "\n"); System.out.println("Current Team" + teamColor + "\n"); if(board[i].isMoveValid(board[i].getPosition(), currentStickValue)){ System.out.println("Move for this piece valid. Setting allowed tile."); setAllowedTile(board[i].getPosition()+currentStickValue); } else{ System.out.println("Move for this piece invalid"); } pawnStack.toFront(); // bring to the front Coordinate cd = calculatePXbyTile(board[i].getPosition()); // If it's the current team's turn, continue with the drag // show the current teams arm stage if (teamColor == Piece.Color.BLACK) { // draw a black arm to the stack showArmFromBelowStage = true; float armFromBelowY = cd.getY()-(tileSize*7.25f)-10; armFromBelow.setPosition(cd.getX()-tileSize*0.5f, armFromBelowY); } else { // draw a white arm to the stack showArmFromAboveStage = true; armFromAbove.setPosition(cd.getX()-tileSize*0.5f, cd.getY()+tileSize*1.5f); } } @Override public void drag(InputEvent event, float x, float y, int pointer) { // Code here will run during the dragging // move by the difference between the current position and the last position pawnStack.moveBy(x - pawnStack.getWidth() / 2, y - pawnStack.getHeight() / 2); // set the arm position to the current position of the pawn if (getTurn() == Piece.Color.BLACK) { // draw a black arm to the stack armFromBelow.moveBy(x - pawnStack.getWidth() / 2, y - pawnStack.getHeight() / 2); } else { // draw a white arm to the stack armFromAbove.moveBy(x - pawnStack.getWidth() / 2, y - pawnStack.getHeight() / 2); } } @Override public void dragStop(InputEvent event, float x, float y, int pointer) { // Code here will run when the player lets go of the actor // Get the position of the tileWidget relative to the parent actor (the gameBoard) Vector2 localCoords = new Vector2(x, y); // Convert the position to stage (screen) coordinates Vector2 screenCoords = pawnStack.localToStageCoordinates(localCoords); System.out.println("\n Drag stopped at screen position: " + screenCoords.x + ", " + screenCoords.y + "\n"); int endTile = calculateTilebyPx((int) screenCoords.x, (int) screenCoords.y); System.out.print("End Tile: " + endTile + "\n"); // for loop through validMoveTiles, at each tile we check for equality of currentCoord // with the Coordinate // in the ArrayList by using currentCoord.checkEqual(validMoveTiles[i]) and if true, // we set the // validMove Variable to true, call on the update method of the Board class and break // the for loop // then clear the Board. if(endTile == possibleMove){ // Board.update with oldX, oldY, newX, newY board[tile.getPosition()].movePiece(endTile); legitMove = true; System.out.println("Move valid as in check of tile to possibleMove"); } else { System.out.println("Move invalid as in check of tile to possibleMove"); } // and the possibleMove is cleared possibleMove = -1; // for turning off the Overlay // turn off the arm stage showArmFromBelowStage = false; showArmFromAboveStage = false; // board is rendered new renderBoard(); } }); // end of listener creation } pawnRoot.add(pawnStack); } public static void createMapStacks(final Tile[] board, Table root, int i){ final Tile tile = board[i]; // ----------------- Tile Stack ----------------- // for the stack below being the tile of the board final Stack stack = new Stack(); stack.setSize(tileSize, tileSize); // add a png of a tile texture to the stack
Image tileTexture = new Image(SenetBoom.tileTexture);
5
2023-12-05 22:19:00+00:00
24k
sinbad-navigator/erp-crm
center/src/main/java/com/ec/web/controller/system/SysProfileController.java
[ { "identifier": "ErpCrmConfig", "path": "common/src/main/java/com/ec/common/config/ErpCrmConfig.java", "snippet": "@Component\n@ConfigurationProperties(prefix = \"ec\")\npublic class ErpCrmConfig {\n /**\n * 上传路径\n */\n private static String profile;\n /**\n * 获取地址开关\n */\n p...
import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.ec.common.annotation.Log; import com.ec.common.config.ErpCrmConfig; import com.ec.common.constant.UserConstants; import com.ec.common.core.controller.BaseController; import com.ec.common.core.domain.AjaxResult; import com.ec.common.core.domain.entity.SysUser; import com.ec.common.core.domain.model.LoginUser; import com.ec.common.enums.BusinessType; import com.ec.common.utils.SecurityUtils; import com.ec.common.utils.StringUtils; import com.ec.common.utils.file.FileUploadUtils; import com.ec.auth.web.service.TokenService; import com.ec.sys.service.ISysUserService;
16,426
package com.ec.web.controller.system; /** * 个人信息 业务处理 * * @author ec */ @RestController @RequestMapping("/system/user/profile") public class SysProfileController extends BaseController { @Autowired private ISysUserService userService; @Autowired private TokenService tokenService; /** * 个人信息 */ @GetMapping public AjaxResult profile() { LoginUser loginUser = getLoginUser(); SysUser user = loginUser.getUser(); AjaxResult ajax = AjaxResult.success(user); ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername())); ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername())); return ajax; } /** * 修改用户 */ @Log(title = "个人信息", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult updateProfile(@RequestBody SysUser user) { LoginUser loginUser = getLoginUser(); SysUser sysUser = loginUser.getUser(); user.setUserName(sysUser.getUserName()); if (StringUtils.isNotEmpty(user.getPhonenumber()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) { return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,手机号码已存在"); } if (StringUtils.isNotEmpty(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) { return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在"); } user.setUserId(sysUser.getUserId()); user.setPassword(null); if (userService.updateUserProfile(user) > 0) { // 更新缓存用户信息 sysUser.setNickName(user.getNickName()); sysUser.setPhonenumber(user.getPhonenumber()); sysUser.setEmail(user.getEmail()); sysUser.setSex(user.getSex()); tokenService.setLoginUser(loginUser); return AjaxResult.success(); } return AjaxResult.error("修改个人信息异常,请联系管理员"); } /** * 重置密码 */ @Log(title = "个人信息", businessType = BusinessType.UPDATE) @PutMapping("/updatePwd") public AjaxResult updatePwd(String oldPassword, String newPassword) { LoginUser loginUser = getLoginUser(); String userName = loginUser.getUsername(); String password = loginUser.getPassword(); if (!SecurityUtils.matchesPassword(oldPassword, password)) { return AjaxResult.error("修改密码失败,旧密码错误"); } if (SecurityUtils.matchesPassword(newPassword, password)) { return AjaxResult.error("新密码不能与旧密码相同"); } if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) { // 更新缓存用户密码 loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword)); tokenService.setLoginUser(loginUser); return AjaxResult.success(); } return AjaxResult.error("修改密码异常,请联系管理员"); } /** * 头像上传 */ @Log(title = "用户头像", businessType = BusinessType.UPDATE) @PostMapping("/avatar") public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException { if (!file.isEmpty()) { LoginUser loginUser = getLoginUser();
package com.ec.web.controller.system; /** * 个人信息 业务处理 * * @author ec */ @RestController @RequestMapping("/system/user/profile") public class SysProfileController extends BaseController { @Autowired private ISysUserService userService; @Autowired private TokenService tokenService; /** * 个人信息 */ @GetMapping public AjaxResult profile() { LoginUser loginUser = getLoginUser(); SysUser user = loginUser.getUser(); AjaxResult ajax = AjaxResult.success(user); ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername())); ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername())); return ajax; } /** * 修改用户 */ @Log(title = "个人信息", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult updateProfile(@RequestBody SysUser user) { LoginUser loginUser = getLoginUser(); SysUser sysUser = loginUser.getUser(); user.setUserName(sysUser.getUserName()); if (StringUtils.isNotEmpty(user.getPhonenumber()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) { return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,手机号码已存在"); } if (StringUtils.isNotEmpty(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) { return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在"); } user.setUserId(sysUser.getUserId()); user.setPassword(null); if (userService.updateUserProfile(user) > 0) { // 更新缓存用户信息 sysUser.setNickName(user.getNickName()); sysUser.setPhonenumber(user.getPhonenumber()); sysUser.setEmail(user.getEmail()); sysUser.setSex(user.getSex()); tokenService.setLoginUser(loginUser); return AjaxResult.success(); } return AjaxResult.error("修改个人信息异常,请联系管理员"); } /** * 重置密码 */ @Log(title = "个人信息", businessType = BusinessType.UPDATE) @PutMapping("/updatePwd") public AjaxResult updatePwd(String oldPassword, String newPassword) { LoginUser loginUser = getLoginUser(); String userName = loginUser.getUsername(); String password = loginUser.getPassword(); if (!SecurityUtils.matchesPassword(oldPassword, password)) { return AjaxResult.error("修改密码失败,旧密码错误"); } if (SecurityUtils.matchesPassword(newPassword, password)) { return AjaxResult.error("新密码不能与旧密码相同"); } if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) { // 更新缓存用户密码 loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword)); tokenService.setLoginUser(loginUser); return AjaxResult.success(); } return AjaxResult.error("修改密码异常,请联系管理员"); } /** * 头像上传 */ @Log(title = "用户头像", businessType = BusinessType.UPDATE) @PostMapping("/avatar") public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException { if (!file.isEmpty()) { LoginUser loginUser = getLoginUser();
String avatar = FileUploadUtils.upload(ErpCrmConfig.getAvatarPath(), file);
9
2023-12-07 14:23:12+00:00
24k
Crydsch/the-one
src/routing/ProphetRouterWithEstimation.java
[ { "identifier": "RoutingInfo", "path": "src/routing/util/RoutingInfo.java", "snippet": "public class RoutingInfo {\n\tprivate String text;\n\tprivate List<RoutingInfo> moreInfo = null;\n\n\t/**\n\t * Creates a routing info based on a text.\n\t * @param infoText The text of the info\n\t */\n\tpublic Rout...
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import routing.util.RoutingInfo; import util.Tuple; import core.Connection; import core.DTNHost; import core.Message; import core.Settings; import core.SimClock;
18,684
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */
public ProphetRouterWithEstimation(Settings s) {
5
2023-12-10 15:51:41+00:00
24k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/input/ControlCustomizer.java
[ { "identifier": "Emulator", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.java", "snippet": "public class Emulator {\n\n\t//gets\n\tfinal static public int IN_MENU = 1;\n\tfinal static public int IN_GAME = 2;\n\tfinal static public int NUMBTNS = 3;\n\tfinal static public ...
import java.util.ArrayList; import java.util.StringTokenizer; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Style; import android.view.MotionEvent; import com.seleuco.mame4droid.Emulator; import com.seleuco.mame4droid.MAME4droid; import com.seleuco.mame4droid.helpers.PrefsHelper;
15,097
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.input; public class ControlCustomizer { private static boolean enabled = false; public static void setEnabled(boolean enabled) { ControlCustomizer.enabled = enabled; } public static boolean isEnabled() { return enabled; } private InputValue valueMoved = null; private int ax = 0; private int ay = 0; private int old_ax = 0; private int old_ay = 0; private int prev_ax = 0; private int prev_ay = 0; protected MAME4droid mm = null; public void setMAME4droid(MAME4droid value) { mm = value; } public void discardDefinedControlLayout() { ArrayList<InputValue> values = mm.getInputHandler().getTouchController().getAllInputData(); for (int j = 0; j < values.size(); j++) { InputValue iv = values.get(j); iv.setOffsetTMP(0, 0); if (iv.getType() == TouchController.TYPE_ANALOG_RECT) mm.getInputHandler().getTouchStick().setStickArea(iv.getRect()); } mm.getInputView().updateImages(); } public void saveDefinedControlLayout() { StringBuffer definedStr = new StringBuffer(); ArrayList<InputValue> values = mm.getInputHandler().getTouchController().getAllInputData(); boolean first = true; for (int j = 0; j < values.size(); j++) { InputValue iv = values.get(j); iv.commitChanges(); if (iv.getXoff() == 0 && iv.getYoff() == 0) continue; if (!first) definedStr.append(","); definedStr.append(iv.getType() + "," + iv.getValue() + "," + iv.getXoff() + "," + iv.getYoff()); first = false; } if (mm.getMainHelper().getscrOrientation() == Configuration.ORIENTATION_LANDSCAPE) mm.getPrefsHelper().setDefinedControlLayoutLand(definedStr.toString()); else mm.getPrefsHelper().setDefinedControlLayoutPortrait(definedStr.toString()); } public void readDefinedControlLayout() {
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.input; public class ControlCustomizer { private static boolean enabled = false; public static void setEnabled(boolean enabled) { ControlCustomizer.enabled = enabled; } public static boolean isEnabled() { return enabled; } private InputValue valueMoved = null; private int ax = 0; private int ay = 0; private int old_ax = 0; private int old_ay = 0; private int prev_ax = 0; private int prev_ay = 0; protected MAME4droid mm = null; public void setMAME4droid(MAME4droid value) { mm = value; } public void discardDefinedControlLayout() { ArrayList<InputValue> values = mm.getInputHandler().getTouchController().getAllInputData(); for (int j = 0; j < values.size(); j++) { InputValue iv = values.get(j); iv.setOffsetTMP(0, 0); if (iv.getType() == TouchController.TYPE_ANALOG_RECT) mm.getInputHandler().getTouchStick().setStickArea(iv.getRect()); } mm.getInputView().updateImages(); } public void saveDefinedControlLayout() { StringBuffer definedStr = new StringBuffer(); ArrayList<InputValue> values = mm.getInputHandler().getTouchController().getAllInputData(); boolean first = true; for (int j = 0; j < values.size(); j++) { InputValue iv = values.get(j); iv.commitChanges(); if (iv.getXoff() == 0 && iv.getYoff() == 0) continue; if (!first) definedStr.append(","); definedStr.append(iv.getType() + "," + iv.getValue() + "," + iv.getXoff() + "," + iv.getYoff()); first = false; } if (mm.getMainHelper().getscrOrientation() == Configuration.ORIENTATION_LANDSCAPE) mm.getPrefsHelper().setDefinedControlLayoutLand(definedStr.toString()); else mm.getPrefsHelper().setDefinedControlLayoutPortrait(definedStr.toString()); } public void readDefinedControlLayout() {
if (mm.getMainHelper().getscrOrientation() == Configuration.ORIENTATION_PORTRAIT && !Emulator.isPortraitFull())
0
2023-12-18 11:16:18+00:00
24k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/gui/inventory/inventories/sbmenu/collection/GUICollectionReward.java
[ { "identifier": "CollectionCategories", "path": "generic/src/main/java/net/swofty/types/generic/collection/CollectionCategories.java", "snippet": "@Getter\npublic enum CollectionCategories {\n FARMING(FarmingCollection.class),\n MINING(MiningCollection.class),\n COMBAT(CombatCollection.class),\...
import net.minestom.server.event.inventory.InventoryCloseEvent; import net.minestom.server.event.inventory.InventoryPreClickEvent; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.swofty.types.generic.collection.CollectionCategories; import net.swofty.types.generic.collection.CollectionCategory; import net.swofty.types.generic.gui.inventory.ItemStackCreator; import net.swofty.types.generic.gui.inventory.SkyBlockInventoryGUI; import net.swofty.types.generic.gui.inventory.inventories.sbmenu.crafting.GUIRecipe; import net.swofty.types.generic.gui.inventory.item.GUIClickableItem; import net.swofty.types.generic.gui.inventory.item.GUIItem; import net.swofty.types.generic.item.ItemType; import net.swofty.types.generic.item.SkyBlockItem; import net.swofty.types.generic.user.SkyBlockPlayer; import net.swofty.types.generic.utility.StringUtility; import java.util.*;
16,279
package net.swofty.types.generic.gui.inventory.inventories.sbmenu.collection; public class GUICollectionReward extends SkyBlockInventoryGUI { private static final Map<Integer, int[]> SLOTS = new HashMap<>(Map.of( 0, new int[] { }, 1, new int[] { 22 }, 2, new int[] { 20, 24 }, 3, new int[] { 20, 22, 24 }, 4, new int[] { 19, 21, 23, 25 } ));
package net.swofty.types.generic.gui.inventory.inventories.sbmenu.collection; public class GUICollectionReward extends SkyBlockInventoryGUI { private static final Map<Integer, int[]> SLOTS = new HashMap<>(Map.of( 0, new int[] { }, 1, new int[] { 22 }, 2, new int[] { 20, 24 }, 3, new int[] { 20, 22, 24 }, 4, new int[] { 19, 21, 23, 25 } ));
private final ItemType item;
7
2023-12-14 09:51:15+00:00
24k
Tianscar/uxgl
desktop/src/test/java/org/example/desktop/foreign/LibraryMapping.java
[ { "identifier": "Pointer", "path": "base/src/main/java/unrefined/nio/Pointer.java", "snippet": "public abstract class Pointer implements Closeable, Duplicatable {\n\n public static final Pointer NULL = Pointer.wrap(0);\n \n private final Allocator allocator;\n\n /**\n * Wraps a Java {@co...
import unrefined.nio.Pointer; import unrefined.runtime.DesktopRuntime; import unrefined.util.UnexpectedError; import unrefined.util.foreign.Foreign; import unrefined.util.foreign.Library; import java.io.IOException; import java.util.Random; import java.util.concurrent.ThreadLocalRandom;
16,015
package org.example.desktop.foreign; /** * UXGL "Library Mapping"! Dynamic proxy objects, working just like JNA! * Note that type mapping as the same of UXGL "Handle Mapping", different from JNA. */ public class LibraryMapping { public interface CLibrary extends Library { void printf(long format, int... args); // Varargs supported! } public static void main(String[] args) { DesktopRuntime.setup(args); // Initialize the UXGL runtime environment Foreign foreign = Foreign.getInstance(); // Get the platform-dependent FFI factory Random random = ThreadLocalRandom.current(); int a = random.nextInt(); int b = random.nextInt(); CLibrary c = foreign.downcallProxy(CLibrary.class);
package org.example.desktop.foreign; /** * UXGL "Library Mapping"! Dynamic proxy objects, working just like JNA! * Note that type mapping as the same of UXGL "Handle Mapping", different from JNA. */ public class LibraryMapping { public interface CLibrary extends Library { void printf(long format, int... args); // Varargs supported! } public static void main(String[] args) { DesktopRuntime.setup(args); // Initialize the UXGL runtime environment Foreign foreign = Foreign.getInstance(); // Get the platform-dependent FFI factory Random random = ThreadLocalRandom.current(); int a = random.nextInt(); int b = random.nextInt(); CLibrary c = foreign.downcallProxy(CLibrary.class);
try (Pointer format = Pointer.allocateDirect("SUM (%d, %d) = %d")) {
0
2023-12-15 19:03:31+00:00
24k
litongjava/next-jfinal
src/main/java/com/jfinal/core/Injector.java
[ { "identifier": "TypeConverter", "path": "src/main/java/com/jfinal/core/converter/TypeConverter.java", "snippet": "public class TypeConverter {\n\t\n\tprivate final Map<Class<?>, IConverter<?>> converterMap = new HashMap<Class<?>, IConverter<?>>(64);\n\tprivate Func.F21<Class<?>, String, Object> convert...
import java.lang.reflect.Method; import java.util.Map; import java.util.Map.Entry; import com.jfinal.core.converter.TypeConverter; import com.jfinal.kit.StrKit; import com.jfinal.plugin.activerecord.ActiveRecordException; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.Table; import com.jfinal.plugin.activerecord.TableMapping; import com.jfinal.servlet.http.HttpServletRequest;
16,431
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jfinal.core; /** * Injector. */ public class Injector { private static <T> T createInstance(Class<T> objClass) { try { return objClass.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } public static <T> T injectModel(Class<T> modelClass, HttpServletRequest request, boolean skipConvertError) { String modelName = modelClass.getSimpleName(); return (T)injectModel(modelClass, StrKit.firstCharToLowerCase(modelName), request, skipConvertError); } public static <T> T injectBean(Class<T> beanClass, HttpServletRequest request, boolean skipConvertError) { String beanName = beanClass.getSimpleName(); return (T)injectBean(beanClass, StrKit.firstCharToLowerCase(beanName), request, skipConvertError); } @SuppressWarnings("unchecked") public static <T> T injectBean(Class<T> beanClass, String beanName, HttpServletRequest request, boolean skipConvertError) { Object bean = createInstance(beanClass); String modelNameAndDot = StrKit.notBlank(beanName) ? beanName + "." : null; TypeConverter converter = TypeConverter.me(); Map<String, String[]> parasMap = request.getParameterMap(); Method[] methods = beanClass.getMethods(); for (Method method : methods) { String methodName = method.getName(); if (methodName.startsWith("set") == false || methodName.length() <= 3) { // only setter method continue; } Class<?>[] types = method.getParameterTypes(); if (types.length != 1) { // only one parameter continue; } String attrName = StrKit.firstCharToLowerCase(methodName.substring(3)); String paraName = modelNameAndDot != null ? modelNameAndDot + attrName : attrName; if (parasMap.containsKey(paraName)) { try { String paraValue = request.getParameter(paraName); Object value = paraValue != null ? converter.convert(types[0], paraValue) : null; method.invoke(bean, value); } catch (Exception e) { if (skipConvertError == false) { // throw new RuntimeException(e); throw new RuntimeException("Can not convert parameter: " + paraName, e); } } } } return (T)bean; } @SuppressWarnings("unchecked") public static <T> T injectModel(Class<T> modelClass, String modelName, HttpServletRequest request, boolean skipConvertError) { Object temp = createInstance(modelClass); if (temp instanceof Model == false) { throw new IllegalArgumentException("getModel only support class of Model, using getBean for other class."); } Model<?> model = (Model<?>)temp; Table table = TableMapping.me().getTable(model.getClass()); if (table == null) {
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jfinal.core; /** * Injector. */ public class Injector { private static <T> T createInstance(Class<T> objClass) { try { return objClass.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } public static <T> T injectModel(Class<T> modelClass, HttpServletRequest request, boolean skipConvertError) { String modelName = modelClass.getSimpleName(); return (T)injectModel(modelClass, StrKit.firstCharToLowerCase(modelName), request, skipConvertError); } public static <T> T injectBean(Class<T> beanClass, HttpServletRequest request, boolean skipConvertError) { String beanName = beanClass.getSimpleName(); return (T)injectBean(beanClass, StrKit.firstCharToLowerCase(beanName), request, skipConvertError); } @SuppressWarnings("unchecked") public static <T> T injectBean(Class<T> beanClass, String beanName, HttpServletRequest request, boolean skipConvertError) { Object bean = createInstance(beanClass); String modelNameAndDot = StrKit.notBlank(beanName) ? beanName + "." : null; TypeConverter converter = TypeConverter.me(); Map<String, String[]> parasMap = request.getParameterMap(); Method[] methods = beanClass.getMethods(); for (Method method : methods) { String methodName = method.getName(); if (methodName.startsWith("set") == false || methodName.length() <= 3) { // only setter method continue; } Class<?>[] types = method.getParameterTypes(); if (types.length != 1) { // only one parameter continue; } String attrName = StrKit.firstCharToLowerCase(methodName.substring(3)); String paraName = modelNameAndDot != null ? modelNameAndDot + attrName : attrName; if (parasMap.containsKey(paraName)) { try { String paraValue = request.getParameter(paraName); Object value = paraValue != null ? converter.convert(types[0], paraValue) : null; method.invoke(bean, value); } catch (Exception e) { if (skipConvertError == false) { // throw new RuntimeException(e); throw new RuntimeException("Can not convert parameter: " + paraName, e); } } } } return (T)bean; } @SuppressWarnings("unchecked") public static <T> T injectModel(Class<T> modelClass, String modelName, HttpServletRequest request, boolean skipConvertError) { Object temp = createInstance(modelClass); if (temp instanceof Model == false) { throw new IllegalArgumentException("getModel only support class of Model, using getBean for other class."); } Model<?> model = (Model<?>)temp; Table table = TableMapping.me().getTable(model.getClass()); if (table == null) {
throw new ActiveRecordException("The Table mapping of model: " + modelClass.getName() +
2
2023-12-19 10:58:33+00:00
24k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/modules/render/ShieldCD.java
[ { "identifier": "Category", "path": "src/java/xyz/apfelmus/cf4m/module/Category.java", "snippet": "public enum Category {\n COMBAT,\n RENDER,\n MOVEMENT,\n PLAYER,\n WORLD,\n MISC,\n NONE;\n\n}" }, { "identifier": "ConfigGUI", "path": "src/java/xyz/apfelmus/cheeto/client...
import java.awt.Color; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import xyz.apfelmus.cf4m.annotation.Event; import xyz.apfelmus.cf4m.annotation.Setting; import xyz.apfelmus.cf4m.annotation.module.Module; import xyz.apfelmus.cf4m.module.Category; import xyz.apfelmus.cheeto.client.clickgui.ConfigGUI; import xyz.apfelmus.cheeto.client.events.Render2DEvent; import xyz.apfelmus.cheeto.client.settings.BooleanSetting; import xyz.apfelmus.cheeto.client.settings.FloatSetting; import xyz.apfelmus.cheeto.client.settings.IntegerSetting; import xyz.apfelmus.cheeto.client.utils.client.FontUtils;
15,787
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.Minecraft * net.minecraft.client.renderer.GlStateManager */ package xyz.apfelmus.cheeto.client.modules.render; @Module(name="ShieldCD", category=Category.RENDER) public class ShieldCD { @Setting(name="xPos") private IntegerSetting xPos = new IntegerSetting(0, 0, 1000); @Setting(name="yPos") private IntegerSetting yPos = new IntegerSetting(0, 0, 1000); @Setting(name="RGB") private BooleanSetting rgb = new BooleanSetting(true); @Setting(name="Scale")
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.Minecraft * net.minecraft.client.renderer.GlStateManager */ package xyz.apfelmus.cheeto.client.modules.render; @Module(name="ShieldCD", category=Category.RENDER) public class ShieldCD { @Setting(name="xPos") private IntegerSetting xPos = new IntegerSetting(0, 0, 1000); @Setting(name="yPos") private IntegerSetting yPos = new IntegerSetting(0, 0, 1000); @Setting(name="RGB") private BooleanSetting rgb = new BooleanSetting(true); @Setting(name="Scale")
private FloatSetting scale = new FloatSetting(Float.valueOf(1.0f), Float.valueOf(0.0f), Float.valueOf(2.5f));
4
2023-12-21 16:22:25+00:00
24k
emtee40/ApkSignatureKill-pc
app/src/main/java/org/jf/dexlib2/dexbacked/instruction/DexBackedInstruction22c.java
[ { "identifier": "Opcode", "path": "app/src/main/java/org/jf/dexlib2/Opcode.java", "snippet": "public enum Opcode {\n NOP(0x00, \"nop\", ReferenceType.NONE, Format.Format10x, Opcode.CAN_CONTINUE),\n MOVE(0x01, \"move\", ReferenceType.NONE, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTE...
import androidx.annotation.NonNull; import org.jf.dexlib2.Opcode; import org.jf.dexlib2.dexbacked.DexBackedDexFile; import org.jf.dexlib2.dexbacked.reference.DexBackedReference; import org.jf.dexlib2.iface.UpdateReference; import org.jf.dexlib2.iface.instruction.formats.Instruction22c; import org.jf.dexlib2.iface.reference.Reference; import org.jf.dexlib2.writer.builder.DexBuilder; import org.jf.util.NibbleUtils;
20,853
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.dexbacked.instruction; public class DexBackedInstruction22c extends DexBackedInstruction implements Instruction22c, UpdateReference { private Reference reference = null; public DexBackedInstruction22c(@NonNull DexBackedDexFile dexFile, @NonNull Opcode opcode, int instructionStart) { super(dexFile, opcode, instructionStart); } @Override public int getRegisterA() {
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.dexbacked.instruction; public class DexBackedInstruction22c extends DexBackedInstruction implements Instruction22c, UpdateReference { private Reference reference = null; public DexBackedInstruction22c(@NonNull DexBackedDexFile dexFile, @NonNull Opcode opcode, int instructionStart) { super(dexFile, opcode, instructionStart); } @Override public int getRegisterA() {
return NibbleUtils.extractLowUnsignedNibble(dexFile.readByte(instructionStart + 1));
7
2023-12-16 11:11:16+00:00
24k
123yyh123/xiaofanshu
xfs-modules-server/xfs-user-server/src/main/java/com/yyh/xfs/user/service/impl/UserServiceImpl.java
[ { "identifier": "Result", "path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/domain/Result.java", "snippet": "@Setter\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Result<T> implements Serializable {\n private Integer code;\n private String msg;\n priv...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.yyh.xfs.common.domain.Result; import com.yyh.xfs.common.myEnum.ExceptionMsgEnum; import com.yyh.xfs.common.redis.constant.RedisConstant; import com.yyh.xfs.common.redis.utils.RedisCache; import com.yyh.xfs.common.redis.utils.RedisKey; import com.yyh.xfs.common.utils.CodeUtil; import com.yyh.xfs.common.utils.Md5Util; import com.yyh.xfs.common.utils.ResultUtil; import com.yyh.xfs.common.utils.TimeUtil; import com.yyh.xfs.common.web.exception.BusinessException; import com.yyh.xfs.common.web.exception.SystemException; import com.yyh.xfs.common.web.properties.JwtProperties; import com.yyh.xfs.common.web.utils.IPUtils; import com.yyh.xfs.common.web.utils.JWTUtil; import com.yyh.xfs.user.domain.UserAttentionDO; import com.yyh.xfs.user.domain.UserDO; import com.yyh.xfs.user.mapper.UserAttentionMapper; import com.yyh.xfs.user.mapper.UserFansMapper; import com.yyh.xfs.user.service.UserService; import com.yyh.xfs.user.mapper.UserMapper; import com.yyh.xfs.user.vo.RegisterInfoVO; import com.yyh.xfs.user.vo.UserTrtcVO; import com.yyh.xfs.user.vo.UserVO; import com.yyh.xfs.user.vo.ViewUserVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import java.sql.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects;
15,601
@Override public Result<?> updateNickname(UserVO userVO) { checkField(userVO.getId(),userVO.getNickname()); if (userVO.getNickname().length() > 12 || userVO.getNickname().length() < 2) { return ResultUtil.errorPost("昵称长度为2-12位"); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "nickname", userVO.getNickname() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改昵称成功", null); } /** * 修改用户简介 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateIntroduction(UserVO userVO) { checkField(userVO.getId(),userVO.getSelfIntroduction()); if (userVO.getSelfIntroduction().length() > 100) { return ResultUtil.errorPost("简介长度不能超过100字"); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "selfIntroduction", userVO.getSelfIntroduction() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改简介成功", null); } /** * 修改用户性别 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateSex(UserVO userVO) { checkField(userVO.getId(),String.valueOf(userVO.getSex())); if (userVO.getSex() < 0 || userVO.getSex() > 1) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "sex", userVO.getSex() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改性别成功", null); } /** * 修改用户生日 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<Integer> updateBirthday(UserVO userVO) { checkField(userVO.getId(),userVO.getBirthday()); Date date = Date.valueOf(userVO.getBirthday()); // 判断生日是否合法,不能大于当前时间 long currentTimeMillis = System.currentTimeMillis(); if (date.getTime() > currentTimeMillis) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } int age = TimeUtil.calculateAge(date.toLocalDate()); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "birthday", userVO.getBirthday() ); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "age", age ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改生日成功", age); } /** * 修改用户地区 * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateArea(UserVO userVO) { checkField(userVO.getId(),userVO.getArea()); // 判断地区是否合法,如果不合法则抛出异常,格式为:省 市 区 String[] split = userVO.getArea().split(" "); if (split.length != 3) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } String area; if (split[0].equals(split[1])) { area = split[0] + " " + split[2]; } else { area = userVO.getArea(); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "area", area ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改地区成功", null); } @Override public Result<ViewUserVO> viewUserInfo(Long userId) { if (Objects.isNull(userId)) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); }
package com.yyh.xfs.user.service.impl; /** * @author yyh * @date 2023-12-11 * 用户服务实现 */ @Service @Slf4j public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService { private static final String DEFAULT_NICKNAME_PREFIX = "小番薯用户"; private final JwtProperties jwtProperties; private final RedisCache redisCache; private final HttpServletRequest request; private final UserAttentionMapper userAttentionMapper; private final UserFansMapper userFansMapper; public UserServiceImpl(RedisCache redisCache, JwtProperties jwtProperties, HttpServletRequest request, UserAttentionMapper userAttentionMapper, UserFansMapper userFansMapper) { this.redisCache = redisCache; this.jwtProperties = jwtProperties; this.request = request; this.userAttentionMapper = userAttentionMapper; this.userFansMapper = userFansMapper; } /** * 登录类型和数据库字段的映射 */ private static final Map<Integer, SFunction<UserDO, String>> LOGIN_TYPE_MAP = new HashMap<>(); /** * 初始化 */ @PostConstruct public void postConstruct() { LOGIN_TYPE_MAP.put(1, UserDO::getWxOpenId); LOGIN_TYPE_MAP.put(2, UserDO::getQqOpenId); LOGIN_TYPE_MAP.put(3, UserDO::getFacebookOpenId); } /** * 手机号登录 * * @param phoneNumber 手机号 * @param password 密码 * @return UserDO */ @Override public Result<UserVO> login(String phoneNumber, String password) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); // 利用MD5加密密码,并且通过手机号给密码加盐 // String md5Password = Md5Util.getMd5(phoneNumber + password); // TODO 暂时使用死密码,方便测试 String md5Password = "@yangyahao5036"; queryWrapper.lambda().eq(UserDO::getPhoneNumber, phoneNumber).eq(UserDO::getPassword, md5Password); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PASSWORD_ERROR); } return generateUserVO(userDO); } /** * 第三方登录验证 * * @param type 登录类型 * @param code 第三方账号的唯一标识 * @return UserDO */ @Override public Result<UserVO> otherLogin(Integer type, String code) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(LOGIN_TYPE_MAP.get(type), code); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { return ResultUtil.errorPost("该第三方账号未绑定"); } return generateUserVO(userDO); } /** * 第三方登录并绑定手机号 * * @param registerInfoVO 注册信息 * @return UserDO */ @Override public Result<UserVO> bindPhone(RegisterInfoVO registerInfoVO) { // 检验验证码是否正确 boolean b = checkSmsCode( RedisKey.build(RedisConstant.REDIS_KEY_SMS_BIND_PHONE_CODE, registerInfoVO.getPhoneNumber()), registerInfoVO.getSmsCode()); if (!b) { throw new BusinessException(ExceptionMsgEnum.SMS_CODE_ERROR); } QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(UserDO::getPhoneNumber, registerInfoVO.getPhoneNumber()); UserDO userDO = this.getOne(queryWrapper); if (Objects.nonNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PHONE_NUMBER_EXIST); } // 注册 UserDO newUserDO = registerAccountByThird(registerInfoVO); return generateUserVO(newUserDO); } /** * 重置密码 * * @param phoneNumber 手机号 * @param password 密码 * @param smsCode 验证码 * @return Result<?> */ @Override public Result<?> resetPassword(String phoneNumber, String password, String smsCode) { boolean b = checkSmsCode( RedisKey.build(RedisConstant.REDIS_KEY_SMS_RESET_PASSWORD_PHONE_CODE, phoneNumber), smsCode); if (!b) { throw new BusinessException(ExceptionMsgEnum.SMS_CODE_ERROR); } QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(UserDO::getPhoneNumber, phoneNumber); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PHONE_NUMBER_NOT_REGISTER); } // 利用MD5加密密码,并且通过手机号给密码加盐 String md5 = Md5Util.getMd5(phoneNumber + password); userDO.setPassword(md5); try { this.updateById(userDO); } catch (Exception e) { throw new SystemException(ExceptionMsgEnum.DB_ERROR, e); } return ResultUtil.successPost("重置密码成功", null); } /** * 通过手机号注册 * * @param registerInfoVO 注册信息 * @return UserDO */ @Override public Result<?> register(RegisterInfoVO registerInfoVO) { // 检验验证码是否正确 boolean b = checkSmsCode( RedisKey.build(RedisConstant.REDIS_KEY_SMS_REGISTER_PHONE_CODE, registerInfoVO.getPhoneNumber()), registerInfoVO.getSmsCode()); if (!b) { throw new BusinessException(ExceptionMsgEnum.SMS_CODE_ERROR); } QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(UserDO::getPhoneNumber, registerInfoVO.getPhoneNumber()); UserDO userDO = this.getOne(queryWrapper); if (Objects.nonNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PHONE_NUMBER_EXIST); } // 注册 UserDO newUserDO = initAccount(registerInfoVO); try { this.save(newUserDO); } catch (Exception e) { throw new SystemException(ExceptionMsgEnum.DB_ERROR, e); } return ResultUtil.successPost("注册成功", null); } /** * 获取用户信息 * @param userId 用户id * @return UserVO */ @Override public Result<UserVO> getUserInfo(Long userId) { if (Objects.isNull(userId)) { throw new BusinessException(ExceptionMsgEnum.NOT_LOGIN); } String ipAddr = IPUtils.getRealIpAddr(request); String addr = IPUtils.getAddrByIp(ipAddr); String address = IPUtils.splitAddress(addr); if (redisCache.hasKey(RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userId)))) { Map<String, Object> map = redisCache.hmget(RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userId))); UserVO userVO = new UserVO(map); userVO.setIpAddr(address); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userId)), "ipAddr", address); return ResultUtil.successGet("获取用户信息成功", userVO); } UserDO userDO = this.getById(userId); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.TOKEN_INVALID); } UserVO userVO = new UserVO(); BeanUtils.copyProperties(userDO, userVO); if (Objects.nonNull(userDO.getBirthday())) { userVO.setBirthday(userDO.getBirthday().toString()); } userVO.setIpAddr(address); Integer attentionNum = userAttentionMapper.getCountById(userDO.getId()); Integer fansNum = userFansMapper.getCountById(userDO.getId()); if (Objects.isNull(attentionNum)) { attentionNum = 0; } if (Objects.isNull(fansNum)) { fansNum = 0; } userVO.setAttentionNum(attentionNum); userVO.setFansNum(fansNum); redisCache.hmset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userDO.getId())), UserVO.toMap(userVO) ); return ResultUtil.successGet("获取用户信息成功", userVO); } /** * 修改用户头像 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateAvatarUrl(UserVO userVO) { checkField(userVO.getId(),userVO.getAvatarUrl()); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "avatarUrl", userVO.getAvatarUrl() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改头像成功", null); } /** * 修改用户背景图片 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateBackgroundImage(UserVO userVO) { checkField(userVO.getId(),userVO.getHomePageBackground()); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "homePageBackground", userVO.getHomePageBackground() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改背景成功", null); } /** * 修改用户昵称 * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateNickname(UserVO userVO) { checkField(userVO.getId(),userVO.getNickname()); if (userVO.getNickname().length() > 12 || userVO.getNickname().length() < 2) { return ResultUtil.errorPost("昵称长度为2-12位"); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "nickname", userVO.getNickname() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改昵称成功", null); } /** * 修改用户简介 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateIntroduction(UserVO userVO) { checkField(userVO.getId(),userVO.getSelfIntroduction()); if (userVO.getSelfIntroduction().length() > 100) { return ResultUtil.errorPost("简介长度不能超过100字"); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "selfIntroduction", userVO.getSelfIntroduction() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改简介成功", null); } /** * 修改用户性别 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateSex(UserVO userVO) { checkField(userVO.getId(),String.valueOf(userVO.getSex())); if (userVO.getSex() < 0 || userVO.getSex() > 1) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "sex", userVO.getSex() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改性别成功", null); } /** * 修改用户生日 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<Integer> updateBirthday(UserVO userVO) { checkField(userVO.getId(),userVO.getBirthday()); Date date = Date.valueOf(userVO.getBirthday()); // 判断生日是否合法,不能大于当前时间 long currentTimeMillis = System.currentTimeMillis(); if (date.getTime() > currentTimeMillis) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } int age = TimeUtil.calculateAge(date.toLocalDate()); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "birthday", userVO.getBirthday() ); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "age", age ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改生日成功", age); } /** * 修改用户地区 * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateArea(UserVO userVO) { checkField(userVO.getId(),userVO.getArea()); // 判断地区是否合法,如果不合法则抛出异常,格式为:省 市 区 String[] split = userVO.getArea().split(" "); if (split.length != 3) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } String area; if (split[0].equals(split[1])) { area = split[0] + " " + split[2]; } else { area = userVO.getArea(); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "area", area ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改地区成功", null); } @Override public Result<ViewUserVO> viewUserInfo(Long userId) { if (Objects.isNull(userId)) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); }
Map<String, Object> token = JWTUtil.parseToken(request.getHeader("token"));
13
2023-12-15 08:13:42+00:00
24k
Blawuken/MicroG-Extended
play-services-core/src/main/java/org/microg/gms/auth/loginservice/AccountAuthenticator.java
[ { "identifier": "AskPermissionActivity", "path": "play-services-core/src/main/java/org/microg/gms/auth/AskPermissionActivity.java", "snippet": "public class AskPermissionActivity extends AccountAuthenticatorActivity {\n public static final String EXTRA_FROM_ACCOUNT_MANAGER = \"from_account_manager\";...
import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.accounts.NetworkErrorException; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Base64; import android.util.Log; import com.google.android.gms.R; import org.microg.gms.auth.AskPermissionActivity; import org.microg.gms.auth.AuthConstants; import org.microg.gms.auth.AuthManager; import org.microg.gms.auth.AuthResponse; import org.microg.gms.auth.login.LoginActivity; import org.microg.gms.common.PackageUtils; import java.util.Arrays; import java.util.List; import static android.accounts.AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE; import static android.accounts.AccountManager.KEY_ACCOUNT_NAME; import static android.accounts.AccountManager.KEY_ACCOUNT_TYPE; import static android.accounts.AccountManager.KEY_ANDROID_PACKAGE_NAME; import static android.accounts.AccountManager.KEY_AUTHTOKEN; import static android.accounts.AccountManager.KEY_BOOLEAN_RESULT; import static android.accounts.AccountManager.KEY_CALLER_PID; import static android.accounts.AccountManager.KEY_CALLER_UID; import static android.accounts.AccountManager.KEY_INTENT;
15,295
/* * Copyright (C) 2013-2017 microG 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 org.microg.gms.auth.loginservice; class AccountAuthenticator extends AbstractAccountAuthenticator { private static final String TAG = "GmsAuthenticator"; private final Context context; private final String accountType; public AccountAuthenticator(Context context) { super(context); this.context = context; this.accountType = AuthConstants.DEFAULT_ACCOUNT_TYPE; } @Override public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { Log.d(TAG, "editProperties: " + accountType); return null; } @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { if (accountType.equals(this.accountType)) { final Intent i = new Intent(context, LoginActivity.class); i.putExtras(options); i.putExtra(LoginActivity.EXTRA_TMPL, LoginActivity.TMPL_NEW_ACCOUNT); i.putExtra(KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); final Bundle result = new Bundle(); result.putParcelable(KEY_INTENT, i); return result; } return null; } @Override public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { Log.d(TAG, "confirmCredentials: " + account + ", " + options); return null; } @Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { options.keySet(); Log.d(TAG, "getAuthToken: " + account + ", " + authTokenType + ", " + options); String app = options.getString(KEY_ANDROID_PACKAGE_NAME); app = PackageUtils.getAndCheckPackage(context, app, options.getInt(KEY_CALLER_UID), options.getInt(KEY_CALLER_PID)); AuthManager authManager = new AuthManager(context, account.name, app, authTokenType); try { AuthResponse res = authManager.requestAuth(true); if (res.auth != null) { Log.d(TAG, "getAuthToken: " + res.auth); Bundle result = new Bundle(); result.putString(KEY_ACCOUNT_TYPE, account.type); result.putString(KEY_ACCOUNT_NAME, account.name); result.putString(KEY_AUTHTOKEN, res.auth); return result; } else { Bundle result = new Bundle();
/* * Copyright (C) 2013-2017 microG 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 org.microg.gms.auth.loginservice; class AccountAuthenticator extends AbstractAccountAuthenticator { private static final String TAG = "GmsAuthenticator"; private final Context context; private final String accountType; public AccountAuthenticator(Context context) { super(context); this.context = context; this.accountType = AuthConstants.DEFAULT_ACCOUNT_TYPE; } @Override public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { Log.d(TAG, "editProperties: " + accountType); return null; } @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { if (accountType.equals(this.accountType)) { final Intent i = new Intent(context, LoginActivity.class); i.putExtras(options); i.putExtra(LoginActivity.EXTRA_TMPL, LoginActivity.TMPL_NEW_ACCOUNT); i.putExtra(KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); final Bundle result = new Bundle(); result.putParcelable(KEY_INTENT, i); return result; } return null; } @Override public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { Log.d(TAG, "confirmCredentials: " + account + ", " + options); return null; } @Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { options.keySet(); Log.d(TAG, "getAuthToken: " + account + ", " + authTokenType + ", " + options); String app = options.getString(KEY_ANDROID_PACKAGE_NAME); app = PackageUtils.getAndCheckPackage(context, app, options.getInt(KEY_CALLER_UID), options.getInt(KEY_CALLER_PID)); AuthManager authManager = new AuthManager(context, account.name, app, authTokenType); try { AuthResponse res = authManager.requestAuth(true); if (res.auth != null) { Log.d(TAG, "getAuthToken: " + res.auth); Bundle result = new Bundle(); result.putString(KEY_ACCOUNT_TYPE, account.type); result.putString(KEY_ACCOUNT_NAME, account.name); result.putString(KEY_AUTHTOKEN, res.auth); return result; } else { Bundle result = new Bundle();
Intent i = new Intent(context, AskPermissionActivity.class);
0
2023-12-17 16:14:53+00:00
24k
PeytonPlayz595/0.30-WebGL-Server
src/com/mojang/minecraft/level/tile/a.java
[ { "identifier": "Vector3DCreator", "path": "src/com/mojang/minecraft/Vector3DCreator.java", "snippet": "public final class Vector3DCreator {\r\n\r\n public Vector3DCreator(int var1, int var2, int var3, int var4, Vector3D var5) {\r\n new Vector3D(var5.x, var5.y, var5.z);\r\n }\r\n}\r" }, { ...
import com.mojang.minecraft.Vector3DCreator; import com.mojang.minecraft.level.Level; import com.mojang.minecraft.level.liquid.LiquidType; import com.mojang.minecraft.level.tile.Tile$SoundType; import com.mojang.minecraft.level.tile.c; import com.mojang.minecraft.level.tile.d; import com.mojang.minecraft.level.tile.e; import com.mojang.minecraft.level.tile.f; import com.mojang.minecraft.level.tile.g; import com.mojang.minecraft.level.tile.h; import com.mojang.minecraft.level.tile.i; import com.mojang.minecraft.level.tile.j; import com.mojang.minecraft.level.tile.k; import com.mojang.minecraft.level.tile.l; import com.mojang.minecraft.level.tile.m; import com.mojang.minecraft.level.tile.n; import com.mojang.minecraft.level.tile.o; import com.mojang.minecraft.level.tile.p; import com.mojang.minecraft.level.tile.q; import com.mojang.minecraft.level.tile.r; import com.mojang.minecraft.level.tile.s; import com.mojang.minecraft.level.tile.t; import com.mojang.minecraft.model.Vector3D; import com.mojang.minecraft.phys.AABB; import java.util.Random;
20,036
package com.mojang.minecraft.level.tile; public class a { protected static Random a = new Random(); public static final a[] b = new a[256]; public static final boolean[] c = new boolean[256]; private static boolean[] ad = new boolean[256]; private static boolean[] ae = new boolean[256]; public static final boolean[] d = new boolean[256]; private static int[] af = new int[256]; public static final a e; public static final a f; public static final a g; public static final a h; public static final a i; public static final a j; public static final a k; public static final a l; public static final a m; public static final a n; public static final a o; public static final a p; public static final a q; public static final a r; public static final a s; public static final a t; public static final a u; public static final a v; public static final a w; public static final a x; public static final a y; public static final a z; public static final a A; public static final a B; public static final a C; public static final a D; public static final a E; public static final a F; public static final a G; public static final a H; public static final a I; public static final a J; public static final a K; public static final a L; public static final a M; public static final a N; public static final a O; public static final a P; public static final a Q; public static final a R; public static final a S; public static final a T; public static final a U; public static final a V; public static final a W; public static final a X; public static final a Y; public static final a Z; public static final a aa; public final int ab; public Tile$SoundType ac; protected boolean ag; private float ah; private float ai; private float aj; private float ak; private float al; private float am; protected a(int var1) { this.ag = true; b[var1] = this; this.ab = var1; this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); ad[var1] = this.c(); ae[var1] = this.a(); d[var1] = false; } public boolean a() { return true; } protected final void a(boolean var1) { c[this.ab] = var1; } protected final void a(float var1, float var2, float var3, float var4, float var5, float var6) { this.ah = var1; this.ai = var2; this.aj = var3; this.ak = var4; this.al = var5; this.am = var6; } protected a(int var1, int var2) { this(var1); } public final void a(int var1) { af[this.ab] = 16; } public AABB a(int var1, int var2, int var3) { return new AABB((float)var1 + this.ah, (float)var2 + this.ai, (float)var3 + this.aj, (float)var1 + this.ak, (float)var2 + this.al, (float)var3 + this.am); } public boolean b() { return true; } public boolean c() { return true; } public void a(Level var1, int var2, int var3, int var4, Random var5) {}
package com.mojang.minecraft.level.tile; public class a { protected static Random a = new Random(); public static final a[] b = new a[256]; public static final boolean[] c = new boolean[256]; private static boolean[] ad = new boolean[256]; private static boolean[] ae = new boolean[256]; public static final boolean[] d = new boolean[256]; private static int[] af = new int[256]; public static final a e; public static final a f; public static final a g; public static final a h; public static final a i; public static final a j; public static final a k; public static final a l; public static final a m; public static final a n; public static final a o; public static final a p; public static final a q; public static final a r; public static final a s; public static final a t; public static final a u; public static final a v; public static final a w; public static final a x; public static final a y; public static final a z; public static final a A; public static final a B; public static final a C; public static final a D; public static final a E; public static final a F; public static final a G; public static final a H; public static final a I; public static final a J; public static final a K; public static final a L; public static final a M; public static final a N; public static final a O; public static final a P; public static final a Q; public static final a R; public static final a S; public static final a T; public static final a U; public static final a V; public static final a W; public static final a X; public static final a Y; public static final a Z; public static final a aa; public final int ab; public Tile$SoundType ac; protected boolean ag; private float ah; private float ai; private float aj; private float ak; private float al; private float am; protected a(int var1) { this.ag = true; b[var1] = this; this.ab = var1; this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); ad[var1] = this.c(); ae[var1] = this.a(); d[var1] = false; } public boolean a() { return true; } protected final void a(boolean var1) { c[this.ab] = var1; } protected final void a(float var1, float var2, float var3, float var4, float var5, float var6) { this.ah = var1; this.ai = var2; this.aj = var3; this.ak = var4; this.al = var5; this.am = var6; } protected a(int var1, int var2) { this(var1); } public final void a(int var1) { af[this.ab] = 16; } public AABB a(int var1, int var2, int var3) { return new AABB((float)var1 + this.ah, (float)var2 + this.ai, (float)var3 + this.aj, (float)var1 + this.ak, (float)var2 + this.al, (float)var3 + this.am); } public boolean b() { return true; } public boolean c() { return true; } public void a(Level var1, int var2, int var3, int var4, Random var5) {}
public LiquidType d() {
2
2023-12-18 15:38:59+00:00
24k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/controller/AcquistoController.java
[ { "identifier": "Utils", "path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/Utils.java", "snippet": "public class Utils {\n\n /**\n * Metodo che converte una stringa contente un tempo, in secondi.\n *\n * @param time in formato \"ore:minuti:secondi\"\n * @return Integer, i sec...
import it.unipv.po.aioobe.trenissimo.model.Utils; import it.unipv.po.aioobe.trenissimo.model.acquisto.Acquisto; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.TitoloViaggioEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.service.TitoloViaggioService; import it.unipv.po.aioobe.trenissimo.model.persistence.service.VoucherService; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.CorsaSingola; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.enumeration.TipoTitoloViaggio; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.utils.TicketBuilder; import it.unipv.po.aioobe.trenissimo.model.user.Account; import it.unipv.po.aioobe.trenissimo.model.viaggio.Viaggio; import it.unipv.po.aioobe.trenissimo.view.HomePage; import it.unipv.po.aioobe.trenissimo.view.ViaggioControl; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.net.URL; import java.util.*;
16,956
this.isRiscattoUsed = false; checkIdRealTime(); checkPagamentoRealTime(); checkDatiRealTime(); if (Account.getLoggedIn()) { txtNome.setText(Account.getInstance().getDatiPersonali().getNome()); txtCognome.setText(Account.getInstance().getDatiPersonali().getCognome()); dtpDataNascita.setValue(Account.getInstance().getDatiPersonali().getDataNascita().toLocalDate()); txtEmail.setText(Account.getInstance().getDatiPersonali().getMail()); txtVia.setText(Account.getInstance().getDatiPersonali().getVia()); txtCivico.setText(Account.getInstance().getDatiPersonali().getCivico()); txtCitta.setText(Account.getInstance().getDatiPersonali().getCitta()); txtCAP.setText(Account.getInstance().getDatiPersonali().getCap().toString()); } } /** * Verifica per abilitazione del tasto acquista dopo la conferma dei dati personali e dei dati di pagamento/riscatto voucher */ private void check() { if ((lblDatiOK.isVisible() && lblCartaOK.isVisible())) btnAcquisto.setDisable(false); else if ((lblDatiOK.isVisible() && acquistoSoloVoucher)) btnAcquisto.setDisable(false); } /** * Imposta i dati dell'acquisto e la lista dei viaggi * * @param viaggi * @see Viaggio */ public void set_viaggi(@NotNull List<Viaggio> viaggi) { for (Viaggio v : viaggi) { subtotale = subtotale + v.getPrezzoTot(); iva = iva + v.getPrezzoIva(); } lblSubtotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); lblIVA.setText("€ " + String.format(Locale.US, "%.2f", iva)); lblTotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); _viaggi.setAll(viaggi); } /** * Gestisce il pagamento e il download del biglietto PDF * * @throws Exception * @see #onScaricaBigliettoPDF(Acquisto) * @see HomePage * @see Acquisto * @see Viaggio * @see CorsaSingola * @see TipoTitoloViaggio * @see Account */ @FXML protected void onPaga() throws Exception { onAlert("Acquisto avvenuto con successo!"); List<Acquisto> biglietti = new ArrayList<>(); for (Viaggio v : _viaggi) { biglietti.add(new CorsaSingola(TipoTitoloViaggio.BIGLIETTOCORSASINGOLA, v)); } biglietti.forEach(x -> x.pagare()); if (Account.getLoggedIn()) { biglietti.forEach(x -> x.puntiFedelta(biglietti)); //metodi per aggiornare i punti fedeltà dal db all'istanza di Account String username = Account.getInstance().getUsername(); Account.getInstance().setAccount(username); } for (Acquisto a : biglietti) { onScaricaBigliettoPDF(a); } biglietto.delete(); HomePage.openScene(root.getScene().getWindow()); } /** * Apre il file chooser e permette di scaricare il biglietto in formato PDF * * @param a * @throws Exception * @see #fillPDF(Acquisto) * @see File * @see FileChooser * @see TicketBuilder */ @FXML protected void onScaricaBigliettoPDF(Acquisto a) throws Exception { fillPDF(a); this.biglietto = new File(TicketBuilder.DEST); //biglietto in folder temporanea FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Scegli dove salvare il titolo di viaggio"); fileChooser.setInitialFileName(a.getId()); File destin = new File(fileChooser.showSaveDialog(new Stage()).getAbsolutePath().concat(".pdf")); TicketBuilder.copy(biglietto, destin); } /** * Compila i campi del biglietto PDF * * @param a acquisto da cui prendere informazioni * @throws Exception * @see TitoloViaggioService * @see TitoloViaggioEntity * @see Acquisto * @see TicketBuilder */ private void fillPDF(@NotNull Acquisto a) throws Exception {
package it.unipv.po.aioobe.trenissimo.controller; /** * Controller class per acquistoView.fxml * * @author ArrayIndexOutOfBoundsException * @see it.unipv.po.aioobe.trenissimo.view.acquistoView * @see javafx.fxml.Initializable */ public class AcquistoController implements Initializable { @FXML private BorderPane root; @FXML private VBox boxViaggi; @FXML private Button btnAcquisto; @FXML private TextField txtNumCarta; @FXML private TextField txtDataScadenza; @FXML private TextField txtCVV; @FXML private Label lblRiscattoOK; @FXML private Label lblErroreRiscatto; @FXML private Button btnRiscatta; @FXML private TextField txtVoucher; @FXML private Label lblSubtotale; @FXML private Label lblIVA; @FXML private Label lblSconto; @FXML private Label lblTotale; @FXML private TextField txtNome; @FXML private TextField txtCognome; @FXML private DatePicker dtpDataNascita; @FXML private TextField txtEmail; @FXML private TextField txtVia; @FXML private TextField txtCivico; @FXML private TextField txtCitta; @FXML private TextField txtCAP; @FXML private Button btnAggiungiPagamento; @FXML private Label lblErroreNumCarta; @FXML private Label lblErroreData; @FXML private Label lblErroreCVV; @FXML private Label lblErroreCAP; @FXML private Label lblErroreEmail; @FXML private Label lblErroreDataNascita; @FXML private Label lblErroreNome; @FXML private Label lblErroreCognome; @FXML private Label lblErroreVia; @FXML private Label lblErroreCivico; @FXML private Label lblErroreCitta; @FXML private Label lblCartaOK; @FXML private Button btnConferma; @FXML private Label lblDatiOK; private ObservableList<Viaggio> _viaggi; private TicketBuilder titoloViaggio; private boolean isIdVoucherOK; private Double subtotale; private Double iva; private boolean acquistoSoloVoucher; private boolean isRiscattoUsed; private File biglietto; /** * Metodo d'Inizializzazione * * @param location * @param resources * @see #checkIdRealTime() * @see #checkPagamentoRealTime() * @see #checkDatiRealTime() * @see Account * @see ViaggioControl */ @Override public void initialize(URL location, ResourceBundle resources) { _viaggi = FXCollections.observableArrayList(); _viaggi.addListener((ListChangeListener<Viaggio>) c -> { boxViaggi.getChildren().setAll(_viaggi.stream().map(x -> new ViaggioControl(x, null)).toList()); }); this.subtotale = 0.0; this.iva = 0.0; this.isRiscattoUsed = false; checkIdRealTime(); checkPagamentoRealTime(); checkDatiRealTime(); if (Account.getLoggedIn()) { txtNome.setText(Account.getInstance().getDatiPersonali().getNome()); txtCognome.setText(Account.getInstance().getDatiPersonali().getCognome()); dtpDataNascita.setValue(Account.getInstance().getDatiPersonali().getDataNascita().toLocalDate()); txtEmail.setText(Account.getInstance().getDatiPersonali().getMail()); txtVia.setText(Account.getInstance().getDatiPersonali().getVia()); txtCivico.setText(Account.getInstance().getDatiPersonali().getCivico()); txtCitta.setText(Account.getInstance().getDatiPersonali().getCitta()); txtCAP.setText(Account.getInstance().getDatiPersonali().getCap().toString()); } } /** * Verifica per abilitazione del tasto acquista dopo la conferma dei dati personali e dei dati di pagamento/riscatto voucher */ private void check() { if ((lblDatiOK.isVisible() && lblCartaOK.isVisible())) btnAcquisto.setDisable(false); else if ((lblDatiOK.isVisible() && acquistoSoloVoucher)) btnAcquisto.setDisable(false); } /** * Imposta i dati dell'acquisto e la lista dei viaggi * * @param viaggi * @see Viaggio */ public void set_viaggi(@NotNull List<Viaggio> viaggi) { for (Viaggio v : viaggi) { subtotale = subtotale + v.getPrezzoTot(); iva = iva + v.getPrezzoIva(); } lblSubtotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); lblIVA.setText("€ " + String.format(Locale.US, "%.2f", iva)); lblTotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); _viaggi.setAll(viaggi); } /** * Gestisce il pagamento e il download del biglietto PDF * * @throws Exception * @see #onScaricaBigliettoPDF(Acquisto) * @see HomePage * @see Acquisto * @see Viaggio * @see CorsaSingola * @see TipoTitoloViaggio * @see Account */ @FXML protected void onPaga() throws Exception { onAlert("Acquisto avvenuto con successo!"); List<Acquisto> biglietti = new ArrayList<>(); for (Viaggio v : _viaggi) { biglietti.add(new CorsaSingola(TipoTitoloViaggio.BIGLIETTOCORSASINGOLA, v)); } biglietti.forEach(x -> x.pagare()); if (Account.getLoggedIn()) { biglietti.forEach(x -> x.puntiFedelta(biglietti)); //metodi per aggiornare i punti fedeltà dal db all'istanza di Account String username = Account.getInstance().getUsername(); Account.getInstance().setAccount(username); } for (Acquisto a : biglietti) { onScaricaBigliettoPDF(a); } biglietto.delete(); HomePage.openScene(root.getScene().getWindow()); } /** * Apre il file chooser e permette di scaricare il biglietto in formato PDF * * @param a * @throws Exception * @see #fillPDF(Acquisto) * @see File * @see FileChooser * @see TicketBuilder */ @FXML protected void onScaricaBigliettoPDF(Acquisto a) throws Exception { fillPDF(a); this.biglietto = new File(TicketBuilder.DEST); //biglietto in folder temporanea FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Scegli dove salvare il titolo di viaggio"); fileChooser.setInitialFileName(a.getId()); File destin = new File(fileChooser.showSaveDialog(new Stage()).getAbsolutePath().concat(".pdf")); TicketBuilder.copy(biglietto, destin); } /** * Compila i campi del biglietto PDF * * @param a acquisto da cui prendere informazioni * @throws Exception * @see TitoloViaggioService * @see TitoloViaggioEntity * @see Acquisto * @see TicketBuilder */ private void fillPDF(@NotNull Acquisto a) throws Exception {
TitoloViaggioService titoloViaggioService = new TitoloViaggioService();
3
2023-12-21 10:41:11+00:00
24k
green-code-initiative/ecoCode-java
src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java
[ { "identifier": "ArrayCopyCheck", "path": "src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java", "snippet": "@Rule(key = \"EC27\")\n@DeprecatedRuleKey(repositoryKey = \"greencodeinitiative-java\", ruleKey = \"GRPS0027\")\npublic class ArrayCopyCheck extends IssuableSubscriptionVisitor {...
import java.util.Collections; import java.util.List; import fr.greencodeinitiative.java.checks.ArrayCopyCheck; import fr.greencodeinitiative.java.checks.AvoidConcatenateStringsInLoop; import fr.greencodeinitiative.java.checks.AvoidFullSQLRequest; import fr.greencodeinitiative.java.checks.AvoidGettingSizeCollectionInLoop; import fr.greencodeinitiative.java.checks.AvoidMultipleIfElseStatement; import fr.greencodeinitiative.java.checks.AvoidRegexPatternNotStatic; import fr.greencodeinitiative.java.checks.AvoidSQLRequestInLoop; import fr.greencodeinitiative.java.checks.AvoidSetConstantInBatchUpdate; import fr.greencodeinitiative.java.checks.AvoidSpringRepositoryCallInLoopOrStreamCheck; import fr.greencodeinitiative.java.checks.AvoidStatementForDMLQueries; import fr.greencodeinitiative.java.checks.AvoidUsageOfStaticCollections; import fr.greencodeinitiative.java.checks.AvoidUsingGlobalVariablesCheck; import fr.greencodeinitiative.java.checks.FreeResourcesOfAutoCloseableInterface; import fr.greencodeinitiative.java.checks.IncrementCheck; import fr.greencodeinitiative.java.checks.InitializeBufferWithAppropriateSize; import fr.greencodeinitiative.java.checks.NoFunctionCallWhenDeclaringForLoop; import fr.greencodeinitiative.java.checks.OptimizeReadFileExceptions; import fr.greencodeinitiative.java.checks.UnnecessarilyAssignValuesToVariables; import fr.greencodeinitiative.java.checks.UseCorrectForLoop; import org.sonar.plugins.java.api.CheckRegistrar; import org.sonar.plugins.java.api.JavaCheck; import org.sonarsource.api.sonarlint.SonarLintSide;
14,701
/* * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.greencodeinitiative.java; /** * Provide the "checks" (implementations of rules) classes that are going be executed during * source code analysis. * <p> * This class is a batch extension by implementing the {@link org.sonar.plugins.java.api.CheckRegistrar} interface. */ @SonarLintSide public class JavaCheckRegistrar implements CheckRegistrar { private static final List<Class<? extends JavaCheck>> ANNOTATED_RULE_CLASSES = List.of( ArrayCopyCheck.class, IncrementCheck.class,
/* * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.greencodeinitiative.java; /** * Provide the "checks" (implementations of rules) classes that are going be executed during * source code analysis. * <p> * This class is a batch extension by implementing the {@link org.sonar.plugins.java.api.CheckRegistrar} interface. */ @SonarLintSide public class JavaCheckRegistrar implements CheckRegistrar { private static final List<Class<? extends JavaCheck>> ANNOTATED_RULE_CLASSES = List.of( ArrayCopyCheck.class, IncrementCheck.class,
AvoidConcatenateStringsInLoop.class,
1
2023-12-19 20:38:40+00:00
24k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/common/container/slot/AttachmentSlot.java
[ { "identifier": "Gun", "path": "src/main/java/com/mrcrayfish/guns/common/Gun.java", "snippet": "public class Gun implements INBTSerializable<CompoundTag>, IEditorMenu\n{\n protected General general = new General();\n protected Projectile projectile = new Projectile();\n protected Sounds sounds ...
import com.mrcrayfish.guns.common.Gun; import com.mrcrayfish.guns.common.container.AttachmentContainer; import com.mrcrayfish.guns.init.ModSounds; import com.mrcrayfish.guns.item.GunItem; import com.mrcrayfish.guns.item.attachment.IAttachment; import net.minecraft.sounds.SoundSource; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentHelper;
17,827
package com.mrcrayfish.guns.common.container.slot; /** * Author: MrCrayfish */ public class AttachmentSlot extends Slot {
package com.mrcrayfish.guns.common.container.slot; /** * Author: MrCrayfish */ public class AttachmentSlot extends Slot {
private AttachmentContainer container;
1
2023-12-18 15:04:35+00:00
24k
ReChronoRain/HyperCeiler
app/src/main/java/com/sevtinge/hyperceiler/module/app/SystemFramework.java
[ { "identifier": "logLevelDesc", "path": "app/src/main/java/com/sevtinge/hyperceiler/utils/log/LogManager.java", "snippet": "public static String logLevelDesc() {\n return switch (logLevel) {\n case 0 -> (\"Disable\");\n case 1 -> (\"Error\");\n case 2 -> (\"Warn\");\n case...
import static com.sevtinge.hyperceiler.utils.api.VoyagerApisKt.isPad; import static com.sevtinge.hyperceiler.utils.devicesdk.SystemSDKKt.isMoreAndroidVersion; import static com.sevtinge.hyperceiler.utils.log.LogManager.logLevelDesc; import com.sevtinge.hyperceiler.module.base.BaseModule; import com.sevtinge.hyperceiler.module.hook.systemframework.AllowUntrustedTouch; import com.sevtinge.hyperceiler.module.hook.systemframework.AllowUntrustedTouchForU; import com.sevtinge.hyperceiler.module.hook.systemframework.AppLinkVerify; import com.sevtinge.hyperceiler.module.hook.systemframework.CleanOpenMenu; import com.sevtinge.hyperceiler.module.hook.systemframework.CleanShareMenu; import com.sevtinge.hyperceiler.module.hook.systemframework.ClipboardWhitelist; import com.sevtinge.hyperceiler.module.hook.systemframework.DeleteOnPostNotification; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableCleaner; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableFreeformBlackList; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableLowApiCheckForU; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableMiuiLite; import com.sevtinge.hyperceiler.module.hook.systemframework.DisablePinVerifyPer72h; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableVerifyCanBeDisabled; import com.sevtinge.hyperceiler.module.hook.systemframework.FlagSecure; import com.sevtinge.hyperceiler.module.hook.systemframework.FreeFormCount; import com.sevtinge.hyperceiler.module.hook.systemframework.FreeformBubble; import com.sevtinge.hyperceiler.module.hook.systemframework.HookEntry; import com.sevtinge.hyperceiler.module.hook.systemframework.MultiFreeFormSupported; import com.sevtinge.hyperceiler.module.hook.systemframework.PackagePermissions; import com.sevtinge.hyperceiler.module.hook.systemframework.QuickScreenshot; import com.sevtinge.hyperceiler.module.hook.systemframework.RemoveSmallWindowRestrictions; import com.sevtinge.hyperceiler.module.hook.systemframework.ScreenRotation; import com.sevtinge.hyperceiler.module.hook.systemframework.SpeedInstall; import com.sevtinge.hyperceiler.module.hook.systemframework.StickyFloatingWindows; import com.sevtinge.hyperceiler.module.hook.systemframework.ThermalBrightness; import com.sevtinge.hyperceiler.module.hook.systemframework.UseOriginalAnimation; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeDefaultStream; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeDisableSafe; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeFirstPress; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeMediaSteps; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeSeparateControl; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeSteps; import com.sevtinge.hyperceiler.module.hook.systemframework.corepatch.BypassSignCheckForT; import com.sevtinge.hyperceiler.module.hook.systemframework.display.AllDarkMode; import com.sevtinge.hyperceiler.module.hook.systemframework.display.DisplayCutout; import com.sevtinge.hyperceiler.module.hook.systemframework.display.ToastTime; import com.sevtinge.hyperceiler.module.hook.systemframework.freeform.OpenAppInFreeForm; import com.sevtinge.hyperceiler.module.hook.systemframework.freeform.UnForegroundPin; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.IgnoreStylusKeyGesture; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.NoMagicPointer; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.RemoveStylusBluetoothRestriction; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.RestoreEsc; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.SetGestureNeedFingerNum; import com.sevtinge.hyperceiler.module.hook.systemframework.network.DualNRSupport; import com.sevtinge.hyperceiler.module.hook.systemframework.network.DualSASupport; import com.sevtinge.hyperceiler.module.hook.systemframework.network.N1Band; import com.sevtinge.hyperceiler.module.hook.systemframework.network.N28Band; import com.sevtinge.hyperceiler.module.hook.systemframework.network.N5N8Band; import com.sevtinge.hyperceiler.module.hook.various.NoAccessDeviceLogsRequest; import de.robv.android.xposed.XposedBridge;
19,485
package com.sevtinge.hyperceiler.module.app; public class SystemFramework extends BaseModule { @Override public void handleLoadPackage() { XposedBridge.log("[HyperCeiler][I]: Log level is " + logLevelDesc()); // 小窗 initHook(new FreeFormCount(), mPrefsMap.getBoolean("system_framework_freeform_count")); initHook(new FreeformBubble(), mPrefsMap.getBoolean("system_framework_freeform_bubble")); initHook(new DisableFreeformBlackList(), mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(RemoveSmallWindowRestrictions.INSTANCE, mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(new StickyFloatingWindows(), mPrefsMap.getBoolean("system_framework_freeform_sticky")); initHook(MultiFreeFormSupported.INSTANCE, mPrefsMap.getBoolean("system_framework_freeform_recents_to_small_freeform")); initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); initHook(new UnForegroundPin(), mPrefsMap.getBoolean("system_framework_freeform_foreground_pin")); // initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); // 音量 initHook(new VolumeDefaultStream()); initHook(new VolumeFirstPress(), mPrefsMap.getBoolean("system_framework_volume_first_press")); initHook(new VolumeSeparateControl(), mPrefsMap.getBoolean("system_framework_volume_separate_control")); initHook(new VolumeSteps(), mPrefsMap.getInt("system_framework_volume_steps", 0) > 0); initHook(new VolumeMediaSteps(), mPrefsMap.getBoolean("system_framework_volume_media_steps_enable")); initHook(new VolumeDisableSafe(), mPrefsMap.getBoolean("system_framework_volume_disable_safe")); // initHook(new ClockShowSecond(), mPrefsMap.getBoolean("system_ui_statusbar_clock_show_second")); // 其他 initHook(new ScreenRotation(), mPrefsMap.getBoolean("system_framework_screen_all_rotations")); initHook(new CleanShareMenu(), mPrefsMap.getBoolean("system_framework_clean_share_menu")); initHook(new CleanOpenMenu(), mPrefsMap.getBoolean("system_framework_clean_open_menu")); initHook(new AllowUntrustedTouch(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch")); if (isMoreAndroidVersion(34)) initHook(new AllowUntrustedTouchForU(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch"));
package com.sevtinge.hyperceiler.module.app; public class SystemFramework extends BaseModule { @Override public void handleLoadPackage() { XposedBridge.log("[HyperCeiler][I]: Log level is " + logLevelDesc()); // 小窗 initHook(new FreeFormCount(), mPrefsMap.getBoolean("system_framework_freeform_count")); initHook(new FreeformBubble(), mPrefsMap.getBoolean("system_framework_freeform_bubble")); initHook(new DisableFreeformBlackList(), mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(RemoveSmallWindowRestrictions.INSTANCE, mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(new StickyFloatingWindows(), mPrefsMap.getBoolean("system_framework_freeform_sticky")); initHook(MultiFreeFormSupported.INSTANCE, mPrefsMap.getBoolean("system_framework_freeform_recents_to_small_freeform")); initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); initHook(new UnForegroundPin(), mPrefsMap.getBoolean("system_framework_freeform_foreground_pin")); // initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); // 音量 initHook(new VolumeDefaultStream()); initHook(new VolumeFirstPress(), mPrefsMap.getBoolean("system_framework_volume_first_press")); initHook(new VolumeSeparateControl(), mPrefsMap.getBoolean("system_framework_volume_separate_control")); initHook(new VolumeSteps(), mPrefsMap.getInt("system_framework_volume_steps", 0) > 0); initHook(new VolumeMediaSteps(), mPrefsMap.getBoolean("system_framework_volume_media_steps_enable")); initHook(new VolumeDisableSafe(), mPrefsMap.getBoolean("system_framework_volume_disable_safe")); // initHook(new ClockShowSecond(), mPrefsMap.getBoolean("system_ui_statusbar_clock_show_second")); // 其他 initHook(new ScreenRotation(), mPrefsMap.getBoolean("system_framework_screen_all_rotations")); initHook(new CleanShareMenu(), mPrefsMap.getBoolean("system_framework_clean_share_menu")); initHook(new CleanOpenMenu(), mPrefsMap.getBoolean("system_framework_clean_open_menu")); initHook(new AllowUntrustedTouch(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch")); if (isMoreAndroidVersion(34)) initHook(new AllowUntrustedTouchForU(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch"));
initHook(new FlagSecure(), mPrefsMap.getBoolean("system_other_flag_secure"));
13
2023-10-27 17:17:42+00:00
24k
sgware/sabre
src/edu/uky/cs/nil/sabre/comp/CompiledAction.java
[ { "identifier": "Action", "path": "src/edu/uky/cs/nil/sabre/Action.java", "snippet": "public class Action implements Event {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/** Identifies the action's name and arguments */\n\tpublic final Sign...
import edu.uky.cs.nil.sabre.Action; import edu.uky.cs.nil.sabre.Character; import edu.uky.cs.nil.sabre.Fluent; import edu.uky.cs.nil.sabre.Settings; import edu.uky.cs.nil.sabre.Signature; import edu.uky.cs.nil.sabre.logic.Clause; import edu.uky.cs.nil.sabre.logic.Conjunction; import edu.uky.cs.nil.sabre.logic.Disjunction; import edu.uky.cs.nil.sabre.logic.Effect; import edu.uky.cs.nil.sabre.logic.Expression; import edu.uky.cs.nil.sabre.logic.False; import edu.uky.cs.nil.sabre.logic.Parameter; import edu.uky.cs.nil.sabre.logic.Precondition; import edu.uky.cs.nil.sabre.util.ImmutableSet;
20,402
package edu.uky.cs.nil.sabre.comp; /** * A compiled action is a {@link edu.uky.cs.nil.sabre.logic.Logical#isGround() * ground} {@link Action action} which defines a {@link * edu.uky.cs.nil.sabre.util.Unique unique} {@link #id ID number} that * corresponds to the action's index in its {@link CompiledProblem#events * compiled problem's set of events}, whose {@link #precondition precondition} * and {@link #observing observation function} are in {@link * Expression#toPrecondition() disjunctive normal form}, and whose {@link * #effect effect} is {@link Expression#toEffect() a clause}. * * @author Stephen G. Ware */ public class CompiledAction extends Action implements CompiledEvent { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** * A unique ID number that corresponds to this action's index in {@link * CompiledProblem#events its compiled problem's set of events} */ public final int id; /** * The action's {@link edu.uky.cs.nil.sabre.Event#getPrecondition() * precondition} in {@link Expression#toPrecondition() in disjunctive normal * form} */ public final Disjunction<Clause<Precondition>> precondition; /** * The action's {@link edu.uky.cs.nil.sabre.Event#getEffect() effect} as a * {@link Expression#toEffect() clause} */ public final Clause<Effect> effect; /** The action's ground {@link Action#consenting} consenting characters */ public final ImmutableSet<Character> consenting; /** * The action's {@link Action#observing observing characters function} in * {@link Expression#toPrecondition() in disjunctive normal form} */ public final CompiledMapping<Disjunction<Clause<Precondition>>> observing; /** * Constructs a new compiled action. * * @param id the action's unique ID number * @param signature the signature * @param precondition the precondition, in disjunctive normal form * @param effect the effect, as a clause * @param consenting the consenting characters * @param observing the observing characters function, in disjunctive normal * form * @param comment the comment */
package edu.uky.cs.nil.sabre.comp; /** * A compiled action is a {@link edu.uky.cs.nil.sabre.logic.Logical#isGround() * ground} {@link Action action} which defines a {@link * edu.uky.cs.nil.sabre.util.Unique unique} {@link #id ID number} that * corresponds to the action's index in its {@link CompiledProblem#events * compiled problem's set of events}, whose {@link #precondition precondition} * and {@link #observing observation function} are in {@link * Expression#toPrecondition() disjunctive normal form}, and whose {@link * #effect effect} is {@link Expression#toEffect() a clause}. * * @author Stephen G. Ware */ public class CompiledAction extends Action implements CompiledEvent { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** * A unique ID number that corresponds to this action's index in {@link * CompiledProblem#events its compiled problem's set of events} */ public final int id; /** * The action's {@link edu.uky.cs.nil.sabre.Event#getPrecondition() * precondition} in {@link Expression#toPrecondition() in disjunctive normal * form} */ public final Disjunction<Clause<Precondition>> precondition; /** * The action's {@link edu.uky.cs.nil.sabre.Event#getEffect() effect} as a * {@link Expression#toEffect() clause} */ public final Clause<Effect> effect; /** The action's ground {@link Action#consenting} consenting characters */ public final ImmutableSet<Character> consenting; /** * The action's {@link Action#observing observing characters function} in * {@link Expression#toPrecondition() in disjunctive normal form} */ public final CompiledMapping<Disjunction<Clause<Precondition>>> observing; /** * Constructs a new compiled action. * * @param id the action's unique ID number * @param signature the signature * @param precondition the precondition, in disjunctive normal form * @param effect the effect, as a clause * @param consenting the consenting characters * @param observing the observing characters function, in disjunctive normal * form * @param comment the comment */
public CompiledAction(int id, Signature signature, Disjunction<Clause<Precondition>> precondition, Clause<Effect> effect, ImmutableSet<Character> consenting, CompiledMapping<Disjunction<Clause<Precondition>>> observing, String comment) {
4
2023-10-26 18:14:19+00:00
24k
granny/Pl3xMap
core/src/main/java/net/pl3x/map/core/renderer/task/UpdateMarkerData.java
[ { "identifier": "Pl3xMap", "path": "core/src/main/java/net/pl3x/map/core/Pl3xMap.java", "snippet": "public abstract class Pl3xMap {\n public static @NotNull Pl3xMap api() {\n return Provider.api();\n }\n\n private final boolean isBukkit;\n\n private final Attributes manifestAttributes...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import net.pl3x.map.core.Pl3xMap; import net.pl3x.map.core.markers.JsonObjectWrapper; import net.pl3x.map.core.markers.layer.Layer; import net.pl3x.map.core.markers.marker.Marker; import net.pl3x.map.core.scheduler.Task; import net.pl3x.map.core.util.FileUtil; import net.pl3x.map.core.world.World; import org.jetbrains.annotations.NotNull;
17,127
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pl3x.map.core.renderer.task; public class UpdateMarkerData extends Task { private final Gson gson = new GsonBuilder() //.setPrettyPrinting() .disableHtmlEscaping() .serializeNulls() .setLenient() .registerTypeHierarchyAdapter(Marker.class, new Adapter()) .create(); private final World world; private final Map<@NotNull String, @NotNull Long> lastUpdated = new HashMap<>(); private final ExecutorService executor; private CompletableFuture<Void> future; private boolean running; public UpdateMarkerData(@NotNull World world) { super(1, true); this.world = world; this.executor = Pl3xMap.ThreadFactory.createService("Pl3xMap-Markers"); } @Override public void run() { if (this.running) { return; } this.running = true; this.future = CompletableFuture.runAsync(() -> { try { parseLayers(); } catch (Throwable t) { t.printStackTrace(); } this.running = false; }, this.executor); } @Override public void cancel() { super.cancel(); if (this.future != null) { this.future.cancel(true); } } private void parseLayers() { List<Object> layers = new ArrayList<>(); this.world.getLayerRegistry().entrySet().forEach(entry -> { String key = entry.getKey(); Layer layer = entry.getValue(); try { layers.add(layer.toJson()); long now = System.currentTimeMillis() / 1000; long lastUpdate = this.lastUpdated.getOrDefault(key, 0L); if (now - lastUpdate > layer.getUpdateInterval()) { List<Marker<?>> list = new ArrayList<>(layer.getMarkers()); FileUtil.writeJson(this.gson.toJson(list), this.world.getMarkersDirectory().resolve(key.replace(":", "-") + ".json")); this.lastUpdated.put(key, now); } } catch (Throwable t) { t.printStackTrace(); } }); FileUtil.writeJson(this.gson.toJson(layers), this.world.getTilesDirectory().resolve("markers.json")); } private static class Adapter implements JsonSerializer<@NotNull Marker<?>> { @Override public @NotNull JsonElement serialize(@NotNull Marker<?> marker, @NotNull Type type, @NotNull JsonSerializationContext context) {
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pl3x.map.core.renderer.task; public class UpdateMarkerData extends Task { private final Gson gson = new GsonBuilder() //.setPrettyPrinting() .disableHtmlEscaping() .serializeNulls() .setLenient() .registerTypeHierarchyAdapter(Marker.class, new Adapter()) .create(); private final World world; private final Map<@NotNull String, @NotNull Long> lastUpdated = new HashMap<>(); private final ExecutorService executor; private CompletableFuture<Void> future; private boolean running; public UpdateMarkerData(@NotNull World world) { super(1, true); this.world = world; this.executor = Pl3xMap.ThreadFactory.createService("Pl3xMap-Markers"); } @Override public void run() { if (this.running) { return; } this.running = true; this.future = CompletableFuture.runAsync(() -> { try { parseLayers(); } catch (Throwable t) { t.printStackTrace(); } this.running = false; }, this.executor); } @Override public void cancel() { super.cancel(); if (this.future != null) { this.future.cancel(true); } } private void parseLayers() { List<Object> layers = new ArrayList<>(); this.world.getLayerRegistry().entrySet().forEach(entry -> { String key = entry.getKey(); Layer layer = entry.getValue(); try { layers.add(layer.toJson()); long now = System.currentTimeMillis() / 1000; long lastUpdate = this.lastUpdated.getOrDefault(key, 0L); if (now - lastUpdate > layer.getUpdateInterval()) { List<Marker<?>> list = new ArrayList<>(layer.getMarkers()); FileUtil.writeJson(this.gson.toJson(list), this.world.getMarkersDirectory().resolve(key.replace(":", "-") + ".json")); this.lastUpdated.put(key, now); } } catch (Throwable t) { t.printStackTrace(); } }); FileUtil.writeJson(this.gson.toJson(layers), this.world.getTilesDirectory().resolve("markers.json")); } private static class Adapter implements JsonSerializer<@NotNull Marker<?>> { @Override public @NotNull JsonElement serialize(@NotNull Marker<?> marker, @NotNull Type type, @NotNull JsonSerializationContext context) {
JsonObjectWrapper wrapper = new JsonObjectWrapper();
1
2023-10-26 01:14:31+00:00
24k
kandybaby/S3mediaArchival
backend/src/test/java/com/example/mediaarchival/MediaArchivalApplicationTests.java
[ { "identifier": "MediaObjectTransferListenerTest", "path": "backend/src/test/java/com/example/mediaarchival/consumers/MediaObjectTransferListenerTest.java", "snippet": "public class MediaObjectTransferListenerTest {\n\n @Mock private MediaRepository mediaRepository;\n\n @Mock private MediaController m...
import com.example.mediaarchival.consumers.MediaObjectTransferListenerTest; import com.example.mediaarchival.controllers.LibraryControllerTest; import com.example.mediaarchival.controllers.MediaControllerTest; import com.example.mediaarchival.controllers.UserControllerTest; import com.example.mediaarchival.converters.StringToArchivedStatusConverterTest; import com.example.mediaarchival.converters.StringToMediaTypeConverterTest; import com.example.mediaarchival.deserializers.ArchivedStatusDeserializerTest; import com.example.mediaarchival.deserializers.MediaCategoryDeserializerTest; import com.example.mediaarchival.filters.JwtValidationFilterTest; import com.example.mediaarchival.tasks.S3CleanupTaskTest; import com.example.mediaarchival.tasks.StartupResetTasksTest; import com.example.mediaarchival.utils.TarUtilsTest; import com.example.mediaarchival.utils.TokenUtilsTest; import com.example.mediaarchival.tasks.RestoreCheckerTest; import com.example.mediaarchival.utils.DirectoryUtilsTest; import com.example.mediaarchival.consumers.LibraryUpdateConsumerTest; import com.example.mediaarchival.consumers.RestoreConsumerTest; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance;
16,798
package com.example.mediaarchival; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaArchivalApplicationTests { @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaControllerTests extends MediaControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LibraryControllerTests extends LibraryControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS)
package com.example.mediaarchival; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaArchivalApplicationTests { @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaControllerTests extends MediaControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LibraryControllerTests extends LibraryControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class JwtValidationFilterTests extends JwtValidationFilterTest {}
8
2023-10-27 01:54:57+00:00
24k
siam1026/siam-cloud
siam-goods/goods-provider/src/main/java/com/siam/package_goods/controller/merchant/MerchantGoodsController.java
[ { "identifier": "BasicResultCode", "path": "siam-common/src/main/java/com/siam/package_common/constant/BasicResultCode.java", "snippet": "public class BasicResultCode {\n public static final int ERR = 0;\n\n public static final int SUCCESS = 1;\n\n public static final int TOKEN_ERR = 2;\n}" }...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.annoation.MerchantPermission; import com.siam.package_common.constant.BasicResultCode; import com.siam.package_common.constant.Quantity; import com.siam.package_common.entity.BasicData; import com.siam.package_common.entity.BasicResult; import com.siam.package_common.exception.StoneCustomerException; import com.siam.package_common.util.OSSUtils; import com.siam.package_goods.entity.Goods; import com.siam.package_goods.entity.MenuGoodsRelation; import com.siam.package_goods.model.dto.GoodsMenuDto; import com.siam.package_goods.model.example.MenuGoodsRelationExample; import com.siam.package_goods.service.*; import com.siam.package_merchant.auth.cache.MerchantSessionManager; import com.siam.package_merchant.entity.Merchant; import com.siam.package_promotion.feign.CouponsFeignApi; import com.siam.package_promotion.feign.CouponsGoodsRelationFeignApi; import com.siam.package_user.util.TokenUtil; import com.siam.package_util.entity.PictureUploadRecord; import com.siam.package_util.feign.PictureUploadRecordFeignApi; import com.siam.package_util.model.example.PictureUploadRecordExample; import com.siam.package_util.model.param.PictureUploadRecordParam; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.List; import java.util.Map;
18,704
package com.siam.package_goods.controller.merchant; @RestController @RequestMapping(value = "/rest/merchant/goods") @Transactional(rollbackFor = Exception.class) @Api(tags = "商家端商品模块相关接口", description = "MerchantGoodsController") public class MerchantGoodsController { @Autowired private GoodsService goodsService; @Autowired private OSSUtils ossUtils; @Autowired private MenuGoodsRelationService menuGoodsRelationService; @Autowired private GoodsSpecificationService goodsSpecificationService; @Autowired private GoodsSpecificationOptionService goodsSpecificationOptionService; @Autowired private ShoppingCartService shoppingCartService; @Autowired private GoodsRawmaterialRelationService goodsRawmaterialRelationService; @Autowired private CouponsFeignApi couponsFeignApi; @Autowired private CouponsGoodsRelationFeignApi couponsGoodsRelationFeignApi; // @Autowired // private MerchantService merchantService; @Autowired private PictureUploadRecordFeignApi pictureUploadRecordFeignApi; @Autowired private MerchantSessionManager merchantSessionManager; @ApiOperation(value = "商品列表") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "商品表主键id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "name", value = "商品名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "categoryId", value = "分类id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "categoryName", value = "分类名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "brandId", value = "品牌id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "brandName", value = "品牌名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "mainImage", value = "商品主图", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "subImages", value = "商品子图", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "specList", value = "商品规格", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detail", value = "商品详情", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detailImages", value = "详情图片", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "price", value = "一口价", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "salePrice", value = "折扣价", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "monthlySales", value = "月销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalSales", value = "累计销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalComments", value = "累计评价", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "stock", value = "库存", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "productTime", value = "制作时长(分钟)", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "exchangePoints", value = "兑换商品所需积分数量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "isHot", value = "是否热门", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "isNew", value = "是否新品", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "status", value = "状态 1=启用 0=禁用 -1=删除", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "menuId", value = "菜单id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "menuName", value = "菜单名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "pageNo", value = "页码(值为-1不分页)", required = true, paramType = "query", dataType = "int", defaultValue = "1"), @ApiImplicitParam(name = "pageSize", value = "页数", required = true, paramType = "query", dataType = "int", defaultValue = "20"), }) @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) GoodsMenuDto goodsMenuDto, HttpServletRequest request){ BasicData basicResult = new BasicData(); //获取当前登录用户绑定的门店编号 Merchant loginMerchant = merchantSessionManager.getSession(TokenUtil.getToken()); goodsMenuDto.setShopId(loginMerchant.getShopId()); Page<Map<String, Object>> page = goodsService.getListByPageJoinMenu(goodsMenuDto.getPageNo(), goodsMenuDto.getPageSize(), goodsMenuDto); return BasicResult.success(page); } @ApiOperation(value = "新增商品") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "商品名称", required = true, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "categoryId", value = "分类id", required = true, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "categoryName", value = "分类名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "brandId", value = "品牌id", required = true, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "brandName", value = "品牌名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "mainImage", value = "商品主图", required = true, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "subImages", value = "商品子图(多图上传)", required = true, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "specList", value = "商品规格", required = true, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detail", value = "商品详情", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detailImages", value = "详情图片(多图上传)", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "price", value = "一口价", required = true, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "salePrice", value = "折扣价", required = true, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "monthlySales", value = "月销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalSales", value = "累计销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalComments", value = "累计评价", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "stock", value = "库存", required = true, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "productTime", value = "制作时长(分钟)", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "exchangePoints", value = "兑换商品所需积分数量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "isHot", value = "是否热门", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "isNew", value = "是否新品", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "status", value = "状态 1=启用 0=禁用 -1=删除", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "menuId", value = "菜单id", required = false, paramType = "query", dataType = "int"), }) @PostMapping(value = "/insert") public BasicResult insert(@RequestBody @Validated(value = {}) Goods goods, HttpServletRequest request){ BasicResult basicResult = new BasicResult(); //获取当前登录用户绑定的门店编号 Merchant loginMerchant = merchantSessionManager.getSession(TokenUtil.getToken()); //商品的主图 等于 商品轮播图的第一张图 if(StringUtils.isNotBlank(goods.getSubImages())){ goods.setMainImage(goods.getSubImages().split(",")[0]); } //添加商品记录 //设置默认库存为0 goods.setShopId(loginMerchant.getShopId()); goods.setStock(Quantity.INT_0); goods.setMonthlySales(Quantity.INT_0); goods.setTotalSales(Quantity.INT_0); goods.setTotalComments(Quantity.INT_0); goods.setCreateTime(new Date()); goods.setUpdateTime(new Date()); //兑换商品所需积分数量新增时默认等于折扣价 goods.setExchangePoints(goods.getPrice().intValue()); goodsService.insertSelective(goods); //建立商品与类别的关系 MenuGoodsRelation insertMenuGoodsRelation = new MenuGoodsRelation(); insertMenuGoodsRelation.setGoodsId(goods.getId()); insertMenuGoodsRelation.setMenuId(goods.getMenuId()); insertMenuGoodsRelation.setCreateTime(new Date()); insertMenuGoodsRelation.setUpdateTime(new Date()); menuGoodsRelationService.insertSelective(insertMenuGoodsRelation); //生成商品公共规格 goodsSpecificationService.insertPublicGoodsSpecification(goods.getId()); //TODO(MARK)-目前只能通过图片地址来判别重复,后续可以优化成那个啥位数来判定唯一 //添加图片上传记录 if(StringUtils.isNotBlank(goods.getSubImages())){ String[] array = goods.getSubImages().split(","); for (String str : array) {
package com.siam.package_goods.controller.merchant; @RestController @RequestMapping(value = "/rest/merchant/goods") @Transactional(rollbackFor = Exception.class) @Api(tags = "商家端商品模块相关接口", description = "MerchantGoodsController") public class MerchantGoodsController { @Autowired private GoodsService goodsService; @Autowired private OSSUtils ossUtils; @Autowired private MenuGoodsRelationService menuGoodsRelationService; @Autowired private GoodsSpecificationService goodsSpecificationService; @Autowired private GoodsSpecificationOptionService goodsSpecificationOptionService; @Autowired private ShoppingCartService shoppingCartService; @Autowired private GoodsRawmaterialRelationService goodsRawmaterialRelationService; @Autowired private CouponsFeignApi couponsFeignApi; @Autowired private CouponsGoodsRelationFeignApi couponsGoodsRelationFeignApi; // @Autowired // private MerchantService merchantService; @Autowired private PictureUploadRecordFeignApi pictureUploadRecordFeignApi; @Autowired private MerchantSessionManager merchantSessionManager; @ApiOperation(value = "商品列表") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "商品表主键id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "name", value = "商品名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "categoryId", value = "分类id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "categoryName", value = "分类名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "brandId", value = "品牌id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "brandName", value = "品牌名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "mainImage", value = "商品主图", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "subImages", value = "商品子图", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "specList", value = "商品规格", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detail", value = "商品详情", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detailImages", value = "详情图片", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "price", value = "一口价", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "salePrice", value = "折扣价", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "monthlySales", value = "月销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalSales", value = "累计销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalComments", value = "累计评价", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "stock", value = "库存", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "productTime", value = "制作时长(分钟)", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "exchangePoints", value = "兑换商品所需积分数量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "isHot", value = "是否热门", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "isNew", value = "是否新品", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "status", value = "状态 1=启用 0=禁用 -1=删除", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "menuId", value = "菜单id", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "menuName", value = "菜单名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "pageNo", value = "页码(值为-1不分页)", required = true, paramType = "query", dataType = "int", defaultValue = "1"), @ApiImplicitParam(name = "pageSize", value = "页数", required = true, paramType = "query", dataType = "int", defaultValue = "20"), }) @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) GoodsMenuDto goodsMenuDto, HttpServletRequest request){ BasicData basicResult = new BasicData(); //获取当前登录用户绑定的门店编号 Merchant loginMerchant = merchantSessionManager.getSession(TokenUtil.getToken()); goodsMenuDto.setShopId(loginMerchant.getShopId()); Page<Map<String, Object>> page = goodsService.getListByPageJoinMenu(goodsMenuDto.getPageNo(), goodsMenuDto.getPageSize(), goodsMenuDto); return BasicResult.success(page); } @ApiOperation(value = "新增商品") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "商品名称", required = true, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "categoryId", value = "分类id", required = true, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "categoryName", value = "分类名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "brandId", value = "品牌id", required = true, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "brandName", value = "品牌名称", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "mainImage", value = "商品主图", required = true, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "subImages", value = "商品子图(多图上传)", required = true, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "specList", value = "商品规格", required = true, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detail", value = "商品详情", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "detailImages", value = "详情图片(多图上传)", required = false, paramType = "query", dataType = "string"), @ApiImplicitParam(name = "price", value = "一口价", required = true, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "salePrice", value = "折扣价", required = true, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "monthlySales", value = "月销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalSales", value = "累计销量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "totalComments", value = "累计评价", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "stock", value = "库存", required = true, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "productTime", value = "制作时长(分钟)", required = false, paramType = "query", dataType = "BigDecimal"), @ApiImplicitParam(name = "exchangePoints", value = "兑换商品所需积分数量", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "isHot", value = "是否热门", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "isNew", value = "是否新品", required = false, paramType = "query", dataType = "Boolean"), @ApiImplicitParam(name = "status", value = "状态 1=启用 0=禁用 -1=删除", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "menuId", value = "菜单id", required = false, paramType = "query", dataType = "int"), }) @PostMapping(value = "/insert") public BasicResult insert(@RequestBody @Validated(value = {}) Goods goods, HttpServletRequest request){ BasicResult basicResult = new BasicResult(); //获取当前登录用户绑定的门店编号 Merchant loginMerchant = merchantSessionManager.getSession(TokenUtil.getToken()); //商品的主图 等于 商品轮播图的第一张图 if(StringUtils.isNotBlank(goods.getSubImages())){ goods.setMainImage(goods.getSubImages().split(",")[0]); } //添加商品记录 //设置默认库存为0 goods.setShopId(loginMerchant.getShopId()); goods.setStock(Quantity.INT_0); goods.setMonthlySales(Quantity.INT_0); goods.setTotalSales(Quantity.INT_0); goods.setTotalComments(Quantity.INT_0); goods.setCreateTime(new Date()); goods.setUpdateTime(new Date()); //兑换商品所需积分数量新增时默认等于折扣价 goods.setExchangePoints(goods.getPrice().intValue()); goodsService.insertSelective(goods); //建立商品与类别的关系 MenuGoodsRelation insertMenuGoodsRelation = new MenuGoodsRelation(); insertMenuGoodsRelation.setGoodsId(goods.getId()); insertMenuGoodsRelation.setMenuId(goods.getMenuId()); insertMenuGoodsRelation.setCreateTime(new Date()); insertMenuGoodsRelation.setUpdateTime(new Date()); menuGoodsRelationService.insertSelective(insertMenuGoodsRelation); //生成商品公共规格 goodsSpecificationService.insertPublicGoodsSpecification(goods.getId()); //TODO(MARK)-目前只能通过图片地址来判别重复,后续可以优化成那个啥位数来判定唯一 //添加图片上传记录 if(StringUtils.isNotBlank(goods.getSubImages())){ String[] array = goods.getSubImages().split(","); for (String str : array) {
PictureUploadRecordParam uploadRecordParam = new PictureUploadRecordParam();
18
2023-10-26 10:45:10+00:00
24k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/CandidateWordView.java
[ { "identifier": "BackgroundDrawableFactory", "path": "app/src/main/java/sh/eliza/japaneseinput/keyboard/BackgroundDrawableFactory.java", "snippet": "public class BackgroundDrawableFactory {\n /** Drawable to create. */\n public enum DrawableType {\n // Key background for twelvekeys layout.\n TWE...
import android.content.Context; import android.graphics.Canvas; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityManager; import android.widget.EdgeEffect; import androidx.core.view.ViewCompat; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import javax.annotation.Nullable; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateList; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateWord; import sh.eliza.japaneseinput.accessibility.CandidateWindowAccessibilityDelegate; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory.DrawableType; import sh.eliza.japaneseinput.ui.CandidateLayout; import sh.eliza.japaneseinput.ui.CandidateLayout.Row; import sh.eliza.japaneseinput.ui.CandidateLayout.Span; import sh.eliza.japaneseinput.ui.CandidateLayoutRenderer; import sh.eliza.japaneseinput.ui.CandidateLayouter; import sh.eliza.japaneseinput.ui.SnapScroller; import sh.eliza.japaneseinput.view.Skin;
14,941
float candidateLength = orientationTrait.getCandidateLength(row, span); int viewLength = orientationTrait.getViewLength(this); if (candidatePosition < scrollPosition || candidatePosition + candidateLength > scrollPosition + viewLength) { return (int) candidatePosition; } else { return scrollPosition; } } /** * If focused candidate is invisible (including partial invisible), update scroll position to see * the candidate. */ protected void updateScrollPositionBasedOnFocusedIndex() { int scrollPosition = 0; if (calculatedLayout != null && currentCandidateList != null) { int focusedIndex = currentCandidateList.getFocusedIndex(); row_loop: for (Row row : calculatedLayout.getRowList()) { for (Span span : row.getSpanList()) { if (!span.getCandidateWord().isPresent()) { continue; } if (span.getCandidateWord().get().getIndex() == focusedIndex) { scrollPosition = getUpdatedScrollPosition(row, span); break row_loop; } } } } setScrollPosition(scrollPosition); } void setScrollPosition(int position) { scroller.scrollTo(position); orientationTrait.scrollTo(this, scroller.getScrollPosition()); invalidate(); } void update(CandidateList candidateList) { CandidateList previousCandidateList = currentCandidateList; currentCandidateList = candidateList; Optional<CandidateList> optionalCandidateList = Optional.fromNullable(candidateList); candidateLayoutRenderer.setCandidateList(optionalCandidateList); if (layouter != null && !equals(candidateList, previousCandidateList)) { updateCalculatedLayout(); } updateScroller(); invalidate(); } private static boolean equals(CandidateList list1, CandidateList list2) { if (list1 == list2) { return true; } if (list1 == null || list2 == null) { return false; } return list1.getCandidatesList().equals(list2.getCandidatesList()); } /** * Updates the layouter, and also updates the calculatedLayout based on the updated layouter. * * <p>TODO(hidehiko): This method is remaining here to reduce a CL size smaller in order to make * refactoring step by step. This will be cleaned when CandidateWordView is refactored. */ protected final void updateLayouter() { updateCalculatedLayout(); updateScroller(); } /** Updates the calculatedLayout if possible. */ private void updateCalculatedLayout() { if (currentCandidateList == null || layouter == null) { calculatedLayout = null; } else { calculatedLayout = layouter.layout(currentCandidateList).orNull(); } accessibilityDelegate.setCandidateLayout( calculatedLayout, (int) orientationTrait.getContentSize(Optional.fromNullable(calculatedLayout)), orientationTrait.getViewLength(this)); } private void updateScroller() { if (calculatedLayout == null || layouter == null) { scroller.setPageSize(0); scroller.setContentSize(0); } else { int pageSize = orientationTrait.getPageSize(layouter); int contentSize = (int) orientationTrait.getContentSize(Optional.fromNullable(calculatedLayout)); if (pageSize != 0) { // Ceil to align pages. contentSize = (contentSize + pageSize - 1) / pageSize * pageSize; } scroller.setPageSize(pageSize); scroller.setContentSize(contentSize); } scroller.setViewSize(orientationTrait.getViewLength(this)); } protected void setSpanBackgroundDrawableType(DrawableType drawableType) { backgroundDrawableType = drawableType; resetSpanBackground(); } private void resetSpanBackground() { Drawable drawable = (backgroundDrawableType != null) ? backgroundDrawableFactory.getDrawable(backgroundDrawableType) : null; candidateLayoutRenderer.setSpanBackgroundDrawable(Optional.fromNullable(drawable)); } /** Returns a Drawable which should be set as the view's background. */
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package sh.eliza.japaneseinput; /** A view for candidate words. */ // TODO(matsuzakit): Optional is introduced partially. Complete introduction. abstract class CandidateWordView extends View implements MemoryManageable { /** Handles gestures to scroll candidate list and choose a candidate. */ class CandidateWordGestureDetector { class CandidateWordViewGestureListener extends SimpleOnGestureListener { @Override public boolean onFling( MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) { float velocity = orientationTrait.projectVector(velocityX, velocityY); // As fling is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Fling makes scrolling. scroller.fling(-(int) velocity); invalidate(); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float distance = orientationTrait.projectVector(distanceX, distanceY); int oldScrollPosition = scroller.getScrollPosition(); int oldMaxScrollPosition = scroller.getMaxScrollPosition(); scroller.scrollBy((int) distance); orientationTrait.scrollTo(CandidateWordView.this, scroller.getScrollPosition()); // As scroll is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Edge effect. Now, in production, we only support vertical scroll. if (oldScrollPosition + distance < 0) { topEdgeEffect.onPull(distance / getHeight()); if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); } } else if (oldScrollPosition + distance > oldMaxScrollPosition) { bottomEdgeEffect.onPull(distance / getHeight()); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); } } invalidate(); return true; } } // GestureDetector cannot handle all complex gestures which we need. // But we use GestureDetector for some gesture recognition // because implementing whole gesture detection logic by ourselves is a bit tedious. private final GestureDetector gestureDetector; /** * Points to an instance of currently pressed candidate word. Or {@code null} if any candidates * aren't pressed. */ @Nullable private CandidateWord pressedCandidate; private final RectF candidateRect = new RectF(); private Optional<Integer> pressedRowIndex = Optional.absent(); public CandidateWordGestureDetector(Context context) { gestureDetector = new GestureDetector(context, new CandidateWordViewGestureListener()); } private void pressCandidate(int rowIndex, Span span) { Row row = calculatedLayout.getRowList().get(rowIndex); pressedRowIndex = Optional.of(rowIndex); pressedCandidate = span.getCandidateWord().orNull(); // TODO(yamaguchi):maybe better to make this rect larger by several pixels to avoid that // users fail to select a candidate by unconscious small movement of tap point. // (i.e. give hysterisis for noise reduction) // Needs UX study. candidateRect.set( span.getLeft(), row.getTop(), span.getRight(), row.getTop() + row.getHeight()); } void reset() { pressedCandidate = null; pressedRowIndex = Optional.absent(); // NOTE: candidateRect doesn't need reset. } CandidateWord getPressedCandidate() { return pressedCandidate; } /** * Checks if a down event is fired inside a candidate rectangle. If so, begin pressing it. * * <p>It is assumed that rows are stored in up-to-down order, and spans are in left-to-right * order. * * @param scrolledX X coordinate of down event point including scroll offset * @param scrolledY Y coordinate of down event point including scroll offset * @return true if the down event is fired inside a candidate rectangle. */ private boolean findCandidateAndPress(float scrolledX, float scrolledY) { if (calculatedLayout == null) { return false; } for (int rowIndex = 0; rowIndex < calculatedLayout.getRowList().size(); ++rowIndex) { Row row = calculatedLayout.getRowList().get(rowIndex); if (scrolledY < row.getTop()) { break; } if (scrolledY >= row.getTop() + row.getHeight()) { continue; } for (Span span : row.getSpanList()) { if (scrolledX < span.getLeft()) { break; } if (scrolledX >= span.getRight()) { continue; } pressCandidate(rowIndex, span); invalidate(); return true; } return false; } return false; } boolean onTouchEvent(MotionEvent event) { // Before delegation to gesture detector, handle ACTION_UP event // in order to release edge effect. if (event.getAction() == MotionEvent.ACTION_UP) { topEdgeEffect.onRelease(); bottomEdgeEffect.onRelease(); invalidate(); } if (gestureDetector.onTouchEvent(event)) { return true; } float scrolledX = event.getX() + getScrollX(); float scrolledY = event.getY() + getScrollY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: findCandidateAndPress(scrolledX, scrolledY); scroller.stopScrolling(); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); invalidate(); } if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); invalidate(); } return true; case MotionEvent.ACTION_MOVE: if (pressedCandidate != null) { // Turn off highlighting if contact point gets out of the candidate. if (!candidateRect.contains(scrolledX, scrolledY)) { reset(); invalidate(); } } return true; case MotionEvent.ACTION_CANCEL: if (pressedCandidate != null) { reset(); invalidate(); } return true; case MotionEvent.ACTION_UP: if (pressedCandidate != null) { if (candidateRect.contains(scrolledX, scrolledY) && candidateSelectListener != null) { candidateSelectListener.onCandidateSelected( CandidateWordView.this, pressedCandidate, pressedRowIndex); } reset(); invalidate(); } return true; } return false; } } /** Polymorphic behavior based on scroll orientation. */ // TODO(hidehiko): rename OrientationTrait to OrientationTraits. interface OrientationTrait { /** * @return scroll position of which direction corresponds to the orientation. */ int getScrollPosition(View view); /** * @return the projected value. */ float projectVector(float x, float y); /** Scrolls to {@code position}. {@code position} is applied to corresponding axis. */ void scrollTo(View view, int position); /** * @return left or top position based on the orientation. */ float getCandidatePosition(Row row, Span span); /** * @return width or height based on the orientation. */ float getCandidateLength(Row row, Span span); /** * @return view's width or height based on the orientation. */ int getViewLength(View view); /** * @return the page size of the layout for the scroll orientation. */ int getPageSize(CandidateLayouter layouter); /** * @return the content size for the scroll orientation of the layout. 0 for absent. */ float getContentSize(Optional<CandidateLayout> layout); } enum Orientation implements OrientationTrait { VERTICAL { @Override public int getScrollPosition(View view) { return view.getScrollY(); } @Override public void scrollTo(View view, int position) { view.scrollTo(0, position); } @Override public float getCandidatePosition(Row row, Span span) { return row.getTop(); } @Override public float getCandidateLength(Row row, Span span) { return row.getHeight(); } @Override public int getViewLength(View view) { return view.getHeight(); } @Override public float projectVector(float x, float y) { return y; } @Override public int getPageSize(CandidateLayouter layouter) { return Preconditions.checkNotNull(layouter).getPageHeight(); } @Override public float getContentSize(Optional<CandidateLayout> layout) { return layout.isPresent() ? layout.get().getContentHeight() : 0; } } } private CandidateSelectListener candidateSelectListener; // Finally, we only need vertical scrolling. // TODO(hidehiko): Remove horizontal scrolling related codes. private final EdgeEffect topEdgeEffect = new EdgeEffect(getContext()); private final EdgeEffect bottomEdgeEffect = new EdgeEffect(getContext()); // The Scroller which manages the status of scrolling the view. // Default behavior of ScrollView does not suffice our UX design // so we introduced this Scroller. // TODO(matsuzakit): The parameter is TBD (needs UX study?). protected final SnapScroller scroller = new SnapScroller(); // The CandidateLayouter which calculates the layout of candidate words. // This fields is not final but must be set in initialization in the subclasses. protected CandidateLayouter layouter; // The calculated layout, created by this.layouter. protected CandidateLayout calculatedLayout; // The CandidateList which is currently shown on the view. protected CandidateList currentCandidateList; protected final CandidateLayoutRenderer candidateLayoutRenderer = new CandidateLayoutRenderer(); final CandidateWordGestureDetector candidateWordGestureDetector = new CandidateWordGestureDetector(getContext()); // Scroll orientation. private final OrientationTrait orientationTrait; protected final BackgroundDrawableFactory backgroundDrawableFactory = new BackgroundDrawableFactory(getResources()); private DrawableType backgroundDrawableType = null; private final CandidateWindowAccessibilityDelegate accessibilityDelegate; private final AccessibilityManager accessibilityManager; CandidateWordView(Context context, OrientationTrait orientationFeature) { super(context); this.orientationTrait = orientationFeature; this.accessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE); } CandidateWordView(Context context, AttributeSet attributeSet, OrientationTrait orientationTrait) { super(context, attributeSet); this.orientationTrait = orientationTrait; this.accessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE); } CandidateWordView( Context context, AttributeSet attributeSet, int defaultStyle, OrientationTrait orientationTrait) { super(context, attributeSet, defaultStyle); this.orientationTrait = orientationTrait; this.accessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE); } { accessibilityDelegate = new CandidateWindowAccessibilityDelegate(this); ViewCompat.setAccessibilityDelegate(this, accessibilityDelegate); } void reset() { calculatedLayout = null; currentCandidateList = null; candidateWordGestureDetector.reset(); } void setCandidateSelectListener(CandidateSelectListener candidateSelectListener) { this.candidateSelectListener = candidateSelectListener; } CandidateLayouter getCandidateLayouter() { return layouter; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); int width = Math.max(right - left, 0); int height = bottom - top; if (layouter != null && layouter.setViewSize(width, height)) { updateCalculatedLayout(); } updateScroller(); } @Override public boolean onTouchEvent(MotionEvent event) { return candidateWordGestureDetector.onTouchEvent(event); } @Override public void draw(Canvas canvas) { super.draw(canvas); // Render edge effect. boolean postInvalidateIsNeeded = false; if (!topEdgeEffect.isFinished()) { int saveCount = canvas.save(); try { canvas.translate(0, Math.min(0, getScrollY())); topEdgeEffect.setSize(getWidth(), getHeight()); if (topEdgeEffect.draw(canvas)) { postInvalidateIsNeeded = true; } } finally { canvas.restoreToCount(saveCount); } } if (!bottomEdgeEffect.isFinished()) { int saveCount = canvas.save(); try { int width = getWidth(); int height = getHeight(); canvas.translate(-width, getScrollY() + height); canvas.rotate(180, width, 0); bottomEdgeEffect.setSize(width, height); if (bottomEdgeEffect.draw(canvas)) { postInvalidateIsNeeded = true; } } finally { canvas.restoreToCount(saveCount); } } if (postInvalidateIsNeeded) { ViewCompat.postInvalidateOnAnimation(this); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (calculatedLayout == null || currentCandidateList == null) { // No layout is available. return; } // Paint the candidates. int saveCount = canvas.save(); try { canvas.translate(0, 0); CandidateWord pressedCandidate = candidateWordGestureDetector.getPressedCandidate(); int pressedCandidateIndex = (pressedCandidate != null && pressedCandidate.hasIndex()) ? pressedCandidate.getIndex() : -1; candidateLayoutRenderer.drawCandidateLayout(canvas, calculatedLayout, pressedCandidateIndex); } finally { canvas.restoreToCount(saveCount); } } @Override public final void computeScroll() { if (scroller.isScrolling()) { // If still scrolling, update the scroll position and invalidate the window. Optional<Float> optionalVelocity = scroller.computeScrollOffset(); orientationTrait.scrollTo(this, scroller.getScrollPosition()); if (optionalVelocity.isPresent()) { float velocity = optionalVelocity.get(); // The end of scrolling. Check edge effect. if (velocity < 0) { topEdgeEffect.onAbsorb((int) velocity); if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); invalidate(); } } else if (velocity > 0) { bottomEdgeEffect.onAbsorb((int) velocity); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); invalidate(); } } } // This invalidation makes next scrolling. ViewCompat.postInvalidateOnAnimation(this); } super.computeScroll(); } private int getUpdatedScrollPosition(Row row, Span span) { int scrollPosition = orientationTrait.getScrollPosition(this); float candidatePosition = orientationTrait.getCandidatePosition(row, span); float candidateLength = orientationTrait.getCandidateLength(row, span); int viewLength = orientationTrait.getViewLength(this); if (candidatePosition < scrollPosition || candidatePosition + candidateLength > scrollPosition + viewLength) { return (int) candidatePosition; } else { return scrollPosition; } } /** * If focused candidate is invisible (including partial invisible), update scroll position to see * the candidate. */ protected void updateScrollPositionBasedOnFocusedIndex() { int scrollPosition = 0; if (calculatedLayout != null && currentCandidateList != null) { int focusedIndex = currentCandidateList.getFocusedIndex(); row_loop: for (Row row : calculatedLayout.getRowList()) { for (Span span : row.getSpanList()) { if (!span.getCandidateWord().isPresent()) { continue; } if (span.getCandidateWord().get().getIndex() == focusedIndex) { scrollPosition = getUpdatedScrollPosition(row, span); break row_loop; } } } } setScrollPosition(scrollPosition); } void setScrollPosition(int position) { scroller.scrollTo(position); orientationTrait.scrollTo(this, scroller.getScrollPosition()); invalidate(); } void update(CandidateList candidateList) { CandidateList previousCandidateList = currentCandidateList; currentCandidateList = candidateList; Optional<CandidateList> optionalCandidateList = Optional.fromNullable(candidateList); candidateLayoutRenderer.setCandidateList(optionalCandidateList); if (layouter != null && !equals(candidateList, previousCandidateList)) { updateCalculatedLayout(); } updateScroller(); invalidate(); } private static boolean equals(CandidateList list1, CandidateList list2) { if (list1 == list2) { return true; } if (list1 == null || list2 == null) { return false; } return list1.getCandidatesList().equals(list2.getCandidatesList()); } /** * Updates the layouter, and also updates the calculatedLayout based on the updated layouter. * * <p>TODO(hidehiko): This method is remaining here to reduce a CL size smaller in order to make * refactoring step by step. This will be cleaned when CandidateWordView is refactored. */ protected final void updateLayouter() { updateCalculatedLayout(); updateScroller(); } /** Updates the calculatedLayout if possible. */ private void updateCalculatedLayout() { if (currentCandidateList == null || layouter == null) { calculatedLayout = null; } else { calculatedLayout = layouter.layout(currentCandidateList).orNull(); } accessibilityDelegate.setCandidateLayout( calculatedLayout, (int) orientationTrait.getContentSize(Optional.fromNullable(calculatedLayout)), orientationTrait.getViewLength(this)); } private void updateScroller() { if (calculatedLayout == null || layouter == null) { scroller.setPageSize(0); scroller.setContentSize(0); } else { int pageSize = orientationTrait.getPageSize(layouter); int contentSize = (int) orientationTrait.getContentSize(Optional.fromNullable(calculatedLayout)); if (pageSize != 0) { // Ceil to align pages. contentSize = (contentSize + pageSize - 1) / pageSize * pageSize; } scroller.setPageSize(pageSize); scroller.setContentSize(contentSize); } scroller.setViewSize(orientationTrait.getViewLength(this)); } protected void setSpanBackgroundDrawableType(DrawableType drawableType) { backgroundDrawableType = drawableType; resetSpanBackground(); } private void resetSpanBackground() { Drawable drawable = (backgroundDrawableType != null) ? backgroundDrawableFactory.getDrawable(backgroundDrawableType) : null; candidateLayoutRenderer.setSpanBackgroundDrawable(Optional.fromNullable(drawable)); } /** Returns a Drawable which should be set as the view's background. */
protected abstract Drawable getViewBackgroundDrawable(Skin skin);
7
2023-10-25 07:33:25+00:00
24k
oghenevovwerho/yaa
src/main/java/yaa/semantic/handlers/MetaCallOp.java
[ { "identifier": "YaaToken", "path": "src/main/java/yaa/parser/YaaToken.java", "snippet": "public class YaaToken {\r\n public TkKind kind;\r\n public String content;\r\n public String neededContent;\r\n public int line;\r\n public int column;\r\n\r\n public YaaToken() {\r\n }\r\n\r\n public YaaTo...
import yaa.ast.*; import yaa.parser.YaaToken; import yaa.pojos.YaaClz; import yaa.pojos.YaaError; import yaa.pojos.YaaMeta; import yaa.semantic.passes.fs5.F5NewMeta; import java.lang.annotation.ElementType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static yaa.pojos.GlobalData.*; import static yaa.pojos.TypeCategory.enum_c;
14,612
package yaa.semantic.handlers; public class MetaCallOp { public static Map<String, YaaMeta> metaCalls(List<YaaMetaCall> calls, ElementType kindOfUsage) { var metas = new HashMap<String, YaaMeta>(calls.size()); var alreadyCalledMetas = new HashMap<String, YaaMetaCall>(1); for (var annotation : calls) { var meta = metaCall(annotation); if (!meta.allowedPlaces.contains(kindOfUsage) && !meta.allowedPlaces.isEmpty()) { throw new YaaError( annotation.placeOfUse(), meta.name + " cannot be used in " + kindOfUsage, "it can be used in " + meta.allowedPlaces ); } var defined_meta = alreadyCalledMetas.get(meta.name); if (defined_meta != null && !meta.isRepeatable) { throw new YaaError(annotation.placeOfUse(), meta.name + " has already been called at " + defined_meta.placeOfUse(), meta.name + " is not repeatable" ); } metas.put(annotation.name.content, meta); alreadyCalledMetas.put(meta.name, annotation); } return metas; } public static void metaCalls(ObjectType type, ElementType kindOfUsage) { metaCalls(type.metaCalls, kindOfUsage); if (type.hasInternalMeta) { for (var type_arg : type.arguments) { metaCalls(type_arg, ElementType.TYPE_USE); } } } private static YaaMeta metaCall(YaaMetaCall metaCall) { var call_name = metaCall.name.content; var gottenMeta = fs.getSymbol(call_name); if (gottenMeta instanceof YaaMeta meta) { if (meta.name.equals(configMetaClzName)) { return meta; } var given_keys = new HashMap<String, YaaToken>(metaCall.arguments.size()); for (var arg : metaCall.arguments.entrySet()) { var field_name = arg.getKey().content; if (given_keys.get(field_name) != null) { throw new YaaError( arg.getKey().placeOfUse(), field_name + " is already defined at " + given_keys.get(field_name).placeOfUse() ); } var value = arg.getValue().visit(fs); var required_field = meta.requiredFields.get(field_name); if (required_field == null) { var default_field = meta.defaultFields.get(field_name); if (default_field == null) { throw new YaaError( arg.getKey().placeOfUse(), field_name + " is not defined in " + meta.name, "the defined keys are, required: " + meta.requiredFields.keySet() + " and default: " + meta.defaultFields.keySet() ); } else { if (!value.name.equals(default_field.data.name)) { throw new YaaError( arg.getValue().placeOfUse(), default_field.data.name, value.name, "The value given to \"" + arg.getKey().content + "\" and the one declared must match" ); } else { if (value.name.equals(array$name)) {
package yaa.semantic.handlers; public class MetaCallOp { public static Map<String, YaaMeta> metaCalls(List<YaaMetaCall> calls, ElementType kindOfUsage) { var metas = new HashMap<String, YaaMeta>(calls.size()); var alreadyCalledMetas = new HashMap<String, YaaMetaCall>(1); for (var annotation : calls) { var meta = metaCall(annotation); if (!meta.allowedPlaces.contains(kindOfUsage) && !meta.allowedPlaces.isEmpty()) { throw new YaaError( annotation.placeOfUse(), meta.name + " cannot be used in " + kindOfUsage, "it can be used in " + meta.allowedPlaces ); } var defined_meta = alreadyCalledMetas.get(meta.name); if (defined_meta != null && !meta.isRepeatable) { throw new YaaError(annotation.placeOfUse(), meta.name + " has already been called at " + defined_meta.placeOfUse(), meta.name + " is not repeatable" ); } metas.put(annotation.name.content, meta); alreadyCalledMetas.put(meta.name, annotation); } return metas; } public static void metaCalls(ObjectType type, ElementType kindOfUsage) { metaCalls(type.metaCalls, kindOfUsage); if (type.hasInternalMeta) { for (var type_arg : type.arguments) { metaCalls(type_arg, ElementType.TYPE_USE); } } } private static YaaMeta metaCall(YaaMetaCall metaCall) { var call_name = metaCall.name.content; var gottenMeta = fs.getSymbol(call_name); if (gottenMeta instanceof YaaMeta meta) { if (meta.name.equals(configMetaClzName)) { return meta; } var given_keys = new HashMap<String, YaaToken>(metaCall.arguments.size()); for (var arg : metaCall.arguments.entrySet()) { var field_name = arg.getKey().content; if (given_keys.get(field_name) != null) { throw new YaaError( arg.getKey().placeOfUse(), field_name + " is already defined at " + given_keys.get(field_name).placeOfUse() ); } var value = arg.getValue().visit(fs); var required_field = meta.requiredFields.get(field_name); if (required_field == null) { var default_field = meta.defaultFields.get(field_name); if (default_field == null) { throw new YaaError( arg.getKey().placeOfUse(), field_name + " is not defined in " + meta.name, "the defined keys are, required: " + meta.requiredFields.keySet() + " and default: " + meta.defaultFields.keySet() ); } else { if (!value.name.equals(default_field.data.name)) { throw new YaaError( arg.getValue().placeOfUse(), default_field.data.name, value.name, "The value given to \"" + arg.getKey().content + "\" and the one declared must match" ); } else { if (value.name.equals(array$name)) {
var declared_array = (YaaClz) default_field.data;
1
2023-10-26 17:41:13+00:00
24k
unloggedio/intellij-java-plugin
src/main/java/com/insidious/plugin/pojo/MethodCallExpression.java
[ { "identifier": "ParameterNameFactory", "path": "src/main/java/com/insidious/plugin/client/ParameterNameFactory.java", "snippet": "public class ParameterNameFactory {\n\n private final Map<String, String> nameByIdMap = new HashMap<>();\n private final Map<String, Parameter> nameToParameterMap = ne...
import com.insidious.common.weaver.DataInfo; import com.insidious.common.weaver.EventType; import com.insidious.plugin.client.ParameterNameFactory; import com.insidious.plugin.client.pojo.DataEventWithSessionId; import com.insidious.plugin.factory.testcase.TestGenerationState; import com.insidious.plugin.factory.testcase.expression.Expression; import com.insidious.plugin.factory.testcase.parameter.VariableContainer; import com.insidious.plugin.util.ClassTypeUtils; import com.insidious.plugin.factory.testcase.writer.ObjectRoutineScript; import com.insidious.plugin.factory.testcase.writer.PendingStatement; import com.insidious.plugin.ui.TestCaseGenerationConfiguration; import com.insidious.plugin.util.LoggerUtil; import com.intellij.openapi.diagnostic.Logger; import org.objectweb.asm.Opcodes; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors;
17,479
package com.insidious.plugin.pojo; public class MethodCallExpression implements Expression, Serializable { private static final Logger logger = LoggerUtil.getInstance(MethodCallExpression.class); private int callStack; private List<Parameter> arguments; private String methodName; private boolean isStaticCall; private Parameter subject; private DataInfo entryProbeInfo; private Parameter returnValue; private DataEventWithSessionId entryProbe; private int methodAccess; private long id; private int threadId; private long parentId = -1; private List<DataEventWithSessionId> argumentProbes = new ArrayList<>(); private DataEventWithSessionId returnDataEvent; private boolean usesFields; private int methodDefinitionId; public MethodCallExpression() { } @Override public boolean equals(Object obj) { if (!(obj instanceof MethodCallExpression)) { return false; } MethodCallExpression mceObject = (MethodCallExpression) obj; return mceObject.id == this.id; } public MethodCallExpression( String methodName, Parameter subject, List<Parameter> arguments, Parameter returnValue, int callStack) { this.methodName = methodName; this.subject = subject; this.arguments = arguments; this.returnValue = returnValue; this.callStack = callStack; } public MethodCallExpression(MethodCallExpression original) { methodName = original.methodName; subject = new Parameter(original.subject); arguments = original.arguments.stream().map(Parameter::new).collect(Collectors.toList()); methodAccess = original.methodAccess; returnValue = new Parameter(original.returnValue); callStack = original.callStack; threadId = original.threadId; parentId = original.parentId; id = original.id; isStaticCall = original.isStaticCall; entryProbeInfo = original.entryProbeInfo; entryProbe = original.entryProbe; returnDataEvent = original.returnDataEvent; methodDefinitionId = original.methodDefinitionId; usesFields = original.usesFields; argumentProbes = original.argumentProbes; } public int getThreadId() { return threadId; } public void setThreadId(int threadId) { this.threadId = threadId; } public long getParentId() { return parentId; } public void setParentId(long parentId) { this.parentId = parentId; } public boolean getUsesFields() { return usesFields; } public void setUsesFields(boolean b) { this.usesFields = b; } public int getCallStack() { return callStack; } public void setCallStack(int callStack) { this.callStack = callStack; } public DataInfo getEntryProbeInfo() { return entryProbeInfo; } public void setEntryProbeInfo(DataInfo entryProbeInfo) { this.entryProbeInfo = entryProbeInfo; } public Parameter getSubject() { return subject; } public void setSubject(Parameter testSubject) { this.subject = testSubject; } public List<Parameter> getArguments() { return arguments; } public void setArguments(List<Parameter> arguments) { this.arguments = arguments; } public Parameter getReturnValue() { return returnValue; } public void setReturnValue(Parameter returnValue) { this.returnValue = returnValue; } public String getMethodName() { return methodName; } /* if the name is already used in the script and, if the parameter type and template map are not equal then Generates a New Name, */
package com.insidious.plugin.pojo; public class MethodCallExpression implements Expression, Serializable { private static final Logger logger = LoggerUtil.getInstance(MethodCallExpression.class); private int callStack; private List<Parameter> arguments; private String methodName; private boolean isStaticCall; private Parameter subject; private DataInfo entryProbeInfo; private Parameter returnValue; private DataEventWithSessionId entryProbe; private int methodAccess; private long id; private int threadId; private long parentId = -1; private List<DataEventWithSessionId> argumentProbes = new ArrayList<>(); private DataEventWithSessionId returnDataEvent; private boolean usesFields; private int methodDefinitionId; public MethodCallExpression() { } @Override public boolean equals(Object obj) { if (!(obj instanceof MethodCallExpression)) { return false; } MethodCallExpression mceObject = (MethodCallExpression) obj; return mceObject.id == this.id; } public MethodCallExpression( String methodName, Parameter subject, List<Parameter> arguments, Parameter returnValue, int callStack) { this.methodName = methodName; this.subject = subject; this.arguments = arguments; this.returnValue = returnValue; this.callStack = callStack; } public MethodCallExpression(MethodCallExpression original) { methodName = original.methodName; subject = new Parameter(original.subject); arguments = original.arguments.stream().map(Parameter::new).collect(Collectors.toList()); methodAccess = original.methodAccess; returnValue = new Parameter(original.returnValue); callStack = original.callStack; threadId = original.threadId; parentId = original.parentId; id = original.id; isStaticCall = original.isStaticCall; entryProbeInfo = original.entryProbeInfo; entryProbe = original.entryProbe; returnDataEvent = original.returnDataEvent; methodDefinitionId = original.methodDefinitionId; usesFields = original.usesFields; argumentProbes = original.argumentProbes; } public int getThreadId() { return threadId; } public void setThreadId(int threadId) { this.threadId = threadId; } public long getParentId() { return parentId; } public void setParentId(long parentId) { this.parentId = parentId; } public boolean getUsesFields() { return usesFields; } public void setUsesFields(boolean b) { this.usesFields = b; } public int getCallStack() { return callStack; } public void setCallStack(int callStack) { this.callStack = callStack; } public DataInfo getEntryProbeInfo() { return entryProbeInfo; } public void setEntryProbeInfo(DataInfo entryProbeInfo) { this.entryProbeInfo = entryProbeInfo; } public Parameter getSubject() { return subject; } public void setSubject(Parameter testSubject) { this.subject = testSubject; } public List<Parameter> getArguments() { return arguments; } public void setArguments(List<Parameter> arguments) { this.arguments = arguments; } public Parameter getReturnValue() { return returnValue; } public void setReturnValue(Parameter returnValue) { this.returnValue = returnValue; } public String getMethodName() { return methodName; } /* if the name is already used in the script and, if the parameter type and template map are not equal then Generates a New Name, */
public Parameter generateParameterName(Parameter parameter, ObjectRoutineScript ors) {
6
2023-10-31 09:07:46+00:00
24k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/api/item/IRPGItem.java
[ { "identifier": "ItemAttributes", "path": "src/main/java/mixac1/dangerrpg/capability/ItemAttributes.java", "snippet": "public abstract class ItemAttributes {\n\n public static final IALevel LEVEL = new IALevel(\"lvl\");\n public static final IACurrExp CURR_EXP = new IACurrExp(\"curr_exp\");\n p...
import mixac1.dangerrpg.capability.ItemAttributes; import mixac1.dangerrpg.capability.RPGItemHelper; import mixac1.dangerrpg.capability.data.RPGItemRegister.RPGItemData; import mixac1.dangerrpg.entity.projectile.EntityRPGArrow; import mixac1.dangerrpg.entity.projectile.core.EntityMaterial; import mixac1.dangerrpg.init.RPGOther; import mixac1.dangerrpg.item.RPGArmorMaterial; import mixac1.dangerrpg.item.RPGItemComponent; import mixac1.dangerrpg.item.RPGItemComponent.*; import mixac1.dangerrpg.item.RPGToolMaterial; import mixac1.dangerrpg.util.RPGHelper; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.*; import net.minecraft.world.World;
18,317
package mixac1.dangerrpg.api.item; /** * Implements this interface for creating RPGableItem */ public interface IRPGItem { public void registerAttributes(Item item, RPGItemData map); public interface IRPGItemMod extends IRPGItem {
package mixac1.dangerrpg.api.item; /** * Implements this interface for creating RPGableItem */ public interface IRPGItem { public void registerAttributes(Item item, RPGItemData map); public interface IRPGItemMod extends IRPGItem {
public RPGItemComponent getItemComponent(Item item);
8
2023-10-31 21:00:14+00:00
24k
llllllxy/tiny-jdbc-boot-starter
src/main/java/org/tinycloud/jdbc/support/AbstractSqlSupport.java
[ { "identifier": "Criteria", "path": "src/main/java/org/tinycloud/jdbc/criteria/Criteria.java", "snippet": "public class Criteria extends AbstractCriteria {\n\n public <R> Criteria lt(String field, R value) {\n String condition = \" AND \" + field + \" < \" + \"?\";\n conditions.add(cond...
import org.springframework.jdbc.core.*; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.tinycloud.jdbc.criteria.Criteria; import org.tinycloud.jdbc.criteria.LambdaCriteria; import org.tinycloud.jdbc.exception.JdbcException; import org.tinycloud.jdbc.page.IPageHandle; import org.tinycloud.jdbc.page.Page; import org.tinycloud.jdbc.sql.SqlGenerator; import org.tinycloud.jdbc.sql.SqlProvider; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.*;
14,776
package org.tinycloud.jdbc.support; /** * jdbc抽象类,给出默认的支持 * * @author liuxingyu01 * @since 2022-03-11-16:49 **/ public abstract class AbstractSqlSupport<T, ID> implements ISqlSupport<T, ID>, IObjectSupport<T, ID> { protected abstract JdbcTemplate getJdbcTemplate(); protected abstract IPageHandle getPageHandle(); /** * 泛型 */ private final Class<T> entityClass; /** * bean转换器 */ private final RowMapper<T> rowMapper; @SuppressWarnings("unchecked") public AbstractSqlSupport() { ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); entityClass = (Class<T>) type.getActualTypeArguments()[0]; rowMapper = BeanPropertyRowMapper.newInstance(entityClass); } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param params 要绑定到查询的参数 ,可以不传 * @return 查询结果 */ @Override public List<T> select(String sql, Object... params) { List<T> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, rowMapper); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, rowMapper); } return resultList; } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param clazz 实体类 * @param params 要绑定到查询的参数 ,可以不传 * @param <F> 泛型 * @return 查询结果 */ @Override public <F> List<F> select(String sql, Class<F> clazz, Object... params) { List<F> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, new BeanPropertyRowMapper<>(clazz)); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, new BeanPropertyRowMapper<>(clazz)); } return resultList; } /** * 执行查询sql,有查询条件,(固定返回List<Map<String, Object>>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public List<Map<String, Object>> selectMap(String sql, Object... params) { return getJdbcTemplate().queryForList(sql, params); } /** * 执行查询sql,有查询条件,结果返回第一条(固定返回Map<String, Object>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public Map<String, Object> selectOneMap(String sql, final Object... params) { List<Map<String, Object>> resultList = getJdbcTemplate().queryForList(sql, params); if (!CollectionUtils.isEmpty(resultList)) { return resultList.get(0); } return null; } /** * 查询一个值(经常用于查count) * * @param sql 要执行的SQL查询 * @param clazz 实体类 * @param params 要绑定到查询的参数 * @param <F> 泛型 * @return T */ @Override public <F> F selectOneColumn(String sql, Class<F> clazz, Object... params) { F result; if (params == null || params.length == 0) { result = getJdbcTemplate().queryForObject(sql, clazz); } else { result = getJdbcTemplate().queryForObject(sql, params, clazz); } return result; } /** * 分页查询 * * @param sql 要执行的SQL查询 * @param page 分页参数 * @return T */ @Override public Page<T> paginate(String sql, Page<T> page) { if (page == null || page.getPageNum() == null || page.getPageSize() == null) {
package org.tinycloud.jdbc.support; /** * jdbc抽象类,给出默认的支持 * * @author liuxingyu01 * @since 2022-03-11-16:49 **/ public abstract class AbstractSqlSupport<T, ID> implements ISqlSupport<T, ID>, IObjectSupport<T, ID> { protected abstract JdbcTemplate getJdbcTemplate(); protected abstract IPageHandle getPageHandle(); /** * 泛型 */ private final Class<T> entityClass; /** * bean转换器 */ private final RowMapper<T> rowMapper; @SuppressWarnings("unchecked") public AbstractSqlSupport() { ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); entityClass = (Class<T>) type.getActualTypeArguments()[0]; rowMapper = BeanPropertyRowMapper.newInstance(entityClass); } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param params 要绑定到查询的参数 ,可以不传 * @return 查询结果 */ @Override public List<T> select(String sql, Object... params) { List<T> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, rowMapper); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, rowMapper); } return resultList; } /** * 执行查询sql,有查询条件 * * @param sql 要执行的SQL * @param clazz 实体类 * @param params 要绑定到查询的参数 ,可以不传 * @param <F> 泛型 * @return 查询结果 */ @Override public <F> List<F> select(String sql, Class<F> clazz, Object... params) { List<F> resultList; if (params != null && params.length > 0) { resultList = getJdbcTemplate().query(sql, params, new BeanPropertyRowMapper<>(clazz)); } else { // BeanPropertyRowMapper是自动映射实体类的 resultList = getJdbcTemplate().query(sql, new BeanPropertyRowMapper<>(clazz)); } return resultList; } /** * 执行查询sql,有查询条件,(固定返回List<Map<String, Object>>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public List<Map<String, Object>> selectMap(String sql, Object... params) { return getJdbcTemplate().queryForList(sql, params); } /** * 执行查询sql,有查询条件,结果返回第一条(固定返回Map<String, Object>) * * @param sql 要执行的sql * @param params 要绑定到查询的参数 * @return Map<String, Object> */ @Override public Map<String, Object> selectOneMap(String sql, final Object... params) { List<Map<String, Object>> resultList = getJdbcTemplate().queryForList(sql, params); if (!CollectionUtils.isEmpty(resultList)) { return resultList.get(0); } return null; } /** * 查询一个值(经常用于查count) * * @param sql 要执行的SQL查询 * @param clazz 实体类 * @param params 要绑定到查询的参数 * @param <F> 泛型 * @return T */ @Override public <F> F selectOneColumn(String sql, Class<F> clazz, Object... params) { F result; if (params == null || params.length == 0) { result = getJdbcTemplate().queryForObject(sql, clazz); } else { result = getJdbcTemplate().queryForObject(sql, params, clazz); } return result; } /** * 分页查询 * * @param sql 要执行的SQL查询 * @param page 分页参数 * @return T */ @Override public Page<T> paginate(String sql, Page<T> page) { if (page == null || page.getPageNum() == null || page.getPageSize() == null) {
throw new JdbcException("paginate page cannot be null");
2
2023-10-25 14:44:59+00:00
24k
ansforge/SAMU-Hub-Modeles
src/main/java/com/hubsante/model/emsi/Resource.java
[ { "identifier": "Contact", "path": "src/main/java/com/hubsante/model/emsi/Contact.java", "snippet": "@JsonPropertyOrder(\n {Contact.JSON_PROPERTY_T_Y_P_E, Contact.JSON_PROPERTY_D_E_T_A_I_L})\n@JsonTypeName(\"contact\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class Contact {\n\n /**\n ...
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.dataformat.xml.annotation.*; import com.hubsante.model.emsi.Contact; import com.hubsante.model.emsi.Rgeo; import com.hubsante.model.emsi.Rtype; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Arrays; import java.util.List; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty;
20,274
PKG_DRM("PKG/DRM"), PKG_JERCAN("PKG/JERCAN"), PKG_PAK("PKG/PAK"), PKG_PAL("PKG/PAL"), PKG_RATION("PKG/RATION"), TIM_DAY("TIM/DAY"), TIM_HR("TIM/HR"), TIM_MINUTE("TIM/MINUTE"), TIM_MON("TIM/MON"), TIM_SECOND("TIM/SECOND"), TIM_WEK("TIM/WEK"), TIM_YEA("TIM/YEA"), WGT_CNTGRM("WGT/CNTGRM"), WGT_GRAM("WGT/GRAM"), WGT_KG("WGT/KG"), WGT_KGH("WGT/KGH"); private String value; UMEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static UMEnum fromValue(String value) { for (UMEnum b : UMEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_U_M = "UM"; private UMEnum UM; /** * Définit le statut de disponibilité d&#39;une ressource. - AVAILB : * Lorsqu&#39;une mission est terminée, une ressource redevient disponible - * RESRVD : Lorsque la ressource est réservée pour intervenir sur * l&#39;affaire mais pas encore engagée dans l&#39;opération. Par exemple : * un SMUR termine un autre transfert patient/victime avant de rejoindre une * autre intervention : il est alors RESRVD - IN_USE/MOBILE : à utiliser pour * les véhicules et le personnel lorsqu&#39;ils se déplaces - IN_USE/ON_SCENE * : à utiliser pour les véhicules et le personnel lorsqu&#39;ils sont sur les * lieux de l&#39;affaire */ public enum STATUSEnum { AVAILB("AVAILB"), UNAV("UNAV"), MAINTC("MAINTC"), RESRVD("RESRVD"), VIRTUAL("VIRTUAL"), IN_USE_MOBILE("IN_USE/MOBILE"), IN_USE_ON_SCENE("IN_USE/ON_SCENE"); private String value; STATUSEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static STATUSEnum fromValue(String value) { for (STATUSEnum b : STATUSEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_S_T_A_T_U_S = "STATUS"; private STATUSEnum STATUS; public static final String JSON_PROPERTY_N_A_T_I_O_N_A_L_I_T_Y = "NATIONALITY"; private String NATIONALITY; public static final String JSON_PROPERTY_C_O_N_T_A_C_T_S = "CONTACTS";
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.emsi; /** * Resource */ @JsonPropertyOrder( {Resource.JSON_PROPERTY_R_T_Y_P_E, Resource.JSON_PROPERTY_I_D, Resource.JSON_PROPERTY_O_R_G_I_D, Resource.JSON_PROPERTY_N_A_M_E, Resource.JSON_PROPERTY_F_R_E_E_T_E_X_T, Resource.JSON_PROPERTY_R_G_E_O, Resource.JSON_PROPERTY_Q_U_A_N_T_I_T_Y, Resource.JSON_PROPERTY_U_M, Resource.JSON_PROPERTY_S_T_A_T_U_S, Resource.JSON_PROPERTY_N_A_T_I_O_N_A_L_I_T_Y, Resource.JSON_PROPERTY_C_O_N_T_A_C_T_S}) @JsonTypeName("resource") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Resource { public static final String JSON_PROPERTY_R_T_Y_P_E = "RTYPE"; private Rtype RTYPE; public static final String JSON_PROPERTY_I_D = "ID"; private String ID; public static final String JSON_PROPERTY_O_R_G_I_D = "ORG_ID"; private String ORG_ID; public static final String JSON_PROPERTY_N_A_M_E = "NAME"; private String NAME; public static final String JSON_PROPERTY_F_R_E_E_T_E_X_T = "FREETEXT"; private String FREETEXT; public static final String JSON_PROPERTY_R_G_E_O = "RGEO"; private List<Rgeo> RGEO; public static final String JSON_PROPERTY_Q_U_A_N_T_I_T_Y = "QUANTITY"; private BigDecimal QUANTITY; /** * Dans le cadre d&#39;un échange d&#39;opération, optionnel. Unité de mesure * pour des ressources consommables */ public enum UMEnum { LSV("LSV"), OTH("OTH"), PKG("PKG"), TIM("TIM"), WGT("WGT"), LSV_CM("LSV/CM"), LSV_CMH("LSV/CMH"), LSV_CNTLTR("LSV/CNTLTR"), LSV_DEG("LSV/DEG"), LSV_HCTLTR("LSV/HCTLTR"), LSV_HCTMTR("LSV/HCTMTR"), LSV_KM("LSV/KM"), LSV_KPH("LSV/KPH"), LSV_LI("LSV/LI"), LSV_LTPRHR("LSV/LTPRHR"), LSV_LTPRMN("LSV/LTPRMN"), LSV_METRE("LSV/METRE"), LSV_MILLTR("LSV/MILLTR"), LSV_MILMTR("LSV/MILMTR"), LSV_SMH("LSV/SMH"), LSV_SQM("LSV/SQM"), OTH_COIL("OTH/COIL"), OTH_DOZEN("OTH/DOZEN"), OTH_EA("OTH/EA"), OTH_GROSS("OTH/GROSS"), OTH_MANHUR("OTH/MANHUR"), OTH_MHPRHR("OTH/MHPRHR"), PKG_BALE("PKG/BALE"), PKG_BARREL("PKG/BARREL"), PKG_BLK("PKG/BLK"), PKG_BOX("PKG/BOX"), PKG_CASE("PKG/CASE"), PKG_CONTNR("PKG/CONTNR"), PKG_CRATE("PKG/CRATE"), PKG_DRM("PKG/DRM"), PKG_JERCAN("PKG/JERCAN"), PKG_PAK("PKG/PAK"), PKG_PAL("PKG/PAL"), PKG_RATION("PKG/RATION"), TIM_DAY("TIM/DAY"), TIM_HR("TIM/HR"), TIM_MINUTE("TIM/MINUTE"), TIM_MON("TIM/MON"), TIM_SECOND("TIM/SECOND"), TIM_WEK("TIM/WEK"), TIM_YEA("TIM/YEA"), WGT_CNTGRM("WGT/CNTGRM"), WGT_GRAM("WGT/GRAM"), WGT_KG("WGT/KG"), WGT_KGH("WGT/KGH"); private String value; UMEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static UMEnum fromValue(String value) { for (UMEnum b : UMEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_U_M = "UM"; private UMEnum UM; /** * Définit le statut de disponibilité d&#39;une ressource. - AVAILB : * Lorsqu&#39;une mission est terminée, une ressource redevient disponible - * RESRVD : Lorsque la ressource est réservée pour intervenir sur * l&#39;affaire mais pas encore engagée dans l&#39;opération. Par exemple : * un SMUR termine un autre transfert patient/victime avant de rejoindre une * autre intervention : il est alors RESRVD - IN_USE/MOBILE : à utiliser pour * les véhicules et le personnel lorsqu&#39;ils se déplaces - IN_USE/ON_SCENE * : à utiliser pour les véhicules et le personnel lorsqu&#39;ils sont sur les * lieux de l&#39;affaire */ public enum STATUSEnum { AVAILB("AVAILB"), UNAV("UNAV"), MAINTC("MAINTC"), RESRVD("RESRVD"), VIRTUAL("VIRTUAL"), IN_USE_MOBILE("IN_USE/MOBILE"), IN_USE_ON_SCENE("IN_USE/ON_SCENE"); private String value; STATUSEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static STATUSEnum fromValue(String value) { for (STATUSEnum b : STATUSEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_S_T_A_T_U_S = "STATUS"; private STATUSEnum STATUS; public static final String JSON_PROPERTY_N_A_T_I_O_N_A_L_I_T_Y = "NATIONALITY"; private String NATIONALITY; public static final String JSON_PROPERTY_C_O_N_T_A_C_T_S = "CONTACTS";
private List<Contact> CONTACTS;
0
2023-10-25 14:24:31+00:00
24k
yaroslav318/shop-telegram-bot
telegram-bot/src/main/java/ua/ivanzaitsev/bot/Application.java
[ { "identifier": "ConfigReader", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/core/ConfigReader.java", "snippet": "public class ConfigReader {\n\n private static final ConfigReader INSTANCE = new ConfigReader();\n\n private final Properties properties;\n\n private ConfigReader() {\n ...
import java.util.ArrayList; import java.util.List; import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; import ua.ivanzaitsev.bot.core.ConfigReader; import ua.ivanzaitsev.bot.core.TelegramBot; import ua.ivanzaitsev.bot.handlers.ActionHandler; import ua.ivanzaitsev.bot.handlers.CommandHandler; import ua.ivanzaitsev.bot.handlers.UpdateHandler; import ua.ivanzaitsev.bot.handlers.commands.CartCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.CatalogCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderConfirmCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterAddressCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterCityCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterNameCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderEnterPhoneNumberCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderStepCancelCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.OrderStepPreviousCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.StartCommandHandler; import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistry; import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistryDefault; import ua.ivanzaitsev.bot.repositories.CartRepository; import ua.ivanzaitsev.bot.repositories.CategoryRepository; import ua.ivanzaitsev.bot.repositories.ClientActionRepository; import ua.ivanzaitsev.bot.repositories.ClientCommandStateRepository; import ua.ivanzaitsev.bot.repositories.ClientOrderStateRepository; import ua.ivanzaitsev.bot.repositories.ClientRepository; import ua.ivanzaitsev.bot.repositories.OrderRepository; import ua.ivanzaitsev.bot.repositories.ProductRepository; import ua.ivanzaitsev.bot.repositories.database.CategoryRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.ClientRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.OrderRepositoryDefault; import ua.ivanzaitsev.bot.repositories.database.ProductRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.CartRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientActionRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientCommandStateRepositoryDefault; import ua.ivanzaitsev.bot.repositories.memory.ClientOrderStateRepositoryDefault; import ua.ivanzaitsev.bot.services.MessageService; import ua.ivanzaitsev.bot.services.NotificationService; import ua.ivanzaitsev.bot.services.impl.MessageServiceDefault; import ua.ivanzaitsev.bot.services.impl.NotificationServiceDefault;
18,863
package ua.ivanzaitsev.bot; public class Application { private ConfigReader configReader = ConfigReader.getInstance(); private ClientActionRepository clientActionRepository; private ClientCommandStateRepository clientCommandStateRepository; private ClientOrderStateRepository clientOrderStateRepository; private CartRepository cartRepository; private CategoryRepository categoryRepository; private ProductRepository productRepository; private OrderRepository orderRepository; private ClientRepository clientRepository; private MessageService messageService; private NotificationService notificationService; private CommandHandlerRegistry commandHandlerRegistry; private List<CommandHandler> commandHandlers;
package ua.ivanzaitsev.bot; public class Application { private ConfigReader configReader = ConfigReader.getInstance(); private ClientActionRepository clientActionRepository; private ClientCommandStateRepository clientCommandStateRepository; private ClientOrderStateRepository clientOrderStateRepository; private CartRepository cartRepository; private CategoryRepository categoryRepository; private ProductRepository productRepository; private OrderRepository orderRepository; private ClientRepository clientRepository; private MessageService messageService; private NotificationService notificationService; private CommandHandlerRegistry commandHandlerRegistry; private List<CommandHandler> commandHandlers;
private List<UpdateHandler> updateHandlers;
4
2023-10-29 15:49:41+00:00
24k
LeoK99/swtw45WS21_reupload
src/main/java/com/buschmais/frontend/views/adrCreate/ADRRichCreateView.java
[ { "identifier": "Application", "path": "backup/java/com/buschmais/Application.java", "snippet": "@SpringBootApplication\n@Theme(value = \"adr-workbench\")\n@PWA(name = \"ADR-Workbench\", shortName = \"ADR-Workbench\", offlineResources = {\"images/logo.png\"})\n@NpmPackage(value = \"line-awesome\", versi...
import com.buschmais.Application; import com.buschmais.backend.adr.ADR; import com.buschmais.backend.adr.ADRTag; import com.buschmais.backend.adr.dataAccess.ADRDao; import com.buschmais.backend.adr.status.ADRStatusCreated; import com.buschmais.backend.users.dataAccess.UserDao; import com.buschmais.frontend.broadcasting.BroadcastListener; import com.buschmais.frontend.broadcasting.Broadcaster; import com.buschmais.frontend.components.*; import com.buschmais.frontend.vars.StringConstantsFrontend; import com.buschmais.frontend.views.adrVote.ADRVoteView; import com.vaadin.flow.component.Text; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.Header; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.Scroller; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.data.binder.Binder; import com.vaadin.flow.router.*; import org.springframework.beans.factory.annotation.Autowired; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream;
16,020
package com.buschmais.frontend.views.adrCreate; //@Route(value="ADREdit", layout = MainLayout.class) @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @PageTitle(StringConstantsFrontend.ADRCREATE_EDITADR) public class ADRRichCreateView extends VerticalLayout implements HasUrlParameter<String>, BeforeEnterObserver { //name of new ADR private final TextField name = new TextField(StringConstantsFrontend.ADRCREATE_NAME); //title of new ADR private final TextField title = new TextField(StringConstantsFrontend.ADRCREATE_TITLE); //context, decision and consequences of new ADR private final Label contextLabel = new Label(StringConstantsFrontend.ADRCREATE_CONTEXT); private final RichTextEditor context = new RichTextEditor(); private final Label decisionLabel = new Label(StringConstantsFrontend.ADRCREATE_DECISION); private final RichTextEditor decision = new RichTextEditor(); private final Label consequencesLabel = new Label(StringConstantsFrontend.ADRCREATE_CONSEQUENCES); private final RichTextEditor consequences = new RichTextEditor(); private final TextField id = new TextField(); private ErrorNotification errNot; private SuccessNotification succNot; //Scroller so that we can fit everything private Scroller scroller; //Contents of the Scroller private final VerticalLayout mainContent = new VerticalLayout(); //Title of the Scroller H2 editADR = new H2(); private final Header header = new Header(); private TagSelect tagSelect; private StringSelect supersededSelect; private final ADRDao adrDao; private final UserDao userDao;
package com.buschmais.frontend.views.adrCreate; //@Route(value="ADREdit", layout = MainLayout.class) @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @PageTitle(StringConstantsFrontend.ADRCREATE_EDITADR) public class ADRRichCreateView extends VerticalLayout implements HasUrlParameter<String>, BeforeEnterObserver { //name of new ADR private final TextField name = new TextField(StringConstantsFrontend.ADRCREATE_NAME); //title of new ADR private final TextField title = new TextField(StringConstantsFrontend.ADRCREATE_TITLE); //context, decision and consequences of new ADR private final Label contextLabel = new Label(StringConstantsFrontend.ADRCREATE_CONTEXT); private final RichTextEditor context = new RichTextEditor(); private final Label decisionLabel = new Label(StringConstantsFrontend.ADRCREATE_DECISION); private final RichTextEditor decision = new RichTextEditor(); private final Label consequencesLabel = new Label(StringConstantsFrontend.ADRCREATE_CONSEQUENCES); private final RichTextEditor consequences = new RichTextEditor(); private final TextField id = new TextField(); private ErrorNotification errNot; private SuccessNotification succNot; //Scroller so that we can fit everything private Scroller scroller; //Contents of the Scroller private final VerticalLayout mainContent = new VerticalLayout(); //Title of the Scroller H2 editADR = new H2(); private final Header header = new Header(); private TagSelect tagSelect; private StringSelect supersededSelect; private final ADRDao adrDao; private final UserDao userDao;
private ADR adr;
1
2023-10-25 15:18:06+00:00
24k
Java-Game-Engine-Merger/Libgdx-Processing
framework0001/framework0001-netty/src/main/java/l42111996/test/LatencySimulator.java
[ { "identifier": "Snmp", "path": "framework0001/framework0001-netty/src/main/java/com/backblaze/erasure/fec/Snmp.java", "snippet": "public class Snmp{\n // bytes sent from upper level\n public LongAdder BytesSent=new LongAdder();\n // bytes received to upper level\n public LongAdder BytesReceived=new...
import com.backblaze.erasure.fec.Snmp; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import l42111996.internal.CodecOutputList; import l42111996.kcp.IKcp; import l42111996.kcp.Kcp; import l42111996.kcp.KcpOutput; import java.util.Iterator; import java.util.LinkedList; import java.util.Random;
17,718
package l42111996.test; /** * Created by JinMiao * 2019-01-04. */ public class LatencySimulator{ private static long long2Uint(long n) { return n&0x00000000FFFFFFFFL; } private long current; /** * 丢包率 **/ private int lostrate; private int rttmin; private int rttmax; private LinkedList<DelayPacket> p12=new LinkedList(); private LinkedList<DelayPacket> p21=new LinkedList(); private Random r12=new Random(); private Random r21=new Random(); // lostrate: 往返一周丢包率的百分比,默认 10% // rttmin:rtt最小值,默认 60 // rttmax:rtt最大值,默认 125 //func (p *LatencySimulator)Init(int lostrate = 10, int rttmin = 60, int rttmax = 125, int nmax = 1000): public void init(int lostrate,int rttmin,int rttmax) { this.current=System.currentTimeMillis(); this.lostrate=lostrate/2; // 上面数据是往返丢包率,单程除以2 this.rttmin=rttmin/2; this.rttmax=rttmax/2; } // 发送数据 // peer - 端点0/1,从0发送,从1接收;从1发送从0接收 public int send(int peer,ByteBuf data) { int rnd; if(peer==0) { rnd=r12.nextInt(100); }else { rnd=r21.nextInt(100); } //println("!!!!!!!!!!!!!!!!!!!!", rnd, p.lostrate, peer) if(rnd<lostrate) { return 0; } DelayPacket pkt=new DelayPacket(); pkt.init(data); current=System.currentTimeMillis(); int delay=rttmin; if(rttmax>rttmin) { delay+=new Random().nextInt()%(rttmax-rttmin); } pkt.setTs(current+delay); if(peer==0) { p12.addLast(pkt); }else { p21.addLast(pkt); } return 1; } // 接收数据 public int recv(int peer,ByteBuf data) { DelayPacket pkt; if(peer==0) { if(p21.size()==0) { return -1; } pkt=p21.getFirst(); }else { if(p12.size()==0) { return -1; } pkt=p12.getFirst(); } current=System.currentTimeMillis(); if(current<pkt.getTs()) { return -2; } if(peer==0) { p21.removeFirst(); }else { p12.removeFirst(); } int maxsize=pkt.getPtr().readableBytes(); data.writeBytes(pkt.getPtr()); pkt.release(); return maxsize; } public static void main(String[] args) { LatencySimulator latencySimulator=new LatencySimulator(); try { //latencySimulator.test(0); //latencySimulator.test(1); latencySimulator.test(2); }catch(Throwable e) { e.printStackTrace(); } //latencySimulator.BenchmarkFlush(); } //测试flush性能 public void BenchmarkFlush() {
package l42111996.test; /** * Created by JinMiao * 2019-01-04. */ public class LatencySimulator{ private static long long2Uint(long n) { return n&0x00000000FFFFFFFFL; } private long current; /** * 丢包率 **/ private int lostrate; private int rttmin; private int rttmax; private LinkedList<DelayPacket> p12=new LinkedList(); private LinkedList<DelayPacket> p21=new LinkedList(); private Random r12=new Random(); private Random r21=new Random(); // lostrate: 往返一周丢包率的百分比,默认 10% // rttmin:rtt最小值,默认 60 // rttmax:rtt最大值,默认 125 //func (p *LatencySimulator)Init(int lostrate = 10, int rttmin = 60, int rttmax = 125, int nmax = 1000): public void init(int lostrate,int rttmin,int rttmax) { this.current=System.currentTimeMillis(); this.lostrate=lostrate/2; // 上面数据是往返丢包率,单程除以2 this.rttmin=rttmin/2; this.rttmax=rttmax/2; } // 发送数据 // peer - 端点0/1,从0发送,从1接收;从1发送从0接收 public int send(int peer,ByteBuf data) { int rnd; if(peer==0) { rnd=r12.nextInt(100); }else { rnd=r21.nextInt(100); } //println("!!!!!!!!!!!!!!!!!!!!", rnd, p.lostrate, peer) if(rnd<lostrate) { return 0; } DelayPacket pkt=new DelayPacket(); pkt.init(data); current=System.currentTimeMillis(); int delay=rttmin; if(rttmax>rttmin) { delay+=new Random().nextInt()%(rttmax-rttmin); } pkt.setTs(current+delay); if(peer==0) { p12.addLast(pkt); }else { p21.addLast(pkt); } return 1; } // 接收数据 public int recv(int peer,ByteBuf data) { DelayPacket pkt; if(peer==0) { if(p21.size()==0) { return -1; } pkt=p21.getFirst(); }else { if(p12.size()==0) { return -1; } pkt=p12.getFirst(); } current=System.currentTimeMillis(); if(current<pkt.getTs()) { return -2; } if(peer==0) { p21.removeFirst(); }else { p12.removeFirst(); } int maxsize=pkt.getPtr().readableBytes(); data.writeBytes(pkt.getPtr()); pkt.release(); return maxsize; } public static void main(String[] args) { LatencySimulator latencySimulator=new LatencySimulator(); try { //latencySimulator.test(0); //latencySimulator.test(1); latencySimulator.test(2); }catch(Throwable e) { e.printStackTrace(); } //latencySimulator.BenchmarkFlush(); } //测试flush性能 public void BenchmarkFlush() {
Kcp kcp=new Kcp(1,(data,kcp1)-> {});
3
2023-10-27 05:47:39+00:00
24k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/readPct/NuevaConsulta.java
[ { "identifier": "ApplicationContext", "path": "src/com/context/ApplicationContext.java", "snippet": "public class ApplicationContext {\r\n public static SesionUsuario sesionUsuario;\r\n public static LoadingApp loading = new LoadingApp();\r\n public static LoadingApplication loadingApplication ...
import com.context.ApplicationContext; import com.context.ChoosedPalette; import com.helper.ConsultasHelper; import com.model.ConsultaModel; import com.utils.Styles; import com.utils.Tools; import com.view.createPacient.NewContext; import static com.view.createPacient.NewContext.dateTimeFormatter; import static com.view.readPct.AgendaContext.validateCombo; import static com.view.readPct.AgendaContext.validateComplete; import static com.view.readPct.AgendaContext.validateHour; import java.time.LocalDateTime;
15,242
package com.view.readPct; /** * * @author Daniel Batres * @version 1.0.0 * @since 2/10/22 */ public class NuevaConsulta extends Styles { /** * Creates new form NuevaConsulta */ public NuevaConsulta() { initComponents(); styleMyComponentBaby(); } private ConsultaModel devolverDatos() { ConsultaModel consultaModel = new ConsultaModel(); consultaModel.setDiaDeConsulta(Integer.parseInt(textField1.getText())); consultaModel.setMesDeConsulta(Integer.parseInt(textField2.getText())); consultaModel.setAnnioDeConsulta(Integer.parseInt(textField3.getText())); consultaModel.setHoraDeConsulta(textField4.getText()); consultaModel.setConsultaRealizada(false); consultaModel.setTratamientoDeConsulta(tratamientoCombo.getSelectedItem().toString()); consultaModel.setDiaCreacion(LocalDateTime.now().getDayOfMonth()); consultaModel.setMesCreacion(LocalDateTime.now().getMonthValue()); consultaModel.setAnnioCreacion(LocalDateTime.now().getYear()); consultaModel.setHoraCreacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter)); consultaModel.setDiaModificacion(LocalDateTime.now().getDayOfMonth()); consultaModel.setMesModificacion(LocalDateTime.now().getMonthValue()); consultaModel.setAnnioModificacion(LocalDateTime.now().getYear()); consultaModel.setHoraModificacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter)); return consultaModel; } private void addItems() { tratamientoCombo.addItem("Elegir tratamiento"); tratamientoCombo.addItem("Odontolog\u00eda"); tratamientoCombo.addItem("Ortodoncia"); } @Override public void addTitlesAndSubtitles() { TITLES_AND_SUBTITLES.add(title1); TITLES_AND_SUBTITLES.add(title2); TITLES_AND_SUBTITLES.add(title3); TITLES_AND_SUBTITLES.add(title4); TITLES_AND_SUBTITLES.add(title5); TITLES_AND_SUBTITLES.add(title6); } @Override public void addPlainText() { PLAIN_TEXT.add(text1); } @Override public void addContainers() { CONTAINERS.add(container); CONTAINERS.add(container1); CONTAINERS.add(container2); CONTAINERS.add(container3); CONTAINERS.add(container5); } @Override public void addTextFields() { TEXTFIELDS.add(textField1); TEXTFIELDS.add(textField2); TEXTFIELDS.add(textField3); TEXTFIELDS.add(textField4); } @Override public void colorBasics() { paintAll(); paintOneContainer(saveButton, ChoosedPalette.getMidColor()); paintOneContainer(cancelButton, ChoosedPalette.getDarkColor()); cancel.setForeground(ChoosedPalette.getDarkColor()); } @Override public void initStyles(){ addItems(); informationIcon.setSize(50, 50);
package com.view.readPct; /** * * @author Daniel Batres * @version 1.0.0 * @since 2/10/22 */ public class NuevaConsulta extends Styles { /** * Creates new form NuevaConsulta */ public NuevaConsulta() { initComponents(); styleMyComponentBaby(); } private ConsultaModel devolverDatos() { ConsultaModel consultaModel = new ConsultaModel(); consultaModel.setDiaDeConsulta(Integer.parseInt(textField1.getText())); consultaModel.setMesDeConsulta(Integer.parseInt(textField2.getText())); consultaModel.setAnnioDeConsulta(Integer.parseInt(textField3.getText())); consultaModel.setHoraDeConsulta(textField4.getText()); consultaModel.setConsultaRealizada(false); consultaModel.setTratamientoDeConsulta(tratamientoCombo.getSelectedItem().toString()); consultaModel.setDiaCreacion(LocalDateTime.now().getDayOfMonth()); consultaModel.setMesCreacion(LocalDateTime.now().getMonthValue()); consultaModel.setAnnioCreacion(LocalDateTime.now().getYear()); consultaModel.setHoraCreacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter)); consultaModel.setDiaModificacion(LocalDateTime.now().getDayOfMonth()); consultaModel.setMesModificacion(LocalDateTime.now().getMonthValue()); consultaModel.setAnnioModificacion(LocalDateTime.now().getYear()); consultaModel.setHoraModificacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter)); return consultaModel; } private void addItems() { tratamientoCombo.addItem("Elegir tratamiento"); tratamientoCombo.addItem("Odontolog\u00eda"); tratamientoCombo.addItem("Ortodoncia"); } @Override public void addTitlesAndSubtitles() { TITLES_AND_SUBTITLES.add(title1); TITLES_AND_SUBTITLES.add(title2); TITLES_AND_SUBTITLES.add(title3); TITLES_AND_SUBTITLES.add(title4); TITLES_AND_SUBTITLES.add(title5); TITLES_AND_SUBTITLES.add(title6); } @Override public void addPlainText() { PLAIN_TEXT.add(text1); } @Override public void addContainers() { CONTAINERS.add(container); CONTAINERS.add(container1); CONTAINERS.add(container2); CONTAINERS.add(container3); CONTAINERS.add(container5); } @Override public void addTextFields() { TEXTFIELDS.add(textField1); TEXTFIELDS.add(textField2); TEXTFIELDS.add(textField3); TEXTFIELDS.add(textField4); } @Override public void colorBasics() { paintAll(); paintOneContainer(saveButton, ChoosedPalette.getMidColor()); paintOneContainer(cancelButton, ChoosedPalette.getDarkColor()); cancel.setForeground(ChoosedPalette.getDarkColor()); } @Override public void initStyles(){ addItems(); informationIcon.setSize(50, 50);
Tools.addMouseListenerIngresa(TEXTFIELDS);
5
2023-10-26 19:35:40+00:00
24k
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/ENTSOEHistoricalDataRetrieval.java
[ { "identifier": "CSVGenerator", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/CSVGenerator.java", "snippet": "public class CSVGenerator {\n\n private static final Logger LOGGER = LogManager.getLogger(CSVGenerator.class);\n \n private static record ColumnBlock(List<ColumnD...
import java.io.File; import java.io.IOException; import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import tech.inceptive.ai4czc.entsoedataretrieval.csv.CSVGenerator; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.CSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.GLDocumentCSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.PublicationDocCSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.UnavailabilityDocCSVTransformer; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalError; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.ENTSOEDataFetcher; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ColumnType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.GLMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.PublicationMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.UnavailabilityMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.tools.DateTimeDivider;
21,374
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license */ package tech.inceptive.ai4czc.entsoedataretrieval; /** * The class to fetch an dataset from entsoe. * * @author andres */ public class ENTSOEHistoricalDataRetrieval { private final Set<ColumnType> columnType; private ENTSOEDataFetcher fetcher; // not final for testing purpose private CSVGenerator csvGen; // not final for testing purpose private final String csvEscapeChar; private final String csvSeparator; // TODO : make the time granularity configurable? public ENTSOEHistoricalDataRetrieval(String authToken, Set<ColumnType> columnType, String csvEscapeChar, String csvSeparator, boolean useRequestCache) { this.columnType = columnType; this.fetcher = new ENTSOEDataFetcher(authToken, useRequestCache); this.csvEscapeChar = csvEscapeChar; this.csvSeparator = csvSeparator; this.csvGen = new CSVGenerator(csvSeparator, csvEscapeChar); } /** * Retrieves to a temporal file the dataset, on CSV format. * * @param startDate * @param endDate * @return */ public File fetchDataset(LocalDateTime startDate, LocalDateTime endDate, Duration timeStep, Set<Area> targetAreas, Area mainFlowsArea, Duration maxTimeDuration) { List<CSVTransformer> transformers = new ArrayList<>(columnType.size()); List<LocalDateTime> splits; if (Duration.ofDays(365).minus(maxTimeDuration).isNegative()) { throw new DataRetrievalError("Maximal duration can not be bigger than 365 days"); } if (columnType.contains(ColumnType.ACTUAL_LOAD)) { // split request depending on stard and end date splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchActualLoad(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.DAY_AHEAD_LOAD)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(24, ChronoUnit.HOURS)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchDayAheadLoadForecast(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.WEAK_AHEAD_LOAD)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(7, ChronoUnit.DAYS)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchWeekAheadLoadForecast(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.AGGREGATED_GENERATION_TYPE)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchAggregatedGenerationType(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.PHYSICAL_FLOW)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<PublicationMarketDocument> opt = fetcher.fetchPhysicalFlows(targetArea, mainFlowsArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new PublicationDocCSVTransformer(opt.get(), csvSeparator, csvEscapeChar)); } opt = fetcher.fetchPhysicalFlows(mainFlowsArea, targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new PublicationDocCSVTransformer(opt.get(), csvSeparator, csvEscapeChar)); } } } } if (columnType.contains(ColumnType.TRANSMISSION_OUTAGE)) { if (mainFlowsArea == null) { throw new DataRetrievalError("Please fix the main flows are when retriving data from transmission " + "outages (article 10.1.A&B)"); } splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { // TODO : check if we need to do both sides
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license */ package tech.inceptive.ai4czc.entsoedataretrieval; /** * The class to fetch an dataset from entsoe. * * @author andres */ public class ENTSOEHistoricalDataRetrieval { private final Set<ColumnType> columnType; private ENTSOEDataFetcher fetcher; // not final for testing purpose private CSVGenerator csvGen; // not final for testing purpose private final String csvEscapeChar; private final String csvSeparator; // TODO : make the time granularity configurable? public ENTSOEHistoricalDataRetrieval(String authToken, Set<ColumnType> columnType, String csvEscapeChar, String csvSeparator, boolean useRequestCache) { this.columnType = columnType; this.fetcher = new ENTSOEDataFetcher(authToken, useRequestCache); this.csvEscapeChar = csvEscapeChar; this.csvSeparator = csvSeparator; this.csvGen = new CSVGenerator(csvSeparator, csvEscapeChar); } /** * Retrieves to a temporal file the dataset, on CSV format. * * @param startDate * @param endDate * @return */ public File fetchDataset(LocalDateTime startDate, LocalDateTime endDate, Duration timeStep, Set<Area> targetAreas, Area mainFlowsArea, Duration maxTimeDuration) { List<CSVTransformer> transformers = new ArrayList<>(columnType.size()); List<LocalDateTime> splits; if (Duration.ofDays(365).minus(maxTimeDuration).isNegative()) { throw new DataRetrievalError("Maximal duration can not be bigger than 365 days"); } if (columnType.contains(ColumnType.ACTUAL_LOAD)) { // split request depending on stard and end date splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchActualLoad(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.DAY_AHEAD_LOAD)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(24, ChronoUnit.HOURS)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchDayAheadLoadForecast(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.WEAK_AHEAD_LOAD)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(7, ChronoUnit.DAYS)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchWeekAheadLoadForecast(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.AGGREGATED_GENERATION_TYPE)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<GLMarketDocument> opt = fetcher.fetchAggregatedGenerationType(targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get())); } } } } if (columnType.contains(ColumnType.PHYSICAL_FLOW)) { splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { Optional<PublicationMarketDocument> opt = fetcher.fetchPhysicalFlows(targetArea, mainFlowsArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new PublicationDocCSVTransformer(opt.get(), csvSeparator, csvEscapeChar)); } opt = fetcher.fetchPhysicalFlows(mainFlowsArea, targetArea, splits.get(i), splits.get(i + 1)); if (opt.isPresent()) { transformers.add(new PublicationDocCSVTransformer(opt.get(), csvSeparator, csvEscapeChar)); } } } } if (columnType.contains(ColumnType.TRANSMISSION_OUTAGE)) { if (mainFlowsArea == null) { throw new DataRetrievalError("Please fix the main flows are when retriving data from transmission " + "outages (article 10.1.A&B)"); } splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration, Duration.of(60, ChronoUnit.MINUTES)); for (int i = 0; i < splits.size() - 1; i++) { for (Area targetArea : targetAreas) { // TODO : check if we need to do both sides
List<UnavailabilityMarketDocument> outages = fetcher.fetchTransmissionGridOutages(mainFlowsArea, targetArea,
11
2023-10-30 09:09:53+00:00
24k
EricFan2002/SC2002
src/app/ui/camp/enquiriesview/OverlayCampInfoDisplayEnquiriesStaff.java
[ { "identifier": "CampEnquiryController", "path": "src/app/controller/camp/CampEnquiryController.java", "snippet": "public class CampEnquiryController {\n /**\n * Private constructor to prevent instantiation.\n */\n private CampEnquiryController() {\n }\n\n /*\n * Creates a new en...
import app.controller.camp.CampEnquiryController; import app.entity.RepositoryCollection; import app.entity.camp.Camp; import app.entity.enquiry.Enquiry; import app.entity.enquiry.EnquiryList; import app.entity.user.Staff; import app.ui.camp.infomationview.OverlayCampInfoDisplayView; import app.ui.overlayactions.OverlayChooseBox; import app.ui.overlayactions.OverlayTextInputAction; import app.ui.widgets.TEXT_ALIGNMENT; import app.ui.widgets.WidgetButton; import app.ui.widgets.WidgetLabel; import app.ui.widgets.WidgetPageSelection; import app.ui.windows.ICallBack; import app.ui.windows.Window; import java.util.ArrayList;
16,794
package app.ui.camp.enquiriesview; /** * OverlayCampInfoDisplayEnquiriesStaff extends OverlayCampInfoDisplayView and implements ICallBack. * Manages the display and interaction with camp enquiries within an overlay view for staff members. */ public class OverlayCampInfoDisplayEnquiriesStaff extends OverlayCampInfoDisplayView implements ICallBack { protected Staff staff; protected Window mainWindow; protected WidgetPageSelection participantsView; protected ArrayList<Enquiry> enquiryList; protected Enquiry selectedEnq; protected boolean replyEnq = false; public OverlayCampInfoDisplayEnquiriesStaff(int x, int y, int offsetY, int offsetX, String windowName, Camp camp, Staff staff, Window mainWindow) { super(x, y, offsetY, offsetX, windowName, camp); this.mainWindow = mainWindow; this.camp = camp; this.staff = staff; enquiryList = new ArrayList<>(); ArrayList<ArrayList<String>> enqList = new ArrayList<>(); EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp); for (Enquiry enquiry : enquires) { ArrayList<String> tmp = new ArrayList<String>(); enquiryList.add(enquiry); if(enquiry.getSender().equals(staff)) tmp.add("Question: " + enquiry.getQuestion() + " ( From You )"); else tmp.add("Question: " + enquiry.getQuestion() + " ( From " + enquiry.getSender().getName() + " )"); if (enquiry.getAnswer() == null || enquiry.getAnswer().equals("")) tmp.add(" Not Answer Yet. Our coordinators will answer soon."); else tmp.add(" : " + enquiry.getAnswer() + " ( Answered By " + enquiry.getAnsweredBy().getName() + ")"); enqList.add(tmp); } WidgetLabel labelParticipants = new WidgetLabel(3, 15, 34, "Reply Participant Enquires:",
package app.ui.camp.enquiriesview; /** * OverlayCampInfoDisplayEnquiriesStaff extends OverlayCampInfoDisplayView and implements ICallBack. * Manages the display and interaction with camp enquiries within an overlay view for staff members. */ public class OverlayCampInfoDisplayEnquiriesStaff extends OverlayCampInfoDisplayView implements ICallBack { protected Staff staff; protected Window mainWindow; protected WidgetPageSelection participantsView; protected ArrayList<Enquiry> enquiryList; protected Enquiry selectedEnq; protected boolean replyEnq = false; public OverlayCampInfoDisplayEnquiriesStaff(int x, int y, int offsetY, int offsetX, String windowName, Camp camp, Staff staff, Window mainWindow) { super(x, y, offsetY, offsetX, windowName, camp); this.mainWindow = mainWindow; this.camp = camp; this.staff = staff; enquiryList = new ArrayList<>(); ArrayList<ArrayList<String>> enqList = new ArrayList<>(); EnquiryList enquires = RepositoryCollection.getEnquiryRepository().filterByCamp(camp); for (Enquiry enquiry : enquires) { ArrayList<String> tmp = new ArrayList<String>(); enquiryList.add(enquiry); if(enquiry.getSender().equals(staff)) tmp.add("Question: " + enquiry.getQuestion() + " ( From You )"); else tmp.add("Question: " + enquiry.getQuestion() + " ( From " + enquiry.getSender().getName() + " )"); if (enquiry.getAnswer() == null || enquiry.getAnswer().equals("")) tmp.add(" Not Answer Yet. Our coordinators will answer soon."); else tmp.add(" : " + enquiry.getAnswer() + " ( Answered By " + enquiry.getAnsweredBy().getName() + ")"); enqList.add(tmp); } WidgetLabel labelParticipants = new WidgetLabel(3, 15, 34, "Reply Participant Enquires:",
TEXT_ALIGNMENT.ALIGN_RIGHT);
9
2023-11-01 05:18:29+00:00
24k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/entity/BMDEntities.java
[ { "identifier": "PauseAnimationTimer", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/animation/PauseAnimationTimer.java", "snippet": "public class PauseAnimationTimer implements IAnimationTimer {\n private final Supplier<Double> sysTimeProvider;\n private final Supplier<Boolean> isP...
import com.cerbon.bosses_of_mass_destruction.animation.PauseAnimationTimer; import com.cerbon.bosses_of_mass_destruction.client.render.*; import com.cerbon.bosses_of_mass_destruction.config.BMDConfig; import com.cerbon.bosses_of_mass_destruction.entity.custom.gauntlet.*; import com.cerbon.bosses_of_mass_destruction.entity.custom.lich.*; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithArmorRenderer; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithBoneLight; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithEntity; import com.cerbon.bosses_of_mass_destruction.entity.custom.void_blossom.*; import com.cerbon.bosses_of_mass_destruction.entity.util.SimpleLivingGeoRenderer; import com.cerbon.bosses_of_mass_destruction.item.custom.ChargedEnderPearlEntity; import com.cerbon.bosses_of_mass_destruction.item.custom.SoulStarEntity; import com.cerbon.bosses_of_mass_destruction.particle.BMDParticles; import com.cerbon.bosses_of_mass_destruction.particle.ParticleFactories; import com.cerbon.bosses_of_mass_destruction.projectile.MagicMissileProjectile; import com.cerbon.bosses_of_mass_destruction.projectile.PetalBladeProjectile; import com.cerbon.bosses_of_mass_destruction.projectile.SporeBallProjectile; import com.cerbon.bosses_of_mass_destruction.projectile.comet.CometCodeAnimations; import com.cerbon.bosses_of_mass_destruction.projectile.comet.CometProjectile; import com.cerbon.bosses_of_mass_destruction.util.BMDConstants; import com.cerbon.cerbons_api.api.general.data.WeakHashPredicate; import com.cerbon.cerbons_api.api.general.particle.ClientParticleBuilder; import com.cerbon.cerbons_api.api.static_utilities.RandomUtils; import com.cerbon.cerbons_api.api.static_utilities.Vec3Colors; import com.cerbon.cerbons_api.api.static_utilities.VecUtils; import com.mojang.blaze3d.Blaze3D; import me.shedaniel.autoconfig.AutoConfig; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.EntityRenderers; import net.minecraft.client.renderer.entity.ThrownItemRenderer; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.phys.Vec3; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.event.entity.EntityAttributeCreationEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject;
19,048
.build(new ResourceLocation(BMDConstants.MOD_ID, "charged_ender_pearl").toString())); public static final RegistryObject<EntityType<ObsidilithEntity>> OBSIDILITH = ENTITY_TYPES.register("obsidilith", () -> EntityType.Builder.<ObsidilithEntity>of((entityType, level) -> new ObsidilithEntity(entityType, level, mobConfig.obsidilithConfig), MobCategory.MONSTER) .sized(2.0f, 4.4f) .fireImmune() .build(new ResourceLocation(BMDConstants.MOD_ID, "obsidilith").toString())); public static final RegistryObject<EntityType<GauntletEntity>> GAUNTLET = ENTITY_TYPES.register("gauntlet", () -> EntityType.Builder.<GauntletEntity>of((entityType, level) -> new GauntletEntity(entityType, level, mobConfig.gauntletConfig) , MobCategory.MONSTER) .sized(5.0f, 4.0f) .fireImmune() .build(new ResourceLocation(BMDConstants.MOD_ID, "gauntlet").toString())); public static final RegistryObject<EntityType<VoidBlossomEntity>> VOID_BLOSSOM = ENTITY_TYPES.register("void_blossom", () -> EntityType.Builder.<VoidBlossomEntity>of((entityType, level) -> new VoidBlossomEntity(entityType, level, mobConfig.voidBlossomConfig), MobCategory.MONSTER) .sized(8.0f, 10.0f) .fireImmune() .setTrackingRange(3) .build(new ResourceLocation(BMDConstants.MOD_ID, "void_blossom").toString())); public static final RegistryObject<EntityType<SporeBallProjectile>> SPORE_BALL = ENTITY_TYPES.register("spore_ball", () -> EntityType.Builder.<SporeBallProjectile>of(SporeBallProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "spore_ball").toString())); public static final RegistryObject<EntityType<PetalBladeProjectile>> PETAL_BLADE = ENTITY_TYPES.register("petal_blade", () -> EntityType.Builder.<PetalBladeProjectile>of(PetalBladeProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "petal_blade").toString())); public static final LichKillCounter killCounter = new LichKillCounter(mobConfig.lichConfig.summonMechanic); public static void createAttributes(EntityAttributeCreationEvent event){ event.put(BMDEntities.LICH.get(), Mob.createMobAttributes() .add(Attributes.FLYING_SPEED, 5.0) .add(Attributes.MAX_HEALTH, BMDEntities.mobConfig.lichConfig.health) .add(Attributes.FOLLOW_RANGE, 64) .add(Attributes.ATTACK_DAMAGE, BMDEntities.mobConfig.lichConfig.missile.damage) .build()); event.put(BMDEntities.OBSIDILITH.get(), Mob.createMobAttributes() .add(Attributes.MAX_HEALTH, mobConfig.obsidilithConfig.health) .add(Attributes.FOLLOW_RANGE, 32) .add(Attributes.ATTACK_DAMAGE, mobConfig.obsidilithConfig.attack) .add(Attributes.KNOCKBACK_RESISTANCE, 10) .add(Attributes.ARMOR, mobConfig.obsidilithConfig.armor) .build()); event.put(BMDEntities.GAUNTLET.get(), Mob.createMobAttributes() .add(Attributes.FLYING_SPEED, 4.0) .add(Attributes.FOLLOW_RANGE, 48.0) .add(Attributes.MAX_HEALTH, mobConfig.gauntletConfig.health) .add(Attributes.KNOCKBACK_RESISTANCE, 10) .add(Attributes.ATTACK_DAMAGE, mobConfig.gauntletConfig.attack) .add(Attributes.ARMOR, mobConfig.gauntletConfig.armor) .build()); event.put(BMDEntities.VOID_BLOSSOM.get(), Mob.createMobAttributes() .add(Attributes.MAX_HEALTH, mobConfig.voidBlossomConfig.health) .add(Attributes.FOLLOW_RANGE, 32) .add(Attributes.ATTACK_DAMAGE, mobConfig.voidBlossomConfig.attack) .add(Attributes.KNOCKBACK_RESISTANCE, 10.0) .add(Attributes.ARMOR, mobConfig.voidBlossomConfig.armor) .build()); } @OnlyIn(Dist.CLIENT) public static void initClient(){ PauseAnimationTimer pauseSecondTimer = new PauseAnimationTimer(Blaze3D::getTime, () -> Minecraft.getInstance().isPaused()); EntityRenderers.register(LICH.get(), context -> { ResourceLocation texture = new ResourceLocation(BMDConstants.MOD_ID, "textures/entity/lich.png"); return new SimpleLivingGeoRenderer<>( context, new GeoModel<>( lichEntity -> new ResourceLocation(BMDConstants.MOD_ID, "geo/lich.geo.json"), entity -> texture, new ResourceLocation(BMDConstants.MOD_ID, "animations/lich.animation.json"), new LichCodeAnimations(), RenderType::entityCutoutNoCull ), new BoundedLighting<>(5), new LichBoneLight(), new EternalNightRenderer(), null, null, true ); }); EntityRenderers.register(OBSIDILITH.get(), context -> { ObsidilithBoneLight runeColorHandler = new ObsidilithBoneLight(); GeoModel<ObsidilithEntity> modelProvider = new GeoModel<>( entity -> new ResourceLocation(BMDConstants.MOD_ID, "geo/obsidilith.geo.json"), entity -> new ResourceLocation(BMDConstants.MOD_ID, "textures/entity/obsidilith.png"), new ResourceLocation(BMDConstants.MOD_ID, "animations/obsidilith.animation.json"), (animatable, data, geoModel) -> {}, RenderType::entityCutout ); ObsidilithArmorRenderer armorRenderer = new ObsidilithArmorRenderer(modelProvider, context); return new SimpleLivingGeoRenderer<>( context, modelProvider, null, runeColorHandler, new CompositeRenderer<>(armorRenderer, runeColorHandler), armorRenderer, null, false ); }); EntityRenderers.register(COMET.get(), context -> new SimpleLivingGeoRenderer<>( context, new GeoModel<>( geoAnimatable -> new ResourceLocation(BMDConstants.MOD_ID, "geo/comet.geo.json"), entity -> new ResourceLocation(BMDConstants.MOD_ID, "textures/entity/comet.png"), new ResourceLocation(BMDConstants.MOD_ID, "animations/comet.animation.json"),
package com.cerbon.bosses_of_mass_destruction.entity; public class BMDEntities { public static final BMDConfig mobConfig = AutoConfig.getConfigHolder(BMDConfig.class).getConfig(); public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, BMDConstants.MOD_ID); public static final RegistryObject<EntityType<LichEntity>> LICH = ENTITY_TYPES.register("lich", () -> EntityType.Builder.<LichEntity>of((entityType, level) -> new LichEntity(entityType, level, mobConfig.lichConfig), MobCategory.MONSTER) .sized(1.8f, 3.0f) .updateInterval(1) .build(new ResourceLocation(BMDConstants.MOD_ID, "lich").toString())); public static final RegistryObject<EntityType<MagicMissileProjectile>> MAGIC_MISSILE = ENTITY_TYPES.register("blue_fireball", () -> EntityType.Builder.<MagicMissileProjectile>of(MagicMissileProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "blue_fireball").toString())); public static final RegistryObject<EntityType<CometProjectile>> COMET = ENTITY_TYPES.register("comet", () -> EntityType.Builder.<CometProjectile>of(CometProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "comet").toString())); public static final RegistryObject<EntityType<SoulStarEntity>> SOUL_STAR = ENTITY_TYPES.register("soul_star", () -> EntityType.Builder.<SoulStarEntity>of(SoulStarEntity::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "soul_star").toString())); public static final RegistryObject<EntityType<ChargedEnderPearlEntity>> CHARGED_ENDER_PEARL = ENTITY_TYPES.register("charged_ender_pearl", () -> EntityType.Builder.of(ChargedEnderPearlEntity::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "charged_ender_pearl").toString())); public static final RegistryObject<EntityType<ObsidilithEntity>> OBSIDILITH = ENTITY_TYPES.register("obsidilith", () -> EntityType.Builder.<ObsidilithEntity>of((entityType, level) -> new ObsidilithEntity(entityType, level, mobConfig.obsidilithConfig), MobCategory.MONSTER) .sized(2.0f, 4.4f) .fireImmune() .build(new ResourceLocation(BMDConstants.MOD_ID, "obsidilith").toString())); public static final RegistryObject<EntityType<GauntletEntity>> GAUNTLET = ENTITY_TYPES.register("gauntlet", () -> EntityType.Builder.<GauntletEntity>of((entityType, level) -> new GauntletEntity(entityType, level, mobConfig.gauntletConfig) , MobCategory.MONSTER) .sized(5.0f, 4.0f) .fireImmune() .build(new ResourceLocation(BMDConstants.MOD_ID, "gauntlet").toString())); public static final RegistryObject<EntityType<VoidBlossomEntity>> VOID_BLOSSOM = ENTITY_TYPES.register("void_blossom", () -> EntityType.Builder.<VoidBlossomEntity>of((entityType, level) -> new VoidBlossomEntity(entityType, level, mobConfig.voidBlossomConfig), MobCategory.MONSTER) .sized(8.0f, 10.0f) .fireImmune() .setTrackingRange(3) .build(new ResourceLocation(BMDConstants.MOD_ID, "void_blossom").toString())); public static final RegistryObject<EntityType<SporeBallProjectile>> SPORE_BALL = ENTITY_TYPES.register("spore_ball", () -> EntityType.Builder.<SporeBallProjectile>of(SporeBallProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "spore_ball").toString())); public static final RegistryObject<EntityType<PetalBladeProjectile>> PETAL_BLADE = ENTITY_TYPES.register("petal_blade", () -> EntityType.Builder.<PetalBladeProjectile>of(PetalBladeProjectile::new, MobCategory.MISC) .sized(0.25f, 0.25f) .build(new ResourceLocation(BMDConstants.MOD_ID, "petal_blade").toString())); public static final LichKillCounter killCounter = new LichKillCounter(mobConfig.lichConfig.summonMechanic); public static void createAttributes(EntityAttributeCreationEvent event){ event.put(BMDEntities.LICH.get(), Mob.createMobAttributes() .add(Attributes.FLYING_SPEED, 5.0) .add(Attributes.MAX_HEALTH, BMDEntities.mobConfig.lichConfig.health) .add(Attributes.FOLLOW_RANGE, 64) .add(Attributes.ATTACK_DAMAGE, BMDEntities.mobConfig.lichConfig.missile.damage) .build()); event.put(BMDEntities.OBSIDILITH.get(), Mob.createMobAttributes() .add(Attributes.MAX_HEALTH, mobConfig.obsidilithConfig.health) .add(Attributes.FOLLOW_RANGE, 32) .add(Attributes.ATTACK_DAMAGE, mobConfig.obsidilithConfig.attack) .add(Attributes.KNOCKBACK_RESISTANCE, 10) .add(Attributes.ARMOR, mobConfig.obsidilithConfig.armor) .build()); event.put(BMDEntities.GAUNTLET.get(), Mob.createMobAttributes() .add(Attributes.FLYING_SPEED, 4.0) .add(Attributes.FOLLOW_RANGE, 48.0) .add(Attributes.MAX_HEALTH, mobConfig.gauntletConfig.health) .add(Attributes.KNOCKBACK_RESISTANCE, 10) .add(Attributes.ATTACK_DAMAGE, mobConfig.gauntletConfig.attack) .add(Attributes.ARMOR, mobConfig.gauntletConfig.armor) .build()); event.put(BMDEntities.VOID_BLOSSOM.get(), Mob.createMobAttributes() .add(Attributes.MAX_HEALTH, mobConfig.voidBlossomConfig.health) .add(Attributes.FOLLOW_RANGE, 32) .add(Attributes.ATTACK_DAMAGE, mobConfig.voidBlossomConfig.attack) .add(Attributes.KNOCKBACK_RESISTANCE, 10.0) .add(Attributes.ARMOR, mobConfig.voidBlossomConfig.armor) .build()); } @OnlyIn(Dist.CLIENT) public static void initClient(){ PauseAnimationTimer pauseSecondTimer = new PauseAnimationTimer(Blaze3D::getTime, () -> Minecraft.getInstance().isPaused()); EntityRenderers.register(LICH.get(), context -> { ResourceLocation texture = new ResourceLocation(BMDConstants.MOD_ID, "textures/entity/lich.png"); return new SimpleLivingGeoRenderer<>( context, new GeoModel<>( lichEntity -> new ResourceLocation(BMDConstants.MOD_ID, "geo/lich.geo.json"), entity -> texture, new ResourceLocation(BMDConstants.MOD_ID, "animations/lich.animation.json"), new LichCodeAnimations(), RenderType::entityCutoutNoCull ), new BoundedLighting<>(5), new LichBoneLight(), new EternalNightRenderer(), null, null, true ); }); EntityRenderers.register(OBSIDILITH.get(), context -> { ObsidilithBoneLight runeColorHandler = new ObsidilithBoneLight(); GeoModel<ObsidilithEntity> modelProvider = new GeoModel<>( entity -> new ResourceLocation(BMDConstants.MOD_ID, "geo/obsidilith.geo.json"), entity -> new ResourceLocation(BMDConstants.MOD_ID, "textures/entity/obsidilith.png"), new ResourceLocation(BMDConstants.MOD_ID, "animations/obsidilith.animation.json"), (animatable, data, geoModel) -> {}, RenderType::entityCutout ); ObsidilithArmorRenderer armorRenderer = new ObsidilithArmorRenderer(modelProvider, context); return new SimpleLivingGeoRenderer<>( context, modelProvider, null, runeColorHandler, new CompositeRenderer<>(armorRenderer, runeColorHandler), armorRenderer, null, false ); }); EntityRenderers.register(COMET.get(), context -> new SimpleLivingGeoRenderer<>( context, new GeoModel<>( geoAnimatable -> new ResourceLocation(BMDConstants.MOD_ID, "geo/comet.geo.json"), entity -> new ResourceLocation(BMDConstants.MOD_ID, "textures/entity/comet.png"), new ResourceLocation(BMDConstants.MOD_ID, "animations/comet.animation.json"),
new CometCodeAnimations(),
13
2023-10-25 16:28:17+00:00
24k
sinch/sinch-sdk-java
openapi-contracts/src/main/com/sinch/sdk/domains/verification/adapters/api/v1/SendingAndReportingVerificationsApi.java
[ { "identifier": "ApiException", "path": "core/src/main/com/sinch/sdk/core/exceptions/ApiException.java", "snippet": "public class ApiException extends RuntimeException {\n\n private static final long serialVersionUID = -1L;\n private int code = 0;\n\n public ApiException() {}\n\n public ApiException...
import com.fasterxml.jackson.core.type.TypeReference; import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.core.exceptions.ApiExceptionBuilder; import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.core.http.HttpMapper; import com.sinch.sdk.core.http.HttpMethod; import com.sinch.sdk.core.http.HttpRequest; import com.sinch.sdk.core.http.HttpResponse; import com.sinch.sdk.core.http.HttpStatus; import com.sinch.sdk.core.http.URLParameter; import com.sinch.sdk.core.http.URLPathUtils; import com.sinch.sdk.core.models.ServerConfiguration; import com.sinch.sdk.domains.verification.models.dto.v1.InitiateVerificationResourceDto; import com.sinch.sdk.domains.verification.models.dto.v1.InitiateVerificationResponseDto; import com.sinch.sdk.domains.verification.models.dto.v1.VerificationReportRequestResourceDto; import com.sinch.sdk.domains.verification.models.dto.v1.VerificationResponseDto; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger;
18,419
/* * Verification * Verification REST API for verifying phone numbers and users. Support of FlashCall verification, PIN SMS verification and Callout verification. **Note:** OTP CODE must be the full valid E.164 number that we called from. ## Overview For general information on how to use the Sinch APIs including methods, types, errors and authorization, please check the [Using REST](doc:using-rest) page. Use the Sinch Verification Service to verify end-user's mobile phone numbers. The Sinch Verification APIs should be used in combination with the Verification SDKs for a complete end-to-end solution, though it is possible to only use the APIs. Currently, there are three verification methods supported: - FlashCall verification - Android only - PIN SMS verification - iOS, Android, Javascript - Callout verification (voice call) - iOS only - Data verification (distinguished by method = `seamless`) - iOS, Android #### FlashCall verification With the flashCall verification method, a user's phone number is verified by triggering a \"missed call\" towards this number. The call is intercepted by the Android SDK in the mobile app and blocked automatically. To initiate a flashCall verification, check the [Android SDK documentation](doc:verification-android-the-verification-process#flash-call-verification). For additional security, it is recommended that you control which verification requests should proceed and which ones not, by listening in your backend for the [Verification Request Event](doc:verification-rest-verification-api#verification-request) and respond accordingly. Your backend will be notified on the result of the verification with the [Verification Result Event](doc:verification-rest-callback-api#verification-result-event). #### PIN SMS verification With the PIN SMS verification method, a user's phone number is verified by sending an SMS containing a PIN code to this number. In the case of iOS or Javascript, the user needs to enter the PIN manually in the app, while for Android there is an option of intercepting the SMS message delivery and capturing the PIN code automatically. To initiate a PIN SMS verification, check the [iOS](doc:verification-ios-sms-verification), [Android](doc:verification-for-android) and [Javascript](doc:verification-for-javascript) documentation. For additional security, it is recommended that you control which verification requests should proceed and which ones not, by listening in your backend for the [Verification Request Event](doc:verification-rest-verification-api#verification-request) and respond accordingly. Your backend will be notified on the result of the verification with the [Verification Result Event](doc:verification-rest-callback-api#verification-result-event). #### Callout verification With the callout verification method, a user's phone number is verified by receiving a phone call and hearing a pre-recorded or text-to-speech message, advising the user to press a digit code. When the user presses the digit code in the dialpad, the verification is successful. To initiate a callout verification, check the [iOS documentation](doc:verification-ios-callout-verification). For additional security, it is recommended that you control which verification requests should proceed and which ones not, by listening in your backend for the [Verification Request Event](doc:verification-rest-verification-api#verification-request) and respond accordingly. Your backend will be notified on the result of the verification with the [Verification Result Event](doc:verification-rest-callback-api#verification-result-event). #### Data verification With the data verification method, a user's phone number is verified by carrier using mobile data network. For additional security, it is recommended that you control which verification requests should proceed and which ones not, by listening in your backend for the [Verification Request Event](doc:verification-rest-verification-api#verification-request) and respond accordingly. Your backend will be notified on the result of the verification with the [Verification Result Event](doc:verification-rest-callback-api#verification-result-event). > 📘 For information about webhooks and the verifications events [Callbacks](/docs/verification-rest-callback-api). * * The version of the OpenAPI document: 1.0.0 * Contact: support@sinch.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.sinch.sdk.domains.verification.adapters.api.v1; public class SendingAndReportingVerificationsApi { private static final Logger LOGGER = Logger.getLogger(SendingAndReportingVerificationsApi.class.getName()); private HttpClient httpClient; private ServerConfiguration serverConfiguration; private Map<String, AuthManager> authManagersByOasSecuritySchemes; private HttpMapper mapper; public SendingAndReportingVerificationsApi( HttpClient httpClient, ServerConfiguration serverConfiguration, Map<String, AuthManager> authManagersByOasSecuritySchemes, HttpMapper mapper) { this.httpClient = httpClient; this.serverConfiguration = serverConfiguration; this.authManagersByOasSecuritySchemes = authManagersByOasSecuritySchemes; this.mapper = mapper; } /** * Verify verification code by Id Used to report OTP code. * * @param id (required) * @param verificationReportRequestResourceDto (required) * @return VerificationResponseDto * @throws ApiException if fails to make API call */
/* * Verification * Verification REST API for verifying phone numbers and users. Support of FlashCall verification, PIN SMS verification and Callout verification. **Note:** OTP CODE must be the full valid E.164 number that we called from. ## Overview For general information on how to use the Sinch APIs including methods, types, errors and authorization, please check the [Using REST](doc:using-rest) page. Use the Sinch Verification Service to verify end-user's mobile phone numbers. The Sinch Verification APIs should be used in combination with the Verification SDKs for a complete end-to-end solution, though it is possible to only use the APIs. Currently, there are three verification methods supported: - FlashCall verification - Android only - PIN SMS verification - iOS, Android, Javascript - Callout verification (voice call) - iOS only - Data verification (distinguished by method = `seamless`) - iOS, Android #### FlashCall verification With the flashCall verification method, a user's phone number is verified by triggering a \"missed call\" towards this number. The call is intercepted by the Android SDK in the mobile app and blocked automatically. To initiate a flashCall verification, check the [Android SDK documentation](doc:verification-android-the-verification-process#flash-call-verification). For additional security, it is recommended that you control which verification requests should proceed and which ones not, by listening in your backend for the [Verification Request Event](doc:verification-rest-verification-api#verification-request) and respond accordingly. Your backend will be notified on the result of the verification with the [Verification Result Event](doc:verification-rest-callback-api#verification-result-event). #### PIN SMS verification With the PIN SMS verification method, a user's phone number is verified by sending an SMS containing a PIN code to this number. In the case of iOS or Javascript, the user needs to enter the PIN manually in the app, while for Android there is an option of intercepting the SMS message delivery and capturing the PIN code automatically. To initiate a PIN SMS verification, check the [iOS](doc:verification-ios-sms-verification), [Android](doc:verification-for-android) and [Javascript](doc:verification-for-javascript) documentation. For additional security, it is recommended that you control which verification requests should proceed and which ones not, by listening in your backend for the [Verification Request Event](doc:verification-rest-verification-api#verification-request) and respond accordingly. Your backend will be notified on the result of the verification with the [Verification Result Event](doc:verification-rest-callback-api#verification-result-event). #### Callout verification With the callout verification method, a user's phone number is verified by receiving a phone call and hearing a pre-recorded or text-to-speech message, advising the user to press a digit code. When the user presses the digit code in the dialpad, the verification is successful. To initiate a callout verification, check the [iOS documentation](doc:verification-ios-callout-verification). For additional security, it is recommended that you control which verification requests should proceed and which ones not, by listening in your backend for the [Verification Request Event](doc:verification-rest-verification-api#verification-request) and respond accordingly. Your backend will be notified on the result of the verification with the [Verification Result Event](doc:verification-rest-callback-api#verification-result-event). #### Data verification With the data verification method, a user's phone number is verified by carrier using mobile data network. For additional security, it is recommended that you control which verification requests should proceed and which ones not, by listening in your backend for the [Verification Request Event](doc:verification-rest-verification-api#verification-request) and respond accordingly. Your backend will be notified on the result of the verification with the [Verification Result Event](doc:verification-rest-callback-api#verification-result-event). > 📘 For information about webhooks and the verifications events [Callbacks](/docs/verification-rest-callback-api). * * The version of the OpenAPI document: 1.0.0 * Contact: support@sinch.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.sinch.sdk.domains.verification.adapters.api.v1; public class SendingAndReportingVerificationsApi { private static final Logger LOGGER = Logger.getLogger(SendingAndReportingVerificationsApi.class.getName()); private HttpClient httpClient; private ServerConfiguration serverConfiguration; private Map<String, AuthManager> authManagersByOasSecuritySchemes; private HttpMapper mapper; public SendingAndReportingVerificationsApi( HttpClient httpClient, ServerConfiguration serverConfiguration, Map<String, AuthManager> authManagersByOasSecuritySchemes, HttpMapper mapper) { this.httpClient = httpClient; this.serverConfiguration = serverConfiguration; this.authManagersByOasSecuritySchemes = authManagersByOasSecuritySchemes; this.mapper = mapper; } /** * Verify verification code by Id Used to report OTP code. * * @param id (required) * @param verificationReportRequestResourceDto (required) * @return VerificationResponseDto * @throws ApiException if fails to make API call */
public VerificationResponseDto reportVerificationById(
15
2023-10-31 08:32:59+00:00
24k
SpCoGov/SpCoBot
src/main/java/top/spco/SpCoBot.java
[ { "identifier": "Bot", "path": "src/main/java/top/spco/api/Bot.java", "snippet": "public interface Bot extends Identifiable {\n /**\n * 当 BotSettings 在线 (可正常收发消息) 时返回 {@code true}.\n */\n boolean isOnline();\n\n /**\n * 全部的好友分组\n */\n FriendGroups getFriendGroups();\n\n /*...
import top.spco.api.Bot; import top.spco.api.Logger; import top.spco.api.message.service.MessageService; import top.spco.core.CAATP; import top.spco.core.config.BotSettings; import top.spco.core.config.Settings; import top.spco.core.config.SettingsVersion; import top.spco.core.database.DataBase; import top.spco.events.*; import top.spco.service.AutoAgreeValorant; import top.spco.service.AutoSign; import top.spco.service.GroupMessageRecorder; import top.spco.service.chat.ChatDispatcher; import top.spco.service.chat.ChatType; import top.spco.service.command.Command; import top.spco.service.command.CommandDispatcher; import top.spco.service.command.CommandMeta; import top.spco.service.command.CommandSyntaxException; import top.spco.service.dashscope.DashScopeDispatcher; import top.spco.service.statistics.StatisticsDispatcher; import top.spco.user.BotUser; import top.spco.user.BotUsers; import top.spco.util.ExceptionUtils; import java.io.File; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
21,589
/* * Copyright 2023 SpCo * * 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 top.spco; /** * <pre> * _oo0oo_ * o8888888o * 88" . "88 * (| -_- |) * 0\ = /0 * ___/`---'\___ * .' \\| |// '. * / \\||| : |||// \ * / _||||| -:- |||||- \ * | | \\\ - /// | | * | \_| ''\---/'' |_/ | * \ .-\__ '-' ___/-. / * ___'. .' /--.--\ `. .'___ * ."" '< `.___\_<|>_/___.' >' "". * | | : `- \`.;`\ _ /`;.`/ - ` : | | * \ \ `_. \_ __\ /__ _/ .-` / / * =====`-.____`.___ \_____/___.-`___.-'===== * `=---=' * 佛祖保佑机器人不被腾讯风控 * </pre> * * @author SpCo * @version 1.3.0 * @since 0.1.0 */ public class SpCoBot { private static SpCoBot instance; public static Logger logger; public static File dataFolder; public static File configFolder; public long botId; public long botOwnerId; public long testGroupId; private CommandDispatcher commandDispatcher; public final ChatDispatcher chatDispatcher = ChatDispatcher.getInstance(); public final StatisticsDispatcher statisticsDispatcher = StatisticsDispatcher.getInstance(); public final DashScopeDispatcher dashScopeDispatcher = DashScopeDispatcher.getInstance(); private Settings settings; private MessageService messageService; private DataBase dataBase; private Bot bot; private CAATP caatp; private static boolean registered = false; /** * 版本号格式采用语义版本号(X.Y.Z) * <ul> * <li>X: 主版本号 (表示重大的、不兼容的变更)</li> * <li>Y: 次版本号 (表示向后兼容的新功能或改进)</li> * <li>Z: 修订号 (表示向后兼容的错误修复或小的改进)</li> * </ul> * <b>更新版本号(仅限核心的 Feature)时请不要忘记在 build.gradle 中同步修改版本号</b> */ public static final String MAIN_VERSION = "1.3.0"; public static final String VERSION = "v" + MAIN_VERSION + "-1"; public static final String UPDATED_TIME = "2023-01-11 18:13"; public static final String OLDEST_SUPPORTED_CONFIG_VERSION = "0.3.2"; private SpCoBot() { initEvents(); } public void initOthers() { this.dataBase = new DataBase(); this.caatp = CAATP.getInstance(); new GroupMessageRecorder(); new AutoSign(); new AutoAgreeValorant(); this.settings = new Settings(configFolder.getAbsolutePath() + File.separator + "config.yaml"); if (expired(settings.getStringProperty(SettingsVersion.CONFIG_VERSION))) { logger.error("配置版本过时,请备份配置后删除配置重新启动机器人以生成新配置。"); System.exit(-2); } botId = settings.getLongProperty(BotSettings.BOT_ID); botOwnerId = settings.getLongProperty(BotSettings.OWNER_ID); testGroupId = settings.getLongProperty(BotSettings.TEST_GROUP); this.commandDispatcher = CommandDispatcher.getInstance(); } private void initEvents() { if (registered) { return; } registered = true; ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // 每秒钟调用一次 scheduler.scheduleAtFixedRate(() -> PeriodicSchedulerEvents.SECOND_TICK.invoker().onSecondTick(), 0, 1, TimeUnit.SECONDS); // 每分钟调用一次 scheduler.scheduleAtFixedRate(() -> PeriodicSchedulerEvents.MINUTE_TICK.invoker().onMinuteTick(), 0, 1, TimeUnit.MINUTES); // 插件启用时 PluginEvents.ENABLE_PLUGIN_TICK.register(this::onEnable); // 插件禁用时 PluginEvents.DISABLE_PLUGIN_TICK.register(this::onDisable); // 机器人被拍一拍时的提示 BotEvents.NUDGED_TICK.register((from, target, subject, action, suffix) -> { if (target.getId() == this.botId) { subject.sendMessage("机器人正常运行中"); } }); // 自动接受好友请求 FriendEvents.REQUESTED_AS_FRIEND.register((eventId, message, fromId, fromGroupId, fromGroup, behavior) -> behavior.accept()); // 自动接受群邀请 GroupEvents.INVITED_JOIN_GROUP.register((eventId, invitorId, groupId, invitor, behavior) -> behavior.accept()); // 处理好友命令 MessageEvents.FRIEND_MESSAGE.register((bot, sender, message, time) -> { String context = message.toMessageContext(); if (this.chatDispatcher.isInChat(sender, ChatType.FRIEND)) { this.chatDispatcher.onMessage(ChatType.FRIEND, bot, sender, sender, message, time); return; } if (context.startsWith(CommandDispatcher.COMMAND_START_SYMBOL)) { try {
/* * Copyright 2023 SpCo * * 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 top.spco; /** * <pre> * _oo0oo_ * o8888888o * 88" . "88 * (| -_- |) * 0\ = /0 * ___/`---'\___ * .' \\| |// '. * / \\||| : |||// \ * / _||||| -:- |||||- \ * | | \\\ - /// | | * | \_| ''\---/'' |_/ | * \ .-\__ '-' ___/-. / * ___'. .' /--.--\ `. .'___ * ."" '< `.___\_<|>_/___.' >' "". * | | : `- \`.;`\ _ /`;.`/ - ` : | | * \ \ `_. \_ __\ /__ _/ .-` / / * =====`-.____`.___ \_____/___.-`___.-'===== * `=---=' * 佛祖保佑机器人不被腾讯风控 * </pre> * * @author SpCo * @version 1.3.0 * @since 0.1.0 */ public class SpCoBot { private static SpCoBot instance; public static Logger logger; public static File dataFolder; public static File configFolder; public long botId; public long botOwnerId; public long testGroupId; private CommandDispatcher commandDispatcher; public final ChatDispatcher chatDispatcher = ChatDispatcher.getInstance(); public final StatisticsDispatcher statisticsDispatcher = StatisticsDispatcher.getInstance(); public final DashScopeDispatcher dashScopeDispatcher = DashScopeDispatcher.getInstance(); private Settings settings; private MessageService messageService; private DataBase dataBase; private Bot bot; private CAATP caatp; private static boolean registered = false; /** * 版本号格式采用语义版本号(X.Y.Z) * <ul> * <li>X: 主版本号 (表示重大的、不兼容的变更)</li> * <li>Y: 次版本号 (表示向后兼容的新功能或改进)</li> * <li>Z: 修订号 (表示向后兼容的错误修复或小的改进)</li> * </ul> * <b>更新版本号(仅限核心的 Feature)时请不要忘记在 build.gradle 中同步修改版本号</b> */ public static final String MAIN_VERSION = "1.3.0"; public static final String VERSION = "v" + MAIN_VERSION + "-1"; public static final String UPDATED_TIME = "2023-01-11 18:13"; public static final String OLDEST_SUPPORTED_CONFIG_VERSION = "0.3.2"; private SpCoBot() { initEvents(); } public void initOthers() { this.dataBase = new DataBase(); this.caatp = CAATP.getInstance(); new GroupMessageRecorder(); new AutoSign(); new AutoAgreeValorant(); this.settings = new Settings(configFolder.getAbsolutePath() + File.separator + "config.yaml"); if (expired(settings.getStringProperty(SettingsVersion.CONFIG_VERSION))) { logger.error("配置版本过时,请备份配置后删除配置重新启动机器人以生成新配置。"); System.exit(-2); } botId = settings.getLongProperty(BotSettings.BOT_ID); botOwnerId = settings.getLongProperty(BotSettings.OWNER_ID); testGroupId = settings.getLongProperty(BotSettings.TEST_GROUP); this.commandDispatcher = CommandDispatcher.getInstance(); } private void initEvents() { if (registered) { return; } registered = true; ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // 每秒钟调用一次 scheduler.scheduleAtFixedRate(() -> PeriodicSchedulerEvents.SECOND_TICK.invoker().onSecondTick(), 0, 1, TimeUnit.SECONDS); // 每分钟调用一次 scheduler.scheduleAtFixedRate(() -> PeriodicSchedulerEvents.MINUTE_TICK.invoker().onMinuteTick(), 0, 1, TimeUnit.MINUTES); // 插件启用时 PluginEvents.ENABLE_PLUGIN_TICK.register(this::onEnable); // 插件禁用时 PluginEvents.DISABLE_PLUGIN_TICK.register(this::onDisable); // 机器人被拍一拍时的提示 BotEvents.NUDGED_TICK.register((from, target, subject, action, suffix) -> { if (target.getId() == this.botId) { subject.sendMessage("机器人正常运行中"); } }); // 自动接受好友请求 FriendEvents.REQUESTED_AS_FRIEND.register((eventId, message, fromId, fromGroupId, fromGroup, behavior) -> behavior.accept()); // 自动接受群邀请 GroupEvents.INVITED_JOIN_GROUP.register((eventId, invitorId, groupId, invitor, behavior) -> behavior.accept()); // 处理好友命令 MessageEvents.FRIEND_MESSAGE.register((bot, sender, message, time) -> { String context = message.toMessageContext(); if (this.chatDispatcher.isInChat(sender, ChatType.FRIEND)) { this.chatDispatcher.onMessage(ChatType.FRIEND, bot, sender, sender, message, time); return; } if (context.startsWith(CommandDispatcher.COMMAND_START_SYMBOL)) { try {
CommandMeta meta = new CommandMeta(context, message);
15
2023-10-26 10:27:47+00:00
24k
Melledy/LunarCore
src/main/java/emu/lunarcore/command/commands/LineupCommand.java
[ { "identifier": "GameConstants", "path": "src/main/java/emu/lunarcore/GameConstants.java", "snippet": "public class GameConstants {\n public static String VERSION = \"1.6.0\";\n \n public static final ZoneOffset CURRENT_ZONEOFFSET = ZoneOffset.systemDefault().getRules().getOffset(Instant.now())...
import java.util.ArrayList; import java.util.List; import emu.lunarcore.GameConstants; import emu.lunarcore.command.Command; import emu.lunarcore.command.CommandArgs; import emu.lunarcore.command.CommandHandler; import emu.lunarcore.game.avatar.GameAvatar; import emu.lunarcore.game.player.Player; import emu.lunarcore.game.player.lineup.PlayerLineup; import emu.lunarcore.util.Utils;
16,669
package emu.lunarcore.command.commands; @Command(label = "lineup", permission = "player.lineup", requireTarget = true, desc = "/lineup [avatar ids]. USE AT YOUR OWN RISK. Sets your current lineup with the specified avatar ids.") public class LineupCommand implements CommandHandler { @Override public void execute(CommandArgs args) { // Get target player Player target = args.getTarget(); // Do not set lineup while the target player is in a battle if (target.isInBattle()) { args.sendMessage("Error: The targeted player is in a battle"); return; } // Temp avatar list List<Integer> avatars = new ArrayList<>(); // Validate avatars in temp list for (String arg : args.getList()) { // Make sure the avatar actually exist
package emu.lunarcore.command.commands; @Command(label = "lineup", permission = "player.lineup", requireTarget = true, desc = "/lineup [avatar ids]. USE AT YOUR OWN RISK. Sets your current lineup with the specified avatar ids.") public class LineupCommand implements CommandHandler { @Override public void execute(CommandArgs args) { // Get target player Player target = args.getTarget(); // Do not set lineup while the target player is in a battle if (target.isInBattle()) { args.sendMessage("Error: The targeted player is in a battle"); return; } // Temp avatar list List<Integer> avatars = new ArrayList<>(); // Validate avatars in temp list for (String arg : args.getList()) { // Make sure the avatar actually exist
GameAvatar avatar = target.getAvatarById(Utils.parseSafeInt(arg));
6
2023-10-10 12:57:35+00:00
24k
jar-analyzer/jar-analyzer
src/main/java/org/jetbrains/java/decompiler/main/rels/LambdaProcessor.java
[ { "identifier": "CodeConstants", "path": "src/main/java/org/jetbrains/java/decompiler/code/CodeConstants.java", "snippet": "@SuppressWarnings({\"unused\", \"SpellCheckingInspection\"})\npublic interface CodeConstants {\n // ----------------------------------------------------------------------\n // BY...
import org.jetbrains.java.decompiler.code.CodeConstants; import org.jetbrains.java.decompiler.code.Instruction; import org.jetbrains.java.decompiler.code.InstructionSequence; import org.jetbrains.java.decompiler.main.ClassesProcessor; import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; import org.jetbrains.java.decompiler.main.DecompilerContext; import org.jetbrains.java.decompiler.struct.StructClass; import org.jetbrains.java.decompiler.struct.StructMethod; import org.jetbrains.java.decompiler.struct.attr.StructBootstrapMethodsAttribute; import org.jetbrains.java.decompiler.struct.attr.StructGeneralAttribute; import org.jetbrains.java.decompiler.struct.consts.LinkConstant; import org.jetbrains.java.decompiler.struct.consts.PooledConstant; import org.jetbrains.java.decompiler.struct.consts.PrimitiveConstant; import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; import org.jetbrains.java.decompiler.util.InterpreterUtil; import java.io.IOException; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map;
19,748
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.java.decompiler.main.rels; public class LambdaProcessor { @SuppressWarnings("SpellCheckingInspection") private static final String JAVAC_LAMBDA_CLASS = "java/lang/invoke/LambdaMetafactory"; @SuppressWarnings("SpellCheckingInspection") private static final String JAVAC_LAMBDA_METHOD = "metafactory"; @SuppressWarnings("SpellCheckingInspection") private static final String JAVAC_LAMBDA_ALT_METHOD = "altMetafactory"; public void processClass(ClassNode node) throws IOException { for (ClassNode child : node.nested) { processClass(child); } ClassesProcessor clProcessor = DecompilerContext.getClassProcessor(); StructClass cl = node.classStruct; if (cl.getBytecodeVersion() < CodeConstants.BYTECODE_JAVA_8) { // lambda beginning with Java 8 return; } StructBootstrapMethodsAttribute bootstrap = cl.getAttribute(StructGeneralAttribute.ATTRIBUTE_BOOTSTRAP_METHODS); if (bootstrap == null || bootstrap.getMethodsNumber() == 0) { return; // no bootstrap constants in pool } BitSet lambda_methods = new BitSet(); // find lambda bootstrap constants for (int i = 0; i < bootstrap.getMethodsNumber(); ++i) {
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.java.decompiler.main.rels; public class LambdaProcessor { @SuppressWarnings("SpellCheckingInspection") private static final String JAVAC_LAMBDA_CLASS = "java/lang/invoke/LambdaMetafactory"; @SuppressWarnings("SpellCheckingInspection") private static final String JAVAC_LAMBDA_METHOD = "metafactory"; @SuppressWarnings("SpellCheckingInspection") private static final String JAVAC_LAMBDA_ALT_METHOD = "altMetafactory"; public void processClass(ClassNode node) throws IOException { for (ClassNode child : node.nested) { processClass(child); } ClassesProcessor clProcessor = DecompilerContext.getClassProcessor(); StructClass cl = node.classStruct; if (cl.getBytecodeVersion() < CodeConstants.BYTECODE_JAVA_8) { // lambda beginning with Java 8 return; } StructBootstrapMethodsAttribute bootstrap = cl.getAttribute(StructGeneralAttribute.ATTRIBUTE_BOOTSTRAP_METHODS); if (bootstrap == null || bootstrap.getMethodsNumber() == 0) { return; // no bootstrap constants in pool } BitSet lambda_methods = new BitSet(); // find lambda bootstrap constants for (int i = 0; i < bootstrap.getMethodsNumber(); ++i) {
LinkConstant method_ref = bootstrap.getMethodReference(i); // method handle
10
2023-10-07 15:42:35+00:00
24k
lunasaw/gb28181-proxy
gb28181-client/src/test/java/io/github/lunasw/gbproxy/client/test/cmd/ApplicationTest.java
[ { "identifier": "Gb28181Client", "path": "gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/Gb28181Client.java", "snippet": "@SpringBootApplication\npublic class Gb28181Client {\n\n public static void main(String[] args) {\n SpringApplication.run(Gb28181Client.class, args);\n }\...
import javax.sip.message.Request; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import io.github.lunasaw.gbproxy.client.Gb28181Client; import io.github.lunasaw.gbproxy.client.transmit.request.message.ClientMessageRequestProcessor; import io.github.lunasaw.gbproxy.client.transmit.response.register.RegisterResponseProcessor; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.layer.SipLayer; import io.github.lunasaw.sip.common.transmit.SipProcessorObserver; import io.github.lunasaw.sip.common.transmit.SipSender; import io.github.lunasaw.sip.common.transmit.event.Event; import io.github.lunasaw.sip.common.transmit.event.EventResult; import io.github.lunasaw.sip.common.transmit.request.SipRequestProvider; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import lombok.SneakyThrows;
16,704
package io.github.lunasw.gbproxy.client.test.cmd; /** * @author luna * @date 2023/10/13 */ @SpringBootTest(classes = Gb28181Client.class) public class ApplicationTest { static String localIp = "172.19.128.100"; FromDevice fromDevice; ToDevice toDevice; @Autowired SipLayer sipLayer; @BeforeEach public void before() { sipLayer.addListeningPoint(localIp, 8117); fromDevice = FromDevice.getInstance("33010602011187000001", localIp, 8117); toDevice = ToDevice.getInstance("41010500002000000001", localIp, 8118); toDevice.setPassword("luna"); toDevice.setRealm("4101050000"); } @SneakyThrows @Test public void atest() { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createMessageRequest(fromDevice, toDevice, "123123", callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest); } @SneakyThrows @Test public void register() { String callId = SipRequestUtils.getNewCallId(); Request registerRequest = SipRequestProvider.createRegisterRequest(fromDevice, toDevice, 300, callId); SipSender.transmitRequestSuccess(fromDevice.getIp(), registerRequest, new Event() { @Override public void response(EventResult eventResult) { System.out.println(eventResult); } }); } @SneakyThrows @Test public void registerResponse() { String callId = SipRequestUtils.getNewCallId(); // 构造请求 fromDevice:当前发送的设备 toDevice 接收消息的设备 Request registerRequest = SipRequestProvider.createRegisterRequest(fromDevice, toDevice, 300, callId); // 响应处理器 RegisterResponseProcessor responseProcessor = new RegisterResponseProcessor(); // 添加响应处理器
package io.github.lunasw.gbproxy.client.test.cmd; /** * @author luna * @date 2023/10/13 */ @SpringBootTest(classes = Gb28181Client.class) public class ApplicationTest { static String localIp = "172.19.128.100"; FromDevice fromDevice; ToDevice toDevice; @Autowired SipLayer sipLayer; @BeforeEach public void before() { sipLayer.addListeningPoint(localIp, 8117); fromDevice = FromDevice.getInstance("33010602011187000001", localIp, 8117); toDevice = ToDevice.getInstance("41010500002000000001", localIp, 8118); toDevice.setPassword("luna"); toDevice.setRealm("4101050000"); } @SneakyThrows @Test public void atest() { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createMessageRequest(fromDevice, toDevice, "123123", callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest); } @SneakyThrows @Test public void register() { String callId = SipRequestUtils.getNewCallId(); Request registerRequest = SipRequestProvider.createRegisterRequest(fromDevice, toDevice, 300, callId); SipSender.transmitRequestSuccess(fromDevice.getIp(), registerRequest, new Event() { @Override public void response(EventResult eventResult) { System.out.println(eventResult); } }); } @SneakyThrows @Test public void registerResponse() { String callId = SipRequestUtils.getNewCallId(); // 构造请求 fromDevice:当前发送的设备 toDevice 接收消息的设备 Request registerRequest = SipRequestProvider.createRegisterRequest(fromDevice, toDevice, 300, callId); // 响应处理器 RegisterResponseProcessor responseProcessor = new RegisterResponseProcessor(); // 添加响应处理器
SipProcessorObserver.addResponseProcessor(RegisterResponseProcessor.METHOD, responseProcessor);
6
2023-10-11 06:56:28+00:00
24k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/SWMPlugin.java
[ { "identifier": "SlimePlugin", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/SlimePlugin.java", "snippet": "public interface SlimePlugin {\n\n /**\n * Returns the {@link ConfigManager} of the plugin.\n * This can be used to retrieve the {@link net.swofty.swm.api.world.data....
import com.flowpowered.nbt.CompoundMap; import com.flowpowered.nbt.CompoundTag; import net.swofty.swm.api.SlimePlugin; import net.swofty.swm.api.events.PostGenerateWorldEvent; import net.swofty.swm.api.events.PreGenerateWorldEvent; import net.swofty.swm.api.exceptions.*; import net.swofty.swm.api.loaders.SlimeLoader; import net.swofty.swm.api.world.SlimeWorld; import net.swofty.swm.api.world.data.WorldData; import net.swofty.swm.api.world.data.WorldsConfig; import net.swofty.swm.api.world.properties.SlimePropertyMap; import net.swofty.swm.nms.craft.CraftSlimeWorld; import net.swofty.swm.nms.SlimeNMS; import net.swofty.swm.plugin.commands.CommandLoader; import net.swofty.swm.plugin.commands.SWMCommand; import net.swofty.swm.plugin.loader.LoaderUtils; import net.swofty.swm.plugin.log.Logging; import net.swofty.swm.plugin.world.WorldUnlocker; import net.swofty.swm.plugin.world.importer.WorldImporter; import lombok.Getter; import net.swofty.swm.plugin.config.ConfigManager; import ninja.leaping.configurate.objectmapping.ObjectMappingException; import org.bukkit.*; import org.bukkit.command.CommandMap; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.plugin.java.JavaPlugin; import org.reflections.Reflections; import java.io.*; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors;
17,682
package net.swofty.swm.plugin; @Getter public class SWMPlugin extends JavaPlugin implements SlimePlugin { @Getter private static SWMPlugin instance; private SlimeNMS nms; private CommandLoader cl; public CommandMap commandMap; private final List<SlimeWorld> toGenerate = Collections.synchronizedList(new ArrayList<>()); private final ExecutorService worldGeneratorService = Executors.newFixedThreadPool(1); @Override public void onLoad() { /* Static abuse?!?! Nah I'm meming, we all know this is the easiest way to do it Credit: @swofty */ instance = this; /* Initialize config files */ try {
package net.swofty.swm.plugin; @Getter public class SWMPlugin extends JavaPlugin implements SlimePlugin { @Getter private static SWMPlugin instance; private SlimeNMS nms; private CommandLoader cl; public CommandMap commandMap; private final List<SlimeWorld> toGenerate = Collections.synchronizedList(new ArrayList<>()); private final ExecutorService worldGeneratorService = Executors.newFixedThreadPool(1); @Override public void onLoad() { /* Static abuse?!?! Nah I'm meming, we all know this is the easiest way to do it Credit: @swofty */ instance = this; /* Initialize config files */ try {
ConfigManager.initialize();
16
2023-10-08 10:54:28+00:00
24k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/api/impl/PromptConstructorImpl.java
[ { "identifier": "PromptConstructor", "path": "src/main/java/zju/cst/aces/api/PromptConstructor.java", "snippet": "public interface PromptConstructor {\n\n List<Message> generate();\n\n}" }, { "identifier": "Config", "path": "src/main/java/zju/cst/aces/api/config/Config.java", "snippet...
import com.google.j2objc.annotations.ObjectiveCName; import lombok.Data; import zju.cst.aces.api.PromptConstructor; import zju.cst.aces.api.config.Config; import zju.cst.aces.dto.ClassInfo; import zju.cst.aces.dto.Message; import zju.cst.aces.dto.MethodInfo; import zju.cst.aces.dto.PromptInfo; import zju.cst.aces.prompt.PromptGenerator; import zju.cst.aces.runner.AbstractRunner; import zju.cst.aces.util.TokenCounter; import java.io.IOException; import java.util.List; import zju.cst.aces.api.PromptConstructor;
17,919
package zju.cst.aces.api.impl; @Data public class PromptConstructorImpl implements PromptConstructor { Config config; PromptInfo promptInfo; List<Message> messages; int tokenCount = 0; String testName; String fullTestName; static final String separator = "_"; public PromptConstructorImpl(Config config) { this.config = config; } @Override public List<Message> generate() { try { if (promptInfo == null) { throw new RuntimeException("PromptInfo is null, you need to initialize it first."); } this.messages = new PromptGenerator(config).generateMessages(promptInfo); countToken(); return this.messages; } catch (IOException e) { throw new RuntimeException(e); } } public void setPromptInfoWithDep(ClassInfo classInfo, MethodInfo methodInfo) throws IOException {
package zju.cst.aces.api.impl; @Data public class PromptConstructorImpl implements PromptConstructor { Config config; PromptInfo promptInfo; List<Message> messages; int tokenCount = 0; String testName; String fullTestName; static final String separator = "_"; public PromptConstructorImpl(Config config) { this.config = config; } @Override public List<Message> generate() { try { if (promptInfo == null) { throw new RuntimeException("PromptInfo is null, you need to initialize it first."); } this.messages = new PromptGenerator(config).generateMessages(promptInfo); countToken(); return this.messages; } catch (IOException e) { throw new RuntimeException(e); } } public void setPromptInfoWithDep(ClassInfo classInfo, MethodInfo methodInfo) throws IOException {
this.promptInfo = AbstractRunner.generatePromptInfoWithDep(config, classInfo, methodInfo);
7
2023-10-14 07:15:10+00:00
24k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/web/WomClient.java
[ { "identifier": "WomUtilsPlugin", "path": "src/main/java/net/wiseoldman/WomUtilsPlugin.java", "snippet": "@Slf4j\n@PluginDependency(XpUpdaterPlugin.class)\n@PluginDescriptor(\n\tname = \"Wise Old Man\",\n\ttags = {\"wom\", \"utils\", \"group\", \"xp\"},\n\tdescription = \"Helps you manage your wiseoldma...
import com.google.gson.Gson; import net.wiseoldman.WomUtilsPlugin; import net.wiseoldman.beans.GroupInfoWithMemberships; import net.wiseoldman.beans.NameChangeEntry; import net.wiseoldman.beans.ParticipantWithStanding; import net.wiseoldman.beans.WomStatus; import net.wiseoldman.beans.ParticipantWithCompetition; import net.wiseoldman.beans.GroupMemberAddition; import net.wiseoldman.beans.Member; import net.wiseoldman.beans.GroupMemberRemoval; import net.wiseoldman.beans.PlayerInfo; import net.wiseoldman.beans.WomPlayerUpdate; import net.wiseoldman.events.WomOngoingPlayerCompetitionsFetched; import net.wiseoldman.events.WomUpcomingPlayerCompetitionsFetched; import net.wiseoldman.ui.WomIconHandler; import net.wiseoldman.WomUtilsConfig; import net.wiseoldman.events.WomGroupMemberAdded; import net.wiseoldman.events.WomGroupMemberRemoved; import net.wiseoldman.events.WomGroupSynced; import java.awt.Color; import java.io.IOException; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.MessageNode; import net.runelite.api.events.ChatMessage; import net.runelite.client.callback.ClientThread; import net.runelite.client.chat.ChatColorType; import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.QueuedMessage; import net.runelite.client.eventbus.EventBus; import okhttp3.Callback; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response;
16,384
private void syncClanMembersCallBack(Response response) { final String message; if (response.isSuccessful()) { GroupInfoWithMemberships data = parseResponse(response, GroupInfoWithMemberships.class); postEvent(new WomGroupSynced(data)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void removeMemberCallback(Response response, String username) { final String message; final WomStatus data = parseResponse(response, WomStatus.class); if (response.isSuccessful()) { postEvent(new WomGroupMemberRemoved(username)); } else { message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void addMemberCallback(Response response, String username) { final String message; if (response.isSuccessful()) { postEvent(new WomGroupMemberAdded(username)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void playerOngoingCompetitionsCallback(String username, Response response) { if (response.isSuccessful()) { ParticipantWithStanding[] comps = parseResponse(response, ParticipantWithStanding[].class); postEvent(new WomOngoingPlayerCompetitionsFetched(username, comps)); } else { WomStatus data = parseResponse(response, WomStatus.class); String message = "Error: " + data.getMessage(); sendResponseToChat(message, ERROR); } } private void playerUpcomingCompetitionsCallback(String username, Response response) { if (response.isSuccessful()) { ParticipantWithCompetition[] comps = parseResponse(response, ParticipantWithCompetition[].class); postEvent(new WomUpcomingPlayerCompetitionsFetched(username, comps)); } else { WomStatus data = parseResponse(response, WomStatus.class); String message = "Error: " + data.getMessage(); sendResponseToChat(message, ERROR); } } private <T> T parseResponse(Response r, Class<T> clazz) { return parseResponse(r, clazz, false); } private <T> T parseResponse(Response r, Class<T> clazz, boolean nullIferror) { if (nullIferror && !r.isSuccessful()) { return null; } String body; try { body = r.body().string(); } catch (IOException e) { log.error("Could not read response {}", e.getMessage()); return null; } return gson.fromJson(body, clazz); } private void sendResponseToChat(String message, Color color) { ChatMessageBuilder cmb = new ChatMessageBuilder(); cmb.append("[WOM] "); cmb.append(color, message); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(cmb.build()) .build()); } public void syncClanMembers(ArrayList<Member> clanMembers) {
package net.wiseoldman.web; @Slf4j public class WomClient { @Inject private OkHttpClient okHttpClient; private Gson gson; @Inject private WomIconHandler iconHandler; @Inject private Client client; @Inject private WomUtilsConfig config; @Inject private ChatMessageManager chatMessageManager; @Inject private ClientThread clientThread; @Inject private EventBus eventBus; private static final Color SUCCESS = new Color(170, 255, 40); private static final Color ERROR = new Color(204, 66, 66); private static final DecimalFormat NUMBER_FORMAT = new DecimalFormat("#.##"); private final WomUtilsPlugin plugin; private final String leagueError = " You are currently in a League world. Your group configurations might be for the main game."; @Inject public WomClient(Gson gson, WomUtilsPlugin plugin) { this.gson = gson.newBuilder() .setDateFormat(DateFormat.FULL, DateFormat.FULL) .create(); this.plugin = plugin; } public void submitNameChanges(NameChangeEntry[] changes) { Request request = createRequest(changes, HttpMethod.POST, "names", "bulk"); sendRequest(request); log.info("Submitted {} name changes to WOM", changes.length); } void sendRequest(Request request) { sendRequest(request, r -> {}); } void sendRequest(Request request, Consumer<Response> consumer) { sendRequest(request, new WomCallback(consumer)); } void sendRequest(Request request, Consumer<Response> consumer, Consumer<Exception> exceptionConsumer) { sendRequest(request, new WomCallback(consumer, exceptionConsumer)); } void sendRequest(Request request, Callback callback) { okHttpClient.newCall(request).enqueue(callback); } private Request createRequest(Object payload, String... pathSegments) { return createRequest(payload, HttpMethod.POST, pathSegments); } private Request createRequest(Object payload, HttpMethod httpMethod, String... pathSegments) { HttpUrl url = buildUrl(pathSegments); RequestBody body = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), gson.toJson(payload) ); Request.Builder requestBuilder = new Request.Builder() .header("User-Agent", "WiseOldMan RuneLite Plugin") .url(url); if (httpMethod == HttpMethod.PUT) { return requestBuilder.put(body).build(); } else if (httpMethod == HttpMethod.DELETE) { return requestBuilder.delete(body).build(); } return requestBuilder.post(body).build(); } private Request createRequest(String... pathSegments) { HttpUrl url = buildUrl(pathSegments); return new Request.Builder() .header("User-Agent", "WiseOldMan RuneLite Plugin") .url(url) .build(); } private HttpUrl buildUrl(String[] pathSegments) { HttpUrl.Builder urlBuilder = new HttpUrl.Builder() .scheme("https") .host("api.wiseoldman.net") .addPathSegment(this.plugin.isSeasonal ? "league" : "v2"); for (String pathSegment : pathSegments) { if (pathSegment.startsWith("?")) { // A query param String[] kv = pathSegment.substring(1).split("="); urlBuilder.addQueryParameter(kv[0], kv[1]); } else { urlBuilder.addPathSegment(pathSegment); } } return urlBuilder.build(); } public void importGroupMembers() { if (config.groupId() > 0) { Request request = createRequest("groups", "" + config.groupId()); sendRequest(request, this::importMembersCallback); } } private void importMembersCallback(Response response) { if (!response.isSuccessful()) { return; } GroupInfoWithMemberships groupInfo = parseResponse(response, GroupInfoWithMemberships.class); postEvent(new WomGroupSynced(groupInfo, true)); } private void syncClanMembersCallBack(Response response) { final String message; if (response.isSuccessful()) { GroupInfoWithMemberships data = parseResponse(response, GroupInfoWithMemberships.class); postEvent(new WomGroupSynced(data)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void removeMemberCallback(Response response, String username) { final String message; final WomStatus data = parseResponse(response, WomStatus.class); if (response.isSuccessful()) { postEvent(new WomGroupMemberRemoved(username)); } else { message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void addMemberCallback(Response response, String username) { final String message; if (response.isSuccessful()) { postEvent(new WomGroupMemberAdded(username)); } else { WomStatus data = parseResponse(response, WomStatus.class); message = "Error: " + data.getMessage() + (this.plugin.isSeasonal ? leagueError : ""); sendResponseToChat(message, ERROR); } } private void playerOngoingCompetitionsCallback(String username, Response response) { if (response.isSuccessful()) { ParticipantWithStanding[] comps = parseResponse(response, ParticipantWithStanding[].class); postEvent(new WomOngoingPlayerCompetitionsFetched(username, comps)); } else { WomStatus data = parseResponse(response, WomStatus.class); String message = "Error: " + data.getMessage(); sendResponseToChat(message, ERROR); } } private void playerUpcomingCompetitionsCallback(String username, Response response) { if (response.isSuccessful()) { ParticipantWithCompetition[] comps = parseResponse(response, ParticipantWithCompetition[].class); postEvent(new WomUpcomingPlayerCompetitionsFetched(username, comps)); } else { WomStatus data = parseResponse(response, WomStatus.class); String message = "Error: " + data.getMessage(); sendResponseToChat(message, ERROR); } } private <T> T parseResponse(Response r, Class<T> clazz) { return parseResponse(r, clazz, false); } private <T> T parseResponse(Response r, Class<T> clazz, boolean nullIferror) { if (nullIferror && !r.isSuccessful()) { return null; } String body; try { body = r.body().string(); } catch (IOException e) { log.error("Could not read response {}", e.getMessage()); return null; } return gson.fromJson(body, clazz); } private void sendResponseToChat(String message, Color color) { ChatMessageBuilder cmb = new ChatMessageBuilder(); cmb.append("[WOM] "); cmb.append(color, message); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(cmb.build()) .build()); } public void syncClanMembers(ArrayList<Member> clanMembers) {
GroupMemberAddition payload = new GroupMemberAddition(config.verificationCode(), clanMembers);
6
2023-10-09 14:23:06+00:00
24k
PeytonPlayz595/c0.0.23a_01
src/main/java/com/mojang/minecraft/particle/Particle.java
[ { "identifier": "Entity", "path": "src/main/java/com/mojang/minecraft/Entity.java", "snippet": "public class Entity implements Serializable {\n\tpublic static final long serialVersionUID = 0L;\n\tprotected Level level;\n\tpublic float xo;\n\tpublic float yo;\n\tpublic float zo;\n\tpublic float x;\n\tpub...
import com.mojang.minecraft.Entity; import com.mojang.minecraft.level.Level; import com.mojang.minecraft.level.tile.Tile; import com.mojang.minecraft.renderer.Tesselator;
20,061
package com.mojang.minecraft.particle; public class Particle extends Entity { private float xd; private float yd; private float zd; public int tex; private float uo; private float vo; private int age = 0; private int lifetime = 0; private float size; private float gravity;
package com.mojang.minecraft.particle; public class Particle extends Entity { private float xd; private float yd; private float zd; public int tex; private float uo; private float vo; private int age = 0; private int lifetime = 0; private float size; private float gravity;
public Particle(Level var1, float var2, float var3, float var4, float var5, float var6, float var7, Tile var8) {
1
2023-10-10 17:10:45+00:00
24k
5152Alotobots/2024_Crescendo_Preseason
src/main/java/frc/robot/chargedup/commands/auto/singleelement/cone/Auto_rightbluecharge_1cone_Cmd.java
[ { "identifier": "Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj", "path": "src/main/java/frc/robot/library/drivetrains/commands/Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj.java", "snippet": "public class Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj extends CommandBase {\n /** Creates a new Cmd_SubSys_Dr...
import edu.wpi.first.wpilibj.DriverStation.Alliance; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.ParallelCommandGroup; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import frc.robot.library.drivetrains.commands.Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj; import frc.robot.chargedup.subsystems.arm.SubSys_Arm; import frc.robot.chargedup.subsystems.arm.commands.Cmd_SubSys_Arm_RotateAndExtend; import frc.robot.chargedup.subsystems.bling.SubSys_Bling; import frc.robot.chargedup.subsystems.bling.SubSys_Bling_Constants; import frc.robot.chargedup.subsystems.bling.commands.Cmd_SubSys_Bling_SetColorValue; import frc.robot.chargedup.subsystems.chargestation.commands.Cmd_SubSys_ChargeStation_Balance; import frc.robot.chargedup.subsystems.hand.SubSys_Hand; import frc.robot.library.drivetrains.SubSys_DriveTrain; import frc.robot.library.gyroscopes.pigeon2.SubSys_PigeonGyro;
16,825
// 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.chargedup.commands.auto.singleelement.cone; /** * *Link For PathPlaner * * https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e65ac68f1d_0_48 */ public class Auto_rightbluecharge_1cone_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain; private final SubSys_PigeonGyro m_pigeonGyro; private final SubSys_Arm subsysArm; private final SubSys_Hand subsysHand; private final SubSys_Bling blingSubSys; /** Creates a new Auto_Challenge1_Cmd. */ public Auto_rightbluecharge_1cone_Cmd( SubSys_DriveTrain driveSubSys, SubSys_PigeonGyro pigeonGyro, SubSys_Arm arm, SubSys_Hand hand, SubSys_Bling bling) { m_DriveTrain = driveSubSys; m_pigeonGyro = pigeonGyro; subsysArm = arm; subsysHand = hand; blingSubSys = bling; /* Construct parallel command groups */ ParallelCommandGroup driveAndRetractArm = new ParallelCommandGroup( new Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj( driveSubSys, "rightcharge_1cone", true, true, Alliance.Blue),
// 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.chargedup.commands.auto.singleelement.cone; /** * *Link For PathPlaner * * https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e65ac68f1d_0_48 */ public class Auto_rightbluecharge_1cone_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain; private final SubSys_PigeonGyro m_pigeonGyro; private final SubSys_Arm subsysArm; private final SubSys_Hand subsysHand; private final SubSys_Bling blingSubSys; /** Creates a new Auto_Challenge1_Cmd. */ public Auto_rightbluecharge_1cone_Cmd( SubSys_DriveTrain driveSubSys, SubSys_PigeonGyro pigeonGyro, SubSys_Arm arm, SubSys_Hand hand, SubSys_Bling bling) { m_DriveTrain = driveSubSys; m_pigeonGyro = pigeonGyro; subsysArm = arm; subsysHand = hand; blingSubSys = bling; /* Construct parallel command groups */ ParallelCommandGroup driveAndRetractArm = new ParallelCommandGroup( new Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj( driveSubSys, "rightcharge_1cone", true, true, Alliance.Blue),
new Cmd_SubSys_Arm_RotateAndExtend(subsysArm, 10.0, true, 0.8, true).withTimeout(4));
2
2023-10-09 00:27:11+00:00
24k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/agent/server/Server.java
[ { "identifier": "RootHandler", "path": "src/main/java/com/monitor/agent/server/handler/RootHandler.java", "snippet": "public class RootHandler extends DefaultResponder {\r\n\r\n @Override\r\n public NanoHTTPD.Response get(\r\n RouterNanoHTTPD.UriResource uriResource, \r\n Map...
import com.monitor.agent.server.handler.RootHandler; import com.monitor.agent.server.handler.LogRecordsHandler; import com.monitor.agent.server.handler.NotFoundHandler; import com.monitor.agent.server.handler.AckHandler; import com.fasterxml.jackson.databind.JsonMappingException; import com.monitor.agent.server.handler.ConfigHandler; import com.monitor.agent.server.handler.WatchMapHandler; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.router.RouterNanoHTTPD; import static org.apache.log4j.Level.*; import java.io.IOException; import com.monitor.agent.server.config.ConfigurationManager; import com.monitor.agent.server.config.FilesConfig; import com.monitor.agent.server.config.OneCServerConfig; import com.monitor.agent.server.handler.AccessibilityHandler; import com.monitor.agent.server.handler.ContinueServerHandler; import com.monitor.agent.server.handler.DefaultResponder; import com.monitor.agent.server.handler.ExecQueryHandler; import com.monitor.agent.server.handler.TJLogConfigHandler; import com.monitor.agent.server.handler.OneCSessionsInfoHandler; import com.monitor.agent.server.handler.PauseServerHandler; import com.monitor.agent.server.handler.PingHandler; import com.monitor.agent.server.handler.StopServerHandler; import com.monitor.agent.server.handler.VersionHandler; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.concurrent.Semaphore; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.log4j.Appender; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.RollingFileAppender; import org.apache.log4j.spi.RootLogger;
18,260
package com.monitor.agent.server; /* * Copyright 2015 Didier Fetter * Copyright 2021 Aleksei Andreev * * 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. * * Changes by Aleksei Andreev: * - almost all code except option processing was rewriten * */ public class Server { private static final Logger logger = Logger.getLogger(Server.class); private static final String AGENT_VERSION = "2.6.3"; private static final String SINCEDB = ".monitor-remote-agent"; private static final String SINCEDB_CAT = "sincedb"; private static Level logLevel = INFO; private RouterNanoHTTPD httpd; private int starterPort = 0; private int port = 8085; private int spoolSize = 1024; private String config; private ConfigurationManager configManager; private int signatureLength = 4096; private boolean tailSelected = false; private String sincedbFile = SINCEDB; private boolean debugWatcherSelected = false; private String stopRoute = "/shutdown"; private boolean stopServer = false; private String logfile = null; private String logfileSize = "10MB"; private int logfileNumber = 5; private final Semaphore pauseLock = new Semaphore(1); private final HashMap<Section, FileWatcher> watchers = new HashMap<>(); public static boolean isCaseInsensitiveFileSystem() { return System.getProperty("os.name").toLowerCase().startsWith("win"); } public static String version() { return AGENT_VERSION; } @SuppressWarnings({"UseSpecificCatch", "CallToPrintStackTrace"}) public static void main(String[] args) { try { Server server = new Server(); server.parseOptions(args); if (server.stopServer) { server.sendStop(); return; } server.setupLogging(); server.initializeFileWatchers(); server.startServer(); } catch (Exception e) { e.printStackTrace(); System.exit(3); } } public Server() { } private void startServer() throws IOException { new File(SINCEDB_CAT).mkdir(); httpd = new RouterNanoHTTPD(port); httpd.addRoute("/", RootHandler.class); httpd.addRoute("/ping", PingHandler.class); httpd.addRoute("/version", VersionHandler.class); httpd.addRoute("/pause", PauseServerHandler.class, this); httpd.addRoute("/continue", ContinueServerHandler.class, this); httpd.addRoute("/config", ConfigHandler.class, this); httpd.addRoute("/accessibility", AccessibilityHandler.class, this); httpd.addRoute("/watchmap", WatchMapHandler.class, this);
package com.monitor.agent.server; /* * Copyright 2015 Didier Fetter * Copyright 2021 Aleksei Andreev * * 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. * * Changes by Aleksei Andreev: * - almost all code except option processing was rewriten * */ public class Server { private static final Logger logger = Logger.getLogger(Server.class); private static final String AGENT_VERSION = "2.6.3"; private static final String SINCEDB = ".monitor-remote-agent"; private static final String SINCEDB_CAT = "sincedb"; private static Level logLevel = INFO; private RouterNanoHTTPD httpd; private int starterPort = 0; private int port = 8085; private int spoolSize = 1024; private String config; private ConfigurationManager configManager; private int signatureLength = 4096; private boolean tailSelected = false; private String sincedbFile = SINCEDB; private boolean debugWatcherSelected = false; private String stopRoute = "/shutdown"; private boolean stopServer = false; private String logfile = null; private String logfileSize = "10MB"; private int logfileNumber = 5; private final Semaphore pauseLock = new Semaphore(1); private final HashMap<Section, FileWatcher> watchers = new HashMap<>(); public static boolean isCaseInsensitiveFileSystem() { return System.getProperty("os.name").toLowerCase().startsWith("win"); } public static String version() { return AGENT_VERSION; } @SuppressWarnings({"UseSpecificCatch", "CallToPrintStackTrace"}) public static void main(String[] args) { try { Server server = new Server(); server.parseOptions(args); if (server.stopServer) { server.sendStop(); return; } server.setupLogging(); server.initializeFileWatchers(); server.startServer(); } catch (Exception e) { e.printStackTrace(); System.exit(3); } } public Server() { } private void startServer() throws IOException { new File(SINCEDB_CAT).mkdir(); httpd = new RouterNanoHTTPD(port); httpd.addRoute("/", RootHandler.class); httpd.addRoute("/ping", PingHandler.class); httpd.addRoute("/version", VersionHandler.class); httpd.addRoute("/pause", PauseServerHandler.class, this); httpd.addRoute("/continue", ContinueServerHandler.class, this); httpd.addRoute("/config", ConfigHandler.class, this); httpd.addRoute("/accessibility", AccessibilityHandler.class, this); httpd.addRoute("/watchmap", WatchMapHandler.class, this);
httpd.addRoute("/logrecords", LogRecordsHandler.class, this);
1
2023-10-11 20:25:12+00:00
24k
giteecode/bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/appllication/BookStockController.java
[ { "identifier": "RedisCache", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/redis/RedisCache.java", "snippet": "@SuppressWarnings(value = { \"unchecked\", \"rawtypes\" })\n@Component\npublic class RedisCache {\n @Autowired\n public RedisTemplate redisTemplate;\n\n /**\n * 缓存基本的对...
import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletResponse; import com.nhXJH.common.core.redis.RedisCache; import com.nhXJH.common.utils.StringUtils; import com.nhXJH.web.domain.BookStock; import com.nhXJH.web.domain.LibraryBook; import com.nhXJH.web.domain.entity.BrowBookCode; import com.nhXJH.web.domain.vo.BookStockVO; import com.nhXJH.web.service.IBookStockService; import com.nhXJH.web.util.CodeUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.checkerframework.checker.units.qual.A; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.connection.RedisServer; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.nhXJH.common.annotation.Log; import com.nhXJH.common.core.controller.BaseController; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.enums.BusinessType; import com.nhXJH.common.utils.poi.ExcelUtil; import com.nhXJH.common.core.page.TableDataInfo;
20,764
package com.nhXJH.web.controller.appllication; /** * 图书库存信息Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/bookStock") @Api(tags = {"图书库存信息"}) public class BookStockController extends BaseController { @Autowired private IBookStockService bookStockService; @Autowired private RedisCache redis; @Value("${brow.book.timeout:5}") private Integer browBookCodeTimeout; /** * 查询图书库存信息列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:stock:list')") @GetMapping("/list") @ApiOperation(value ="查询图书库存信息列表",notes = "查询图书库存信息列表") public TableDataInfo list(BookStock bookStock) { startPage(); List<BookStock> list = bookStockService.selectBookStockList(bookStock); return getDataTable(list); } /** * 获取图书借阅码 */ @GetMapping("/getCode") @ApiOperation(value ="查询图书库存信息列表",notes = "查询图书库存信息列表") public AjaxResult getCode(LibraryBook book) { BrowBookCode browBookCode = new BrowBookCode(); browBookCode.setUserId(getUserId()); browBookCode = bookStockService.selectBookStockList(book,browBookCode); String key = browBookCode.getCode()+"_"+getUserId();
package com.nhXJH.web.controller.appllication; /** * 图书库存信息Controller * * @author xjh * @date 2022-01-25 */ @RestController @RequestMapping("/userApplication/bookStock") @Api(tags = {"图书库存信息"}) public class BookStockController extends BaseController { @Autowired private IBookStockService bookStockService; @Autowired private RedisCache redis; @Value("${brow.book.timeout:5}") private Integer browBookCodeTimeout; /** * 查询图书库存信息列表 */ @PreAuthorize("@ss.hasAnyRoles('libraryAdmin,admin')") //@PreAuthorize("@ss.hasPermi('userApplication:stock:list')") @GetMapping("/list") @ApiOperation(value ="查询图书库存信息列表",notes = "查询图书库存信息列表") public TableDataInfo list(BookStock bookStock) { startPage(); List<BookStock> list = bookStockService.selectBookStockList(bookStock); return getDataTable(list); } /** * 获取图书借阅码 */ @GetMapping("/getCode") @ApiOperation(value ="查询图书库存信息列表",notes = "查询图书库存信息列表") public AjaxResult getCode(LibraryBook book) { BrowBookCode browBookCode = new BrowBookCode(); browBookCode.setUserId(getUserId()); browBookCode = bookStockService.selectBookStockList(book,browBookCode); String key = browBookCode.getCode()+"_"+getUserId();
if(StringUtils.isNull(redis.getCacheObject(key))) {
1
2023-10-13 07:19:20+00:00
24k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/tardis/control/impl/DimensionControl.java
[ { "identifier": "Control", "path": "src/main/java/mdteam/ait/tardis/control/Control.java", "snippet": "public class Control {\n\n /*public static HashMap<Integer, ControlAnimationState> animationStates = HartnellAnimations.animationStatePerControl(listOfControlAnimations());\n\n// Start animation for...
import mdteam.ait.tardis.control.Control; import mdteam.ait.tardis.control.impl.pos.PosType; import mdteam.ait.tardis.util.TardisUtil; import mdteam.ait.tardis.util.AbsoluteBlockPos; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.client.world.ClientWorld; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.text.Text; import net.minecraft.world.World; import mdteam.ait.tardis.Tardis; import mdteam.ait.tardis.TardisTravel; import java.util.ArrayList; import java.util.List; import java.util.Objects;
17,955
package mdteam.ait.tardis.control.impl; public class DimensionControl extends Control { public DimensionControl() { super("dimension"); } @Override public boolean runServer(Tardis tardis, ServerPlayerEntity player, ServerWorld world) { TardisTravel travel = tardis.getTravel();
package mdteam.ait.tardis.control.impl; public class DimensionControl extends Control { public DimensionControl() { super("dimension"); } @Override public boolean runServer(Tardis tardis, ServerPlayerEntity player, ServerWorld world) { TardisTravel travel = tardis.getTravel();
AbsoluteBlockPos.Directed dest = travel.getDestination();
3
2023-10-08 00:38:53+00:00
24k
jianjian3219/044_bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/appllication/LibraryBookController.java
[ { "identifier": "SysUser", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/entity/SysUser.java", "snippet": "public class SysUser extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 用户ID */\n @Excel(name = \"用户序号\", cellType = ColumnType.NUMERIC, pro...
import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.nhXJH.common.core.domain.entity.SysUser; import com.nhXJH.common.core.domain.model.LoginUser; import com.nhXJH.system.service.ISysUserService; import com.nhXJH.web.domain.BaseFile; import com.nhXJH.web.domain.LibraryBook; import com.nhXJH.web.domain.dto.LibraryBookDto; import com.nhXJH.web.domain.dto.SearchBookDto; import com.nhXJH.web.domain.param.BookFileParam; import com.nhXJH.web.domain.vo.BookVO; import com.nhXJH.web.service.ILibraryBookService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.aspectj.weaver.loadtime.Aj; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.nhXJH.common.annotation.Log; import com.nhXJH.common.core.controller.BaseController; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.enums.BusinessType; import com.nhXJH.common.utils.poi.ExcelUtil; import com.nhXJH.common.core.page.TableDataInfo; import org.springframework.web.multipart.MultipartFile;
20,898
package com.nhXJH.web.controller.appllication; /** * 图书实体信息Controller * * @author xjh * @date 2022-02-07 */ @RestController @RequestMapping("/userApplication/book") @Api(tags = {"图书实体信息"}) public class LibraryBookController extends BaseController { @Autowired private ILibraryBookService libraryBookService; @Autowired private ISysUserService userService; /** * 查询图书实体信息列表 */ @PreAuthorize("@ss.hasPermi('userApplication:book:list')") @GetMapping("/list") @ApiOperation(value ="查询图书实体信息列表",notes = "查询图书实体信息列表") public TableDataInfo list(LibraryBook libraryBook) { startPage(); List<LibraryBookDto> list = libraryBookService.selectLibraryBookDtoList(libraryBook);//selectLibraryBookList return getDataTable(list); } /** * 图书搜索 */ @PostMapping("/getBook") @ApiOperation(value ="查询图书实体信息列表",notes = "查询图书实体信息列表") public TableDataInfo getBook( @RequestBody SearchBookDto dto) { return libraryBookService.getBook(dto); } /** * 导出图书实体信息列表 */ @PreAuthorize("@ss.hasPermi('userApplication:book:export')")
package com.nhXJH.web.controller.appllication; /** * 图书实体信息Controller * * @author xjh * @date 2022-02-07 */ @RestController @RequestMapping("/userApplication/book") @Api(tags = {"图书实体信息"}) public class LibraryBookController extends BaseController { @Autowired private ILibraryBookService libraryBookService; @Autowired private ISysUserService userService; /** * 查询图书实体信息列表 */ @PreAuthorize("@ss.hasPermi('userApplication:book:list')") @GetMapping("/list") @ApiOperation(value ="查询图书实体信息列表",notes = "查询图书实体信息列表") public TableDataInfo list(LibraryBook libraryBook) { startPage(); List<LibraryBookDto> list = libraryBookService.selectLibraryBookDtoList(libraryBook);//selectLibraryBookList return getDataTable(list); } /** * 图书搜索 */ @PostMapping("/getBook") @ApiOperation(value ="查询图书实体信息列表",notes = "查询图书实体信息列表") public TableDataInfo getBook( @RequestBody SearchBookDto dto) { return libraryBookService.getBook(dto); } /** * 导出图书实体信息列表 */ @PreAuthorize("@ss.hasPermi('userApplication:book:export')")
@Log(title = "图书实体信息", businessType = BusinessType.EXPORT)
11
2023-10-14 04:57:42+00:00
24k
codegrits/CodeGRITS
src/main/java/actions/StartStopTrackingAction.java
[ { "identifier": "ConfigDialog", "path": "src/main/java/components/ConfigDialog.java", "snippet": "public class ConfigDialog extends DialogWrapper {\n\n private List<JCheckBox> checkBoxes;\n\n private final JPanel panel = new JPanel();\n private static List<JTextField> labelAreas = new ArrayList...
import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import components.ConfigDialog; import entity.Config; import org.jetbrains.annotations.NotNull; import trackers.EyeTracker; import trackers.IDETracker; import trackers.ScreenRecorder; import utils.AvailabilityChecker; import javax.swing.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.IOException; import java.util.Objects;
17,582
package actions; /** * This class is the action for starting/stopping tracking. */ public class StartStopTrackingAction extends AnAction { /** * This variable indicates whether the tracking is started. */ private static boolean isTracking = false; /** * This variable is the IDE tracker. */ private static IDETracker iDETracker; /** * This variable is the eye tracker. */
package actions; /** * This class is the action for starting/stopping tracking. */ public class StartStopTrackingAction extends AnAction { /** * This variable indicates whether the tracking is started. */ private static boolean isTracking = false; /** * This variable is the IDE tracker. */ private static IDETracker iDETracker; /** * This variable is the eye tracker. */
private static EyeTracker eyeTracker;
2
2023-10-12 15:40:39+00:00
24k
giteecode/supermarket2Public
src/main/java/com/ruoyi/project/system/config/service/ConfigServiceImpl.java
[ { "identifier": "Constants", "path": "src/main/java/com/ruoyi/common/constant/Constants.java", "snippet": "public class Constants\n{\n /**\n * UTF-8 字符集\n */\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n public static final String GBK = \"GBK\";\n\...
import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.CacheUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.ShiroUtils; import com.ruoyi.common.utils.text.Convert; import com.ruoyi.project.system.config.domain.Config; import com.ruoyi.project.system.config.mapper.ConfigMapper;
17,394
package com.ruoyi.project.system.config.service; /** * 参数配置 服务层实现 * * @author ruoyi */ @Service public class ConfigServiceImpl implements IConfigService { @Autowired private ConfigMapper configMapper; /** * 项目启动时,初始化参数到缓存 */ @PostConstruct public void init() { loadingConfigCache(); } /** * 查询参数配置信息 * * @param configId 参数配置ID * @return 参数配置信息 */ @Override public Config selectConfigById(Long configId) { Config config = new Config(); config.setConfigId(configId); return configMapper.selectConfig(config); } /** * 根据键名查询参数配置信息 * * @param configKey 参数名称 * @return 参数键值 */ @Override public String selectConfigByKey(String configKey) {
package com.ruoyi.project.system.config.service; /** * 参数配置 服务层实现 * * @author ruoyi */ @Service public class ConfigServiceImpl implements IConfigService { @Autowired private ConfigMapper configMapper; /** * 项目启动时,初始化参数到缓存 */ @PostConstruct public void init() { loadingConfigCache(); } /** * 查询参数配置信息 * * @param configId 参数配置ID * @return 参数配置信息 */ @Override public Config selectConfigById(Long configId) { Config config = new Config(); config.setConfigId(configId); return configMapper.selectConfig(config); } /** * 根据键名查询参数配置信息 * * @param configKey 参数名称 * @return 参数键值 */ @Override public String selectConfigByKey(String configKey) {
String configValue = Convert.toStr(CacheUtils.get(getCacheName(), getCacheKey(configKey)));
6
2023-10-14 02:27:47+00:00
24k
lukas-mb/ABAP-SQL-Beautifier
ABAP SQL Beautifier/src/com/abap/sql/beautifier/StatementProcessor.java
[ { "identifier": "PreferenceConstants", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/preferences/PreferenceConstants.java", "snippet": "public class PreferenceConstants {\n\n\tpublic static final String ALLIGN_OPERS = \"ALLIGN_OPERS\";\n\n\tpublic static final String COMBINE_CHAR_LIMIT = \"CO...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext; import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; import org.eclipse.jface.text.source.Annotation; import org.eclipse.ui.PlatformUI; import com.abap.sql.beautifier.preferences.PreferenceConstants; import com.abap.sql.beautifier.settings.AbstractSqlSetting; import com.abap.sql.beautifier.settings.CommentsAdder; import com.abap.sql.beautifier.settings.ConditionAligner; import com.abap.sql.beautifier.settings.JoinCombiner; import com.abap.sql.beautifier.settings.OperatorUnifier; import com.abap.sql.beautifier.settings.Restructor; import com.abap.sql.beautifier.settings.SelectCombiner; import com.abap.sql.beautifier.settings.SpaceAdder; import com.abap.sql.beautifier.statement.AbapSql; import com.abap.sql.beautifier.utility.BeautifierIcon; import com.abap.sql.beautifier.utility.Utility; import com.sap.adt.tools.abapsource.ui.AbapSourceUi; import com.sap.adt.tools.abapsource.ui.IAbapSourceUi; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices.Token; import com.sap.adt.tools.abapsource.ui.sources.editors.AbapSourcePage;
14,459
if (!scannerServices.isComment(document, t.offset)) { firstToken = t.toString(); // offset of last dot and startReplacement could be different startReplacement = t.offset; try { int line = document.getLineOfOffset(startReplacement); int lineOffset = document.getLineOffset(line); diff = startReplacement - lineOffset; } catch (BadLocationException e) { e.printStackTrace(); } break; } } if (firstToken != null) { if (firstToken.equalsIgnoreCase(Abap.SELECT)) { sql = code.substring(startReplacement, end); String sqlHelper = sql.replaceAll(",", ""); sqlHelper = Utility.cleanString(sqlHelper); List<String> customTokens = Arrays.asList(sqlHelper.split(" ")); if (customTokens.size() > 2) { // check if old or new syntax String secToken = customTokens.get(1).toString().toUpperCase(); String thirdToken = customTokens.get(2).toString().toUpperCase(); if (secToken.equals(Abap.FROM) || (secToken.equals(Abap.SINGLE) && thirdToken.equals(Abap.FROM))) { this.oldSyntax = false; } } // TODO // check if second SELECT or WHEN in statement --> not working currently in this // plugin // check if it contains multiple 'select' or 'when' // when? if (sql.toUpperCase().contains(" WHEN ")) { return false; } // mult. select? int count = Utility.countKeyword(sql, Abap.SELECT); if (count <= 1) { return true; } } } } return false; } @Override public boolean canFix(Annotation annotation) { return true; } @Override public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) { List<ICompletionProposal> proposals = new ArrayList<>(); if (canAssist(invocationContext)) { int replaceLength = end - startReplacement + 1; String beautifulSql = ""; String convertedSql = ""; try { beautifulSql = beautifyStatement(sql); if (this.oldSyntax) { // convertedSql = convertToNewSyntax(beautifulSql); } } catch (Exception e) { // to avoid 'disturbing' other plugins with other proposals if there is a bug e.printStackTrace(); return null; } String descBeautify = "Beautify this SQL statement depending on the settings in your preferences."; BeautifyProposal beautifyProp = new BeautifyProposal(beautifulSql, startReplacement, replaceLength, 0, BeautifierIcon.get(), "Beautify SQL-Statement", null, descBeautify); proposals.add(beautifyProp); // if (this.oldSyntax) { // CompletionProposal conversionProp = new CompletionProposal(convertedSql, startReplacement, // replaceLength, 0, BeautifierIcon.get(), "Convert SQL-Statement", null, // "Convert this SQL statement to the new syntax depending on the settings in your preferences."); // // proposals.add(conversionProp); // } return proposals.toArray(new ICompletionProposal[proposals.size()]); } return null; } @Override public String getErrorMessage() { return null; } private List<AbstractSqlSetting> generateSettings() { List<AbstractSqlSetting> settings = new ArrayList<>(); settings.add(new Restructor());
package com.abap.sql.beautifier; public class StatementProcessor implements IQuickAssistProcessor { public IDocument document = null; public IAbapSourceScannerServices scannerServices = null; public AbapSourcePage sourcePage; public IAbapSourceUi sourceUi = null; private String sql = ""; private String code; private int diff; private int end; private int offsetCursor; private int startReplacement; private boolean oldSyntax = true; private String beautifyStatement(String inputCode) { // otherwise the whole beautifier would not work inputCode = inputCode.toUpperCase(); AbapSql abapSql = new AbapSql(inputCode, diff); System.out.println("=================================="); System.out.println("Input"); System.out.println(inputCode); List<AbstractSqlSetting> settings = generateSettings(); // apply settings for (AbstractSqlSetting setting : settings) { System.out.println("=================================="); System.out.println(setting.getClass().getSimpleName()); setting.setAbapSql(abapSql); setting.apply(); abapSql = setting.getAbapSql(); System.out.println(abapSql.toString()); } abapSql.setPoint(); String outputCode = abapSql.toString(); // delete last empty row if (outputCode.endsWith("\r\n")) { outputCode = outputCode.substring(0, outputCode.length() - "\r\n".length()); } System.out.println("=================================="); System.out.println("Output"); System.out.println(outputCode); return outputCode; } @Override public boolean canAssist(IQuickAssistInvocationContext invocationContext) { // get part of code and check if the current code part is a sql statement document = invocationContext.getSourceViewer().getDocument(); sourceUi = AbapSourceUi.getInstance(); scannerServices = sourceUi.getSourceScannerServices(); sourcePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() .getAdapter(AbapSourcePage.class); code = document.get(); // offset of current cursor offsetCursor = invocationContext.getOffset(); // get offset of last and next dot int start = scannerServices.goBackToDot(document, offsetCursor) + 1; end = scannerServices.goForwardToDot(document, offsetCursor); // all words in selected code List<Token> statementTokens = scannerServices.getStatementTokens(document, start); // check first word if (statementTokens.size() > 0) { String firstToken = null; // get first non comment token for (int i = 0; i < statementTokens.size(); i++) { Token t = statementTokens.get(i); if (!scannerServices.isComment(document, t.offset)) { firstToken = t.toString(); // offset of last dot and startReplacement could be different startReplacement = t.offset; try { int line = document.getLineOfOffset(startReplacement); int lineOffset = document.getLineOffset(line); diff = startReplacement - lineOffset; } catch (BadLocationException e) { e.printStackTrace(); } break; } } if (firstToken != null) { if (firstToken.equalsIgnoreCase(Abap.SELECT)) { sql = code.substring(startReplacement, end); String sqlHelper = sql.replaceAll(",", ""); sqlHelper = Utility.cleanString(sqlHelper); List<String> customTokens = Arrays.asList(sqlHelper.split(" ")); if (customTokens.size() > 2) { // check if old or new syntax String secToken = customTokens.get(1).toString().toUpperCase(); String thirdToken = customTokens.get(2).toString().toUpperCase(); if (secToken.equals(Abap.FROM) || (secToken.equals(Abap.SINGLE) && thirdToken.equals(Abap.FROM))) { this.oldSyntax = false; } } // TODO // check if second SELECT or WHEN in statement --> not working currently in this // plugin // check if it contains multiple 'select' or 'when' // when? if (sql.toUpperCase().contains(" WHEN ")) { return false; } // mult. select? int count = Utility.countKeyword(sql, Abap.SELECT); if (count <= 1) { return true; } } } } return false; } @Override public boolean canFix(Annotation annotation) { return true; } @Override public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) { List<ICompletionProposal> proposals = new ArrayList<>(); if (canAssist(invocationContext)) { int replaceLength = end - startReplacement + 1; String beautifulSql = ""; String convertedSql = ""; try { beautifulSql = beautifyStatement(sql); if (this.oldSyntax) { // convertedSql = convertToNewSyntax(beautifulSql); } } catch (Exception e) { // to avoid 'disturbing' other plugins with other proposals if there is a bug e.printStackTrace(); return null; } String descBeautify = "Beautify this SQL statement depending on the settings in your preferences."; BeautifyProposal beautifyProp = new BeautifyProposal(beautifulSql, startReplacement, replaceLength, 0, BeautifierIcon.get(), "Beautify SQL-Statement", null, descBeautify); proposals.add(beautifyProp); // if (this.oldSyntax) { // CompletionProposal conversionProp = new CompletionProposal(convertedSql, startReplacement, // replaceLength, 0, BeautifierIcon.get(), "Convert SQL-Statement", null, // "Convert this SQL statement to the new syntax depending on the settings in your preferences."); // // proposals.add(conversionProp); // } return proposals.toArray(new ICompletionProposal[proposals.size()]); } return null; } @Override public String getErrorMessage() { return null; } private List<AbstractSqlSetting> generateSettings() { List<AbstractSqlSetting> settings = new ArrayList<>(); settings.add(new Restructor());
settings.add(new OperatorUnifier());
5
2023-10-10 18:56:27+00:00
24k
Spider-Admin/Frost
src/main/java/frost/messaging/freetalk/FreetalkManager.java
[ { "identifier": "Core", "path": "src/main/java/frost/Core.java", "snippet": "public class Core {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(Core.class);\r\n\r\n // Core instanciates itself, frostSettings must be created before instance=Core() !\r\n public static final Se...
import frost.fcp.fcp07.freetalk.FcpFreetalkConnection; import frost.messaging.freetalk.identities.FreetalkOwnIdentity; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import frost.Core; import frost.SettingsClass; import frost.fcp.FcpHandler; import frost.fcp.NodeAddress;
20,565
/* FreetalkManager.java / Frost Copyright (C) 2009 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.messaging.freetalk; public class FreetalkManager { private static final Logger logger = LoggerFactory.getLogger(FreetalkManager.class); private FcpFreetalkConnection fcpFreetalkConnection = null; private static FreetalkManager instance = null; private final List<FreetalkOwnIdentity> ownIdentityList = new ArrayList<FreetalkOwnIdentity>(); private FreetalkManager() { try { if (FcpHandler.inst().getFreenetNode() == null) { throw new Exception("No freenet nodes defined"); }
/* FreetalkManager.java / Frost Copyright (C) 2009 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.messaging.freetalk; public class FreetalkManager { private static final Logger logger = LoggerFactory.getLogger(FreetalkManager.class); private FcpFreetalkConnection fcpFreetalkConnection = null; private static FreetalkManager instance = null; private final List<FreetalkOwnIdentity> ownIdentityList = new ArrayList<FreetalkOwnIdentity>(); private FreetalkManager() { try { if (FcpHandler.inst().getFreenetNode() == null) { throw new Exception("No freenet nodes defined"); }
final NodeAddress na = FcpHandler.inst().getFreenetNode();
3
2023-10-07 22:25:20+00:00
24k
Gaia3D/mago-3d-tiler
tiler/src/main/java/com/gaia3d/process/postprocess/batch/Batched3DModel.java
[ { "identifier": "GaiaSet", "path": "core/src/main/java/com/gaia3d/basic/exchangable/GaiaSet.java", "snippet": "@Slf4j\n@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class GaiaSet {\n List<GaiaBufferDataSet> bufferDatas;\n List<GaiaMaterial> materials;\n\n private Matrix4d tr...
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.gaia3d.basic.exchangable.GaiaSet; import com.gaia3d.basic.geometry.GaiaBoundingBox; import com.gaia3d.basic.structure.GaiaScene; import com.gaia3d.converter.jgltf.GltfWriter; import com.gaia3d.process.ProcessOptions; import com.gaia3d.process.postprocess.TileModel; import com.gaia3d.process.postprocess.instance.GaiaFeatureTable; import com.gaia3d.process.tileprocess.tile.ContentInfo; import com.gaia3d.process.tileprocess.tile.TileInfo; import com.gaia3d.util.DecimalUtils; import com.gaia3d.util.io.LittleEndianDataInputStream; import com.gaia3d.util.io.LittleEndianDataOutputStream; import lombok.extern.slf4j.Slf4j; import org.apache.commons.cli.CommandLine; import org.lwjgl.BufferUtils; import java.io.*; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.util.List;
15,869
package com.gaia3d.process.postprocess.batch; @Slf4j public class Batched3DModel implements TileModel { private static final String MAGIC = "b3dm"; private static final int VERSION = 1; private final GltfWriter gltfWriter; private final CommandLine command; public Batched3DModel(CommandLine command) { this.gltfWriter = new GltfWriter(); this.command = command; } @Override public ContentInfo run(ContentInfo contentInfo) { GaiaSet batchedSet = contentInfo.getBatchedSet(); int featureTableJSONByteLength; int batchTableJSONByteLength; String featureTableJson; String batchTableJson; String nodeCode = contentInfo.getNodeCode(); List<TileInfo> tileInfos = contentInfo.getTileInfos(); int batchLength = tileInfos.size(); List<String> projectNames = tileInfos.stream() .map((tileInfo) -> tileInfo.getSet().getProjectName()) .toList(); List<String> nodeNames = tileInfos.stream() .map(TileInfo::getName) .toList(); List<Double> geometricErrors = tileInfos.stream() .map((tileInfo) -> tileInfo.getBoundingBox().getLongestDistance()) .toList(); List<Double> heights = tileInfos.stream() .map((tileInfo) -> { GaiaBoundingBox boundingBox = tileInfo.getBoundingBox(); return boundingBox.getMaxZ() - boundingBox.getMinZ(); }) .toList(); GaiaScene scene = new GaiaScene(batchedSet); File outputFile = new File(command.getOptionValue(ProcessOptions.OUTPUT.getArgName())); Path outputRoot = outputFile.toPath().resolve("data"); if (outputRoot.toFile().mkdir()) { log.info("Create directory: {}", outputRoot); } byte[] glbBytes; if (command.hasOption(ProcessOptions.DEBUG_GLTF.getArgName())) { String glbFileName = nodeCode + ".gltf"; File glbOutputFile = outputRoot.resolve(glbFileName).toFile(); this.gltfWriter.writeGltf(scene, glbOutputFile); } if (command.hasOption(ProcessOptions.DEBUG_GLB.getArgName())) { String glbFileName = nodeCode + ".glb"; File glbOutputFile = outputRoot.resolve(glbFileName).toFile(); this.gltfWriter.writeGlb(scene, glbOutputFile); glbBytes = readGlb(glbOutputFile); } else { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); this.gltfWriter.writeGlb(scene, byteArrayOutputStream); glbBytes = byteArrayOutputStream.toByteArray(); } scene = null; //this.gltfWriter = null; GaiaFeatureTable featureTable = new GaiaFeatureTable(); featureTable.setBatchLength(batchLength); GaiaBatchTable batchTable = new GaiaBatchTable(); for (int i = 0; i < batchLength; i++) { batchTable.getBatchId().add(String.valueOf(i)); batchTable.getProejctName().add(projectNames.get(i)); batchTable.getNodeName().add(nodeNames.get(i)); batchTable.getGeometricError().add(DecimalUtils.cut(geometricErrors.get(i))); batchTable.getHeight().add(DecimalUtils.cut(heights.get(i))); } ObjectMapper objectMapper = new ObjectMapper(); try { String featureTableText = objectMapper.writeValueAsString(featureTable); featureTableJson = featureTableText; featureTableJSONByteLength = featureTableText.length(); String batchTableText = objectMapper.writeValueAsString(batchTable); batchTableJson = batchTableText; batchTableJSONByteLength = batchTableText.length(); } catch (JsonProcessingException e) { log.error(e.getMessage()); throw new RuntimeException(e); } int byteLength = 28 + featureTableJSONByteLength + batchTableJSONByteLength + glbBytes.length; File b3dmOutputFile = outputRoot.resolve(nodeCode + ".b3dm").toFile(); try (LittleEndianDataOutputStream stream = new LittleEndianDataOutputStream(new BufferedOutputStream(new FileOutputStream(b3dmOutputFile)))) { // 28-byte header (first 20 bytes) stream.writePureText(MAGIC); stream.writeInt(VERSION); stream.writeInt(byteLength); stream.writeInt(featureTableJSONByteLength); int featureTableBinaryByteLength = 0; stream.writeInt(featureTableBinaryByteLength); // 28-byte header (next 8 bytes) stream.writeInt(batchTableJSONByteLength); int batchTableBinaryByteLength = 0; stream.writeInt(batchTableBinaryByteLength); stream.writePureText(featureTableJson); stream.writePureText(batchTableJson); // body stream.write(glbBytes); glbBytes = null; // delete glb file } catch (Exception e) { log.error(e.getMessage()); } return contentInfo; } private byte[] readGlb(File glbOutputFile) { ByteBuffer byteBuffer = readFile(glbOutputFile, true); byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); return bytes; } public void extract(File b3dm, File output) { byte[] glbBytes = null;
package com.gaia3d.process.postprocess.batch; @Slf4j public class Batched3DModel implements TileModel { private static final String MAGIC = "b3dm"; private static final int VERSION = 1; private final GltfWriter gltfWriter; private final CommandLine command; public Batched3DModel(CommandLine command) { this.gltfWriter = new GltfWriter(); this.command = command; } @Override public ContentInfo run(ContentInfo contentInfo) { GaiaSet batchedSet = contentInfo.getBatchedSet(); int featureTableJSONByteLength; int batchTableJSONByteLength; String featureTableJson; String batchTableJson; String nodeCode = contentInfo.getNodeCode(); List<TileInfo> tileInfos = contentInfo.getTileInfos(); int batchLength = tileInfos.size(); List<String> projectNames = tileInfos.stream() .map((tileInfo) -> tileInfo.getSet().getProjectName()) .toList(); List<String> nodeNames = tileInfos.stream() .map(TileInfo::getName) .toList(); List<Double> geometricErrors = tileInfos.stream() .map((tileInfo) -> tileInfo.getBoundingBox().getLongestDistance()) .toList(); List<Double> heights = tileInfos.stream() .map((tileInfo) -> { GaiaBoundingBox boundingBox = tileInfo.getBoundingBox(); return boundingBox.getMaxZ() - boundingBox.getMinZ(); }) .toList(); GaiaScene scene = new GaiaScene(batchedSet); File outputFile = new File(command.getOptionValue(ProcessOptions.OUTPUT.getArgName())); Path outputRoot = outputFile.toPath().resolve("data"); if (outputRoot.toFile().mkdir()) { log.info("Create directory: {}", outputRoot); } byte[] glbBytes; if (command.hasOption(ProcessOptions.DEBUG_GLTF.getArgName())) { String glbFileName = nodeCode + ".gltf"; File glbOutputFile = outputRoot.resolve(glbFileName).toFile(); this.gltfWriter.writeGltf(scene, glbOutputFile); } if (command.hasOption(ProcessOptions.DEBUG_GLB.getArgName())) { String glbFileName = nodeCode + ".glb"; File glbOutputFile = outputRoot.resolve(glbFileName).toFile(); this.gltfWriter.writeGlb(scene, glbOutputFile); glbBytes = readGlb(glbOutputFile); } else { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); this.gltfWriter.writeGlb(scene, byteArrayOutputStream); glbBytes = byteArrayOutputStream.toByteArray(); } scene = null; //this.gltfWriter = null; GaiaFeatureTable featureTable = new GaiaFeatureTable(); featureTable.setBatchLength(batchLength); GaiaBatchTable batchTable = new GaiaBatchTable(); for (int i = 0; i < batchLength; i++) { batchTable.getBatchId().add(String.valueOf(i)); batchTable.getProejctName().add(projectNames.get(i)); batchTable.getNodeName().add(nodeNames.get(i)); batchTable.getGeometricError().add(DecimalUtils.cut(geometricErrors.get(i))); batchTable.getHeight().add(DecimalUtils.cut(heights.get(i))); } ObjectMapper objectMapper = new ObjectMapper(); try { String featureTableText = objectMapper.writeValueAsString(featureTable); featureTableJson = featureTableText; featureTableJSONByteLength = featureTableText.length(); String batchTableText = objectMapper.writeValueAsString(batchTable); batchTableJson = batchTableText; batchTableJSONByteLength = batchTableText.length(); } catch (JsonProcessingException e) { log.error(e.getMessage()); throw new RuntimeException(e); } int byteLength = 28 + featureTableJSONByteLength + batchTableJSONByteLength + glbBytes.length; File b3dmOutputFile = outputRoot.resolve(nodeCode + ".b3dm").toFile(); try (LittleEndianDataOutputStream stream = new LittleEndianDataOutputStream(new BufferedOutputStream(new FileOutputStream(b3dmOutputFile)))) { // 28-byte header (first 20 bytes) stream.writePureText(MAGIC); stream.writeInt(VERSION); stream.writeInt(byteLength); stream.writeInt(featureTableJSONByteLength); int featureTableBinaryByteLength = 0; stream.writeInt(featureTableBinaryByteLength); // 28-byte header (next 8 bytes) stream.writeInt(batchTableJSONByteLength); int batchTableBinaryByteLength = 0; stream.writeInt(batchTableBinaryByteLength); stream.writePureText(featureTableJson); stream.writePureText(batchTableJson); // body stream.write(glbBytes); glbBytes = null; // delete glb file } catch (Exception e) { log.error(e.getMessage()); } return contentInfo; } private byte[] readGlb(File glbOutputFile) { ByteBuffer byteBuffer = readFile(glbOutputFile, true); byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); return bytes; } public void extract(File b3dm, File output) { byte[] glbBytes = null;
try (LittleEndianDataInputStream stream = new LittleEndianDataInputStream(new BufferedInputStream(new FileInputStream(b3dm)))) {
10
2023-11-30 01:59:44+00:00
24k
lidaofu-hub/j_media_server
src/main/java/com/ldf/media/context/MediaServerContext.java
[ { "identifier": "MediaServerConfig", "path": "src/main/java/com/ldf/media/config/MediaServerConfig.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"media\")\npublic class MediaServerConfig {\n\n private Integer thread_num;\n\n private Integer rtmp_port;\n\n private ...
import com.ldf.media.callback.*; import com.ldf.media.config.MediaServerConfig; import com.ldf.media.sdk.core.ZLMApi; import com.ldf.media.sdk.structure.MK_EVENTS; import com.ldf.media.sdk.structure.MK_INI; import com.sun.jna.Native; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy;
15,963
package com.ldf.media.context; /** * 流媒体上下文 * * @author lidaofu * @since 2023/11/28 **/ @Slf4j @Component public class MediaServerContext { @Autowired
package com.ldf.media.context; /** * 流媒体上下文 * * @author lidaofu * @since 2023/11/28 **/ @Slf4j @Component public class MediaServerContext { @Autowired
private MediaServerConfig config;
0
2023-11-29 07:47:56+00:00
24k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/MainLoader.java
[ { "identifier": "DriverType", "path": "core/src/bms/player/beatoraja/AudioConfig.java", "snippet": "\tpublic enum DriverType {\n\n\t\t/**\n\t\t * OpenAL (libGDX Sound)\n\t\t */\n\t\tOpenAL,\n\t\t/**\n\t\t * PortAudio\n\t\t */\n\t\tPortAudio,\n\t\t/**\n\t\t * AudioDevice (libGDX AudioDevice, 未実装)\n\t\t *...
import java.io.*; import java.net.URL; import java.nio.file.*; import java.util.*; import java.util.logging.FileHandler; import java.util.logging.Logger; import javax.swing.JOptionPane; import com.badlogic.gdx.Graphics; import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Graphics; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.ObjectMapper; import imgui.ImGui; import imgui.ImGuiIO; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.VBox; import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application; import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration; import bms.player.beatoraja.AudioConfig.DriverType; import bms.player.beatoraja.ir.IRConnectionManager; import bms.player.beatoraja.launcher.PlayConfigurationView; import bms.player.beatoraja.song.SQLiteSongDatabaseAccessor; import bms.player.beatoraja.song.SongData; import bms.player.beatoraja.song.SongDatabaseAccessor; import bms.player.beatoraja.song.SongUtils; import javafx.stage.Stage;
21,120
package bms.player.beatoraja; /** * 起動用クラス * * @author exch */ public class MainLoader extends Application { private static final boolean ALLOWS_32BIT_JAVA = false; private static SongDatabaseAccessor songdb; private static final Set<String> illegalSongs = new HashSet<String>(); private static Path bmsPath; private static VersionChecker version; //private static Stage configuratorStage; public static void main(String[] args) { if(!ALLOWS_32BIT_JAVA && !System.getProperty( "os.arch" ).contains( "64")) { JOptionPane.showMessageDialog(null, "This Application needs 64bit-Java.", "Error", JOptionPane.ERROR_MESSAGE); System.exit(1); } Logger logger = Logger.getGlobal(); try { logger.addHandler(new FileHandler("beatoraja_log.xml")); } catch (Throwable e) { e.printStackTrace(); } BMSPlayerMode auto = null; for (String s : args) { if (s.startsWith("-")) { if (s.equals("-a")) { auto = BMSPlayerMode.AUTOPLAY; } if (s.equals("-p")) { auto = BMSPlayerMode.PRACTICE; } if (s.equals("-r") || s.equals("-r1")) { auto = BMSPlayerMode.REPLAY_1; } if (s.equals("-r2")) { auto = BMSPlayerMode.REPLAY_2; } if (s.equals("-r3")) { auto = BMSPlayerMode.REPLAY_3; } if (s.equals("-r4")) { auto = BMSPlayerMode.REPLAY_4; } if (s.equals("-s")) { auto = BMSPlayerMode.PLAY; } } else { bmsPath = Paths.get(s); if(auto == null) { auto = BMSPlayerMode.PLAY; } } } if (Files.exists(MainController.configpath) && (bmsPath != null || auto != null)) { IRConnectionManager.getAllAvailableIRConnectionName(); play(bmsPath, auto, true, null, null, bmsPath != null); } else { launch(args); } } public static void play(Path bmsPath, BMSPlayerMode playerMode, boolean forceExit, Config config, PlayerConfig player, boolean songUpdated) { //configuratorStage.setIconified(true); if(config == null) { config = Config.read(); }
package bms.player.beatoraja; /** * 起動用クラス * * @author exch */ public class MainLoader extends Application { private static final boolean ALLOWS_32BIT_JAVA = false; private static SongDatabaseAccessor songdb; private static final Set<String> illegalSongs = new HashSet<String>(); private static Path bmsPath; private static VersionChecker version; //private static Stage configuratorStage; public static void main(String[] args) { if(!ALLOWS_32BIT_JAVA && !System.getProperty( "os.arch" ).contains( "64")) { JOptionPane.showMessageDialog(null, "This Application needs 64bit-Java.", "Error", JOptionPane.ERROR_MESSAGE); System.exit(1); } Logger logger = Logger.getGlobal(); try { logger.addHandler(new FileHandler("beatoraja_log.xml")); } catch (Throwable e) { e.printStackTrace(); } BMSPlayerMode auto = null; for (String s : args) { if (s.startsWith("-")) { if (s.equals("-a")) { auto = BMSPlayerMode.AUTOPLAY; } if (s.equals("-p")) { auto = BMSPlayerMode.PRACTICE; } if (s.equals("-r") || s.equals("-r1")) { auto = BMSPlayerMode.REPLAY_1; } if (s.equals("-r2")) { auto = BMSPlayerMode.REPLAY_2; } if (s.equals("-r3")) { auto = BMSPlayerMode.REPLAY_3; } if (s.equals("-r4")) { auto = BMSPlayerMode.REPLAY_4; } if (s.equals("-s")) { auto = BMSPlayerMode.PLAY; } } else { bmsPath = Paths.get(s); if(auto == null) { auto = BMSPlayerMode.PLAY; } } } if (Files.exists(MainController.configpath) && (bmsPath != null || auto != null)) { IRConnectionManager.getAllAvailableIRConnectionName(); play(bmsPath, auto, true, null, null, bmsPath != null); } else { launch(args); } } public static void play(Path bmsPath, BMSPlayerMode playerMode, boolean forceExit, Config config, PlayerConfig player, boolean songUpdated) { //configuratorStage.setIconified(true); if(config == null) { config = Config.read(); }
for(SongData song : getScoreDatabaseAccessor().getSongDatas(SongUtils.illegalsongs)) {
6
2023-12-02 23:41:17+00:00
24k