hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e1f9f89c728138131a046aacd931788b783f576
2,276
java
Java
easy-jobs-admin/src/main/java/org/jeasy/jobs/admin/web/controller/JobExecutionRequestsController.java
atdavidpark/easy-jobs
6453f6bac1b7648993d2f0340c75055304ab8649
[ "MIT" ]
36
2017-06-19T13:21:43.000Z
2022-03-16T05:00:08.000Z
easy-jobs-admin/src/main/java/org/jeasy/jobs/admin/web/controller/JobExecutionRequestsController.java
j-easy/easy-jobs
6453f6bac1b7648993d2f0340c75055304ab8649
[ "MIT" ]
28
2017-06-27T18:28:58.000Z
2020-11-19T21:22:37.000Z
easy-jobs-admin/src/main/java/org/jeasy/jobs/admin/web/controller/JobExecutionRequestsController.java
atdavidpark/easy-jobs
6453f6bac1b7648993d2f0340c75055304ab8649
[ "MIT" ]
28
2017-05-21T06:47:20.000Z
2022-03-17T04:07:33.000Z
33.970149
104
0.740773
13,355
package org.jeasy.jobs.admin.web.controller; import org.jeasy.jobs.job.Job; import org.jeasy.jobs.job.JobRepository; import org.jeasy.jobs.request.JobExecutionRequest; import org.jeasy.jobs.request.JobExecutionRequestRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.List; import static java.lang.Integer.parseInt; @Controller public class JobExecutionRequestsController extends AbstractController { @Autowired private JobRepository jobRepository; @Autowired private JobExecutionRequestRepository jobExecutionRequestRepository; @RequestMapping("/requests") public ModelAndView requests() { ModelAndView modelAndView = new ModelAndView("requests"); modelAndView.addObject("requests", jobExecutionRequestRepository.findAllJobExecutionRequests()); return modelAndView; } @RequestMapping(path = "/requests/new", method = RequestMethod.GET) public ModelAndView newJobExecutionRequestForm() { ModelAndView modelAndView = new ModelAndView("new-request"); List<Job> jobs = jobRepository.findAll(); if (!jobs.isEmpty()) { modelAndView.addObject("jobs", jobs); } else { modelAndView.addObject("disabled", true); } return modelAndView; } @RequestMapping(path = "/requests/new", method = RequestMethod.POST) public ModelAndView createNewJobExecutionRequest(HttpServletRequest request) { String jobId = request.getParameter("jobId"); String jobParameters = request.getParameter("jobParameters"); jobExecutionRequestRepository.save(new JobExecutionRequest(parseInt(jobId), jobParameters)); return requests(); } @ModelAttribute("title") public String title() { return "Job execution requests"; } @ModelAttribute("requestsPageActive") public boolean isActive() { return true; } }
3e1f9f97c2fea4565806283dc44512fea5586e8e
10,774
java
Java
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilter.java
dlehammer/elasticsearch
f09190c14d28c04c937e6ceb2f01b381a1369ac8
[ "Apache-2.0" ]
49
2017-05-19T04:43:12.000Z
2021-07-03T05:59:26.000Z
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilter.java
dlehammer/elasticsearch
f09190c14d28c04c937e6ceb2f01b381a1369ac8
[ "Apache-2.0" ]
3
2018-06-07T06:52:21.000Z
2020-11-29T02:42:44.000Z
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilter.java
dlehammer/elasticsearch
f09190c14d28c04c937e6ceb2f01b381a1369ac8
[ "Apache-2.0" ]
39
2017-04-02T16:15:51.000Z
2020-02-03T14:37:28.000Z
58.237838
140
0.672452
13,356
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.security.action.filter; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.admin.indices.close.CloseIndexAction; import org.elasticsearch.action.admin.indices.delete.DeleteIndexAction; import org.elasticsearch.action.admin.indices.open.OpenIndexAction; import org.elasticsearch.action.support.ActionFilter; import org.elasticsearch.action.support.ActionFilterChain; import org.elasticsearch.action.support.ContextPreservingActionListener; import org.elasticsearch.action.support.DestructiveOperations; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.license.LicenseUtils; import org.elasticsearch.license.XPackLicenseState; import org.elasticsearch.tasks.Task; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.xpack.core.XPackField; import org.elasticsearch.xpack.core.security.SecurityContext; import org.elasticsearch.xpack.core.security.authc.Authentication; import org.elasticsearch.xpack.core.security.authz.privilege.HealthAndStatsPrivilege; import org.elasticsearch.xpack.core.security.support.Automatons; import org.elasticsearch.xpack.core.security.user.SystemUser; import org.elasticsearch.xpack.security.action.SecurityActionMapper; import org.elasticsearch.xpack.security.action.interceptor.RequestInterceptor; import org.elasticsearch.xpack.security.authc.AuthenticationService; import org.elasticsearch.xpack.security.authz.AuthorizationService; import org.elasticsearch.xpack.security.authz.AuthorizationUtils; import java.io.IOException; import java.util.Set; import java.util.function.Predicate; public class SecurityActionFilter extends AbstractComponent implements ActionFilter { private static final Predicate<String> LICENSE_EXPIRATION_ACTION_MATCHER = HealthAndStatsPrivilege.INSTANCE.predicate(); private static final Predicate<String> SECURITY_ACTION_MATCHER = Automatons.predicate("cluster:admin/xpack/security*"); private final AuthenticationService authcService; private final AuthorizationService authzService; private final SecurityActionMapper actionMapper = new SecurityActionMapper(); private final Set<RequestInterceptor> requestInterceptors; private final XPackLicenseState licenseState; private final ThreadContext threadContext; private final SecurityContext securityContext; private final DestructiveOperations destructiveOperations; public SecurityActionFilter(Settings settings, AuthenticationService authcService, AuthorizationService authzService, XPackLicenseState licenseState, Set<RequestInterceptor> requestInterceptors, ThreadPool threadPool, SecurityContext securityContext, DestructiveOperations destructiveOperations) { super(settings); this.authcService = authcService; this.authzService = authzService; this.licenseState = licenseState; this.requestInterceptors = requestInterceptors; this.threadContext = threadPool.getThreadContext(); this.securityContext = securityContext; this.destructiveOperations = destructiveOperations; } @Override public <Request extends ActionRequest, Response extends ActionResponse> void apply(Task task, String action, Request request, ActionListener<Response> listener, ActionFilterChain<Request, Response> chain) { /* A functional requirement - when the license of security is disabled (invalid/expires), security will continue to operate normally, except all read operations will be blocked. */ if (licenseState.isStatsAndHealthAllowed() == false && LICENSE_EXPIRATION_ACTION_MATCHER.test(action)) { logger.error("blocking [{}] operation due to expired license. Cluster health, cluster stats and indices stats \n" + "operations are blocked on license expiration. All data operations (read and write) continue to work. \n" + "If you have a new license, please update it. Otherwise, please reach out to your support contact.", action); throw LicenseUtils.newComplianceException(XPackField.SECURITY); } if (licenseState.isAuthAllowed()) { final ActionListener<Response> contextPreservingListener = ContextPreservingActionListener.wrapPreservingContext(listener, threadContext); ActionListener<Void> authenticatedListener = ActionListener.wrap( (aVoid) -> chain.proceed(task, action, request, contextPreservingListener), contextPreservingListener::onFailure); final boolean useSystemUser = AuthorizationUtils.shouldReplaceUserWithSystem(threadContext, action); try { if (useSystemUser) { securityContext.executeAsUser(SystemUser.INSTANCE, (original) -> { try { applyInternal(action, request, authenticatedListener); } catch (IOException e) { listener.onFailure(e); } }, Version.CURRENT); } else if (AuthorizationUtils.shouldSetUserBasedOnActionOrigin(threadContext)) { AuthorizationUtils.switchUserBasedOnActionOriginAndExecute(threadContext, securityContext, (original) -> { try { applyInternal(action, request, authenticatedListener); } catch (IOException e) { listener.onFailure(e); } }); } else { try (ThreadContext.StoredContext ignore = threadContext.newStoredContext(true)) { applyInternal(action, request, authenticatedListener); } } } catch (Exception e) { listener.onFailure(e); } } else if (SECURITY_ACTION_MATCHER.test(action)) { if (licenseState.isSecurityDisabledByTrialLicense()) { listener.onFailure(new ElasticsearchException("Security must be explicitly enabled when using a trial license. " + "Enable security by setting [xpack.security.enabled] to [true] in the elasticsearch.yml file " + "and restart the node.")); } else { listener.onFailure(LicenseUtils.newComplianceException(XPackField.SECURITY)); } } else { chain.proceed(task, action, request, listener); } } @Override public int order() { return Integer.MIN_VALUE; } private <Request extends ActionRequest> void applyInternal(String action, Request request, ActionListener<Void> listener) throws IOException { if (CloseIndexAction.NAME.equals(action) || OpenIndexAction.NAME.equals(action) || DeleteIndexAction.NAME.equals(action)) { IndicesRequest indicesRequest = (IndicesRequest) request; try { destructiveOperations.failDestructive(indicesRequest.indices()); } catch(IllegalArgumentException e) { listener.onFailure(e); return; } } /* here we fallback on the system user. Internal system requests are requests that are triggered by the system itself (e.g. pings, update mappings, share relocation, etc...) and were not originated by user interaction. Since these requests are triggered by es core modules, they are security agnostic and therefore not associated with any user. When these requests execute locally, they are executed directly on their relevant action. Since there is no other way a request can make it to the action without an associated user (not via REST or transport - this is taken care of by the {@link Rest} filter and the {@link ServerTransport} filter respectively), it's safe to assume a system user here if a request is not associated with any other user. */ final String securityAction = actionMapper.action(action, request); authcService.authenticate(securityAction, request, SystemUser.INSTANCE, ActionListener.wrap((authc) -> authorizeRequest(authc, securityAction, request, listener), listener::onFailure)); } private <Request extends ActionRequest> void authorizeRequest(Authentication authentication, String securityAction, Request request, ActionListener<Void> listener) { if (authentication == null) { listener.onFailure(new IllegalArgumentException("authentication must be non null for authorization")); } else { final AuthorizationUtils.AsyncAuthorizer asyncAuthorizer = new AuthorizationUtils.AsyncAuthorizer(authentication, listener, (userRoles, runAsRoles) -> { authzService.authorize(authentication, securityAction, request, userRoles, runAsRoles); /* * We use a separate concept for code that needs to be run after authentication and authorization that could * affect the running of the action. This is done to make it more clear of the state of the request. */ for (RequestInterceptor interceptor : requestInterceptors) { if (interceptor.supports(request)) { interceptor.intercept(request, authentication, runAsRoles != null ? runAsRoles : userRoles, securityAction); } } listener.onResponse(null); }); asyncAuthorizer.authorize(authzService); } } }
3e1f9fd80073a1faae3451684eb237435614c17d
1,354
java
Java
core/src/main/java/io/nson/javapt/core/Material.java
jon-hanson/JavaPT
8f7f8fc5501c03758b4a253177230d6052a75778
[ "MIT" ]
null
null
null
core/src/main/java/io/nson/javapt/core/Material.java
jon-hanson/JavaPT
8f7f8fc5501c03758b4a253177230d6052a75778
[ "MIT" ]
2
2021-12-10T06:29:16.000Z
2022-01-04T16:33:28.000Z
core/src/main/java/io/nson/javapt/core/Material.java
jon-hanson/JavaPT
8f7f8fc5501c03758b4a253177230d6052a75778
[ "MIT" ]
null
null
null
22.949153
62
0.572378
13,357
package io.nson.javapt.core; import io.nson.javapt.geom.*; public interface Material { static Material diffuse(double r, double g, double b) { return new Diffuse(new RGB(r, g, b), RGB.BLACK); } static Material diffuse(RGB colour) { return new Diffuse(colour, RGB.BLACK); } static Material emissive(double r, double g, double b) { return new Diffuse(RGB.BLACK, new RGB(r, g, b), true); } static Material emissive(RGB colour) { return new Diffuse(RGB.BLACK, colour, true); } static Material refractive(double r, double g, double b) { return new Refractive(new RGB(r, g, b), RGB.BLACK); } static Material refractive(RGB colour) { return new Refractive(colour, RGB.BLACK); } static Material reflective(double r, double g, double b) { return new Reflective(new RGB(r, g, b), RGB.BLACK); } static Material reflective(RGB colour) { return new Reflective(colour, RGB.BLACK); } RGB colour(); RGB emColour(); default RGB emission() { return emColour(); } RGB radiance( RNG rng, Renderer rdr, Ray ray, int depth, Point3d p, Vector3d n, Vector3d nl, RGB acc, RGB att ); }
3e1f9fe47c1bd3fd90e1e61baf2f4fac2c8da9d6
560
java
Java
src/lib/ui/ios/IOSMyListsPageObject.java
vil-shavetail/JavaAppiumAutomation
93f5be20e04aa59373b56b3cbdd426152b548f53
[ "MIT" ]
null
null
null
src/lib/ui/ios/IOSMyListsPageObject.java
vil-shavetail/JavaAppiumAutomation
93f5be20e04aa59373b56b3cbdd426152b548f53
[ "MIT" ]
null
null
null
src/lib/ui/ios/IOSMyListsPageObject.java
vil-shavetail/JavaAppiumAutomation
93f5be20e04aa59373b56b3cbdd426152b548f53
[ "MIT" ]
null
null
null
32.941176
84
0.701786
13,358
package lib.ui.ios; import lib.ui.MyListsPageObject; import org.openqa.selenium.remote.RemoteWebDriver; public class IOSMyListsPageObject extends MyListsPageObject { static { FOLDER_BY_NAME_TPL = "xpath://*[@text='{FOLDER_NAME}']"; ARTICLE_BY_TITLE_TPL = "xpath://XCUIElementTypeStaticText[@name='{TITLE}']"; DELETE_LIST_BUTTON = "xpath://*[@text='Delete list']"; MORE_OPTIONS_BUTTON = "id:org.wikipedia:id/item_overflow_menu"; } public IOSMyListsPageObject(RemoteWebDriver driver){ super(driver); } }
3e1fa17881f7fcc6a7a847f3f54cac5255d565c0
3,522
java
Java
idcardcamera/src/main/java/com/wildma/idcardcamera/utils/FileUtils.java
mingrq/IDCardCamera-T
0b38907328bc5dab3b26cac551c9e527b78b25fa
[ "Apache-2.0" ]
1
2021-12-19T20:16:53.000Z
2021-12-19T20:16:53.000Z
idcardcamera/src/main/java/com/wildma/idcardcamera/utils/FileUtils.java
mingrq/IDCardCamera-T
0b38907328bc5dab3b26cac551c9e527b78b25fa
[ "Apache-2.0" ]
null
null
null
idcardcamera/src/main/java/com/wildma/idcardcamera/utils/FileUtils.java
mingrq/IDCardCamera-T
0b38907328bc5dab3b26cac551c9e527b78b25fa
[ "Apache-2.0" ]
1
2020-09-17T03:10:49.000Z
2020-09-17T03:10:49.000Z
24.978723
93
0.545997
13,359
package com.wildma.idcardcamera.utils; import android.os.Environment; import java.io.Closeable; import java.io.File; import java.io.IOException; /** * Author wildma * Github https://github.com/wildma * Date 2018/6/10 * Desc ${文件相关工具类} */ public final class FileUtils { /** * 得到SD卡根目录,SD卡不可用则获取内部存储的根目录 */ public static File getRootPath() { File path = null; if (sdCardIsAvailable()) { path = Environment.getExternalStorageDirectory(); //SD卡根目录 /storage/emulated/0 } else { path = Environment.getDataDirectory();//内部存储的根目录 /data } return path; } /** * SD卡是否可用 */ public static boolean sdCardIsAvailable() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File sd = new File(Environment.getExternalStorageDirectory().getPath()); return sd.canWrite(); } else return false; } /** * 判断目录是否存在,不存在则判断是否创建成功 * * @param dirPath 文件路径 * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败 */ public static boolean createOrExistsDir(String dirPath) { return createOrExistsDir(getFileByPath(dirPath)); } /** * 判断目录是否存在,不存在则判断是否创建成功 * * @param file 文件 * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败 */ public static boolean createOrExistsDir(File file) { // 如果存在,是目录则返回true,是文件则返回false,不存在则返回是否创建成功 return file != null && (file.exists() ? file.isDirectory() : file.mkdirs()); } /** * 判断文件是否存在,不存在则判断是否创建成功 * * @param filePath 文件路径 * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败 */ public static boolean createOrExistsFile(String filePath) { return createOrExistsFile(getFileByPath(filePath)); } /** * 判断文件是否存在,不存在则判断是否创建成功 * * @param file 文件 * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败 */ public static boolean createOrExistsFile(File file) { if (file == null) return false; // 如果存在,是文件则返回true,是目录则返回false if (file.exists()) return file.isFile(); if (!createOrExistsDir(file.getParentFile())) return false; try { return file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } } /** * 根据文件路径获取文件 * * @param filePath 文件路径 * @return 文件 */ public static File getFileByPath(String filePath) { return isSpace(filePath) ? null : new File(filePath); } /** * 判断字符串是否为 null 或全为空白字符 * * @param s * @return */ private static boolean isSpace(final String s) { if (s == null) return true; for (int i = 0, len = s.length(); i < len; ++i) { if (!Character.isWhitespace(s.charAt(i))) { return false; } } return true; } /** * 关闭IO * * @param closeables closeable */ public static void closeIO(Closeable... closeables) { if (closeables == null) return; try { for (Closeable closeable : closeables) { if (closeable != null) { closeable.close(); } } } catch (IOException e) { e.printStackTrace(); } } }
3e1fa1a4f22523d45d1f78744dca17b399e45dc8
1,319
java
Java
languages/java/src/topics/camel/P017_CustomComponentMain.java
vikash-india/DeveloperNotes2Myself
fe277a3c52f73884863f2f72b237365b27a8c882
[ "MIT" ]
2
2019-05-25T10:09:00.000Z
2022-03-11T09:06:23.000Z
languages/java/src/topics/camel/P017_CustomComponentMain.java
vikash-india/DeveloperNotes2Myself
fe277a3c52f73884863f2f72b237365b27a8c882
[ "MIT" ]
2
2020-03-31T04:30:17.000Z
2020-10-30T07:54:28.000Z
languages/java/src/topics/camel/P017_CustomComponentMain.java
vikash-india/DeveloperNotes2Myself
fe277a3c52f73884863f2f72b237365b27a8c882
[ "MIT" ]
4
2019-07-12T13:18:56.000Z
2021-11-17T08:04:55.000Z
32.170732
104
0.601213
13,360
package topics.camel; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; import org.apache.log4j.PropertyConfigurator; public class P017_CustomComponentMain { public static void main(String[] args) { // Enable log4J Logging String log4jPropertiesPath = "src/topics/camel/P004_log4j.properties"; PropertyConfigurator.configure(log4jPropertiesPath); CamelContext context = new DefaultCamelContext(); // Register a new component context.addComponent("custom", new P017_CustomComponent()); // Note: Alternatively, copy P017_custom as custom to the directory // DeveloperNotes2Myself/languages/java/src/META-INF/services/org/apache/camel/component/custom try { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("custom://HelloWorld") .to("log:result"); } }); context.start(); Thread.sleep(5000); context.stop(); } catch (Exception e) { System.out.println("Exception: " + e); } } }
3e1fa1cd63d6acceda276b57ed26a06d8442f109
2,848
java
Java
src/main/java/com/github/elgleidson/multi/tenant/schema/config/SecurityConfig.java
fiona-pet/xchange-app
cc26a7f396f6702137b91dcdb8abc136500d66e9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/elgleidson/multi/tenant/schema/config/SecurityConfig.java
fiona-pet/xchange-app
cc26a7f396f6702137b91dcdb8abc136500d66e9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/elgleidson/multi/tenant/schema/config/SecurityConfig.java
fiona-pet/xchange-app
cc26a7f396f6702137b91dcdb8abc136500d66e9
[ "Apache-2.0" ]
null
null
null
38.486486
107
0.811447
13,361
package com.github.elgleidson.multi.tenant.schema.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import com.github.elgleidson.multi.tenant.schema.domain.enumeration.RoleName; import com.github.elgleidson.multi.tenant.schema.security.JwtAuthenticationEntryPoint; import com.github.elgleidson.multi.tenant.schema.security.JwtFilter; import com.github.elgleidson.multi.tenant.schema.service.UserService; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled=true, securedEnabled=true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService usuarioService; @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public JwtFilter jwtFilter() { return new JwtFilter(); }; @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(usuarioService) .passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/admin/**").hasAuthority(RoleName.ROLE_ADMIN.name()) .antMatchers("/api/auth/**").permitAll() .antMatchers("/v2/api-docs/**").permitAll() .antMatchers("/swagger-ui.html").permitAll() .antMatchers("/management/**").permitAll() .antMatchers("/api/**").authenticated(); http.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class); } }
3e1fa1d329a0b73dc0a48c91afec1470f18689a4
842
java
Java
lucky-noxml/src/main/java/com/lucky/jacklamb/authority/shiro/entity/SysBase.java
FK7075/lucky-noxml
9f2f479d88732c92bb16f4194759c5fd39eb6464
[ "WTFPL" ]
3
2020-04-15T15:17:37.000Z
2020-08-31T01:45:57.000Z
lucky-noxml/src/main/java/com/lucky/jacklamb/authority/shiro/entity/SysBase.java
FK7075/lucky-noxml
9f2f479d88732c92bb16f4194759c5fd39eb6464
[ "WTFPL" ]
18
2020-04-02T09:17:06.000Z
2022-02-01T01:03:48.000Z
lucky-noxml/src/main/java/com/lucky/jacklamb/authority/shiro/entity/SysBase.java
FK7075/lucky-noxml
9f2f479d88732c92bb16f4194759c5fd39eb6464
[ "WTFPL" ]
1
2021-06-17T08:45:06.000Z
2021-06-17T08:45:06.000Z
21.589744
63
0.684086
13,362
package com.lucky.jacklamb.authority.shiro.entity; import com.lucky.jacklamb.annotation.orm.Column; import com.lucky.jacklamb.utils.base.LuckyUtils; import java.sql.Timestamp; /** * @author fk7075 * @version 1.0 * @date 2020/10/28 10:07 */ public abstract class SysBase { /** 创建时间*/ @Column("create_time") protected Timestamp createTime= LuckyUtils.getTimestamp();; /** 最近一次更新时间*/ @Column("update_time") protected Timestamp updateTime= LuckyUtils.getTimestamp(); public Timestamp getCreateTime() { return createTime; } public void setCreateTime(Timestamp createTime) { this.createTime = createTime; } public Timestamp getUpdateTime() { return updateTime; } public void setUpdateTime(Timestamp updateTime) { this.updateTime = updateTime; } }
3e1fa38e422f26922e02f9200d038938969b1ce1
2,172
java
Java
src/entities/CreationTemplate.java
harryqhj/csc207-todolist_app
6f3449b0bcb2c3a78b2b0e40e7b773b56ad267e5
[ "MIT" ]
null
null
null
src/entities/CreationTemplate.java
harryqhj/csc207-todolist_app
6f3449b0bcb2c3a78b2b0e40e7b773b56ad267e5
[ "MIT" ]
null
null
null
src/entities/CreationTemplate.java
harryqhj/csc207-todolist_app
6f3449b0bcb2c3a78b2b0e40e7b773b56ad267e5
[ "MIT" ]
null
null
null
25.255814
79
0.609116
13,363
package entities; import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException; import java.io.Serializable; /** * A class that represents a template used by users to make creations. */ public class CreationTemplate implements Serializable { private String name; private String filepath; private String contents; /** * Initializes a CreationTemplate * @param name name of the template * @param filepath filepath that the template file is located in * @param contents contents of the template file */ public CreationTemplate(String name, String filepath, String contents){ this.name = name; this.filepath = filepath; this.contents = contents; } // ============== Getters ================= /** * Get the name of the template * @return name of the template */ public String getName(){ return name; } /** * Get the filepath of the template * @return absolute filepath of the template */ public String getPath(){ return filepath; } /** * Get the contents of the template file * @return contents of template file */ public String getContents(){ return contents; } /** * Get the prompts of the template * @return array containing each prompt contained in the template */ public String[] getPrompts(){ return splitPrompts(getContents()); } // ============== Setters ================= /** * Set new content to a template as content * @param info new content of the template */ public void setContents(String info) throws java.text.ParseException { if (getPrompts().length != splitPrompts(info).length){ throw new ParseException("Number of prompts should not change", 0); } this.contents = info; } /** * Set the name of this template * @param newName new name of the template */ public void setName(String newName){ name = newName; } private String[] splitPrompts(String rawPrompts){ return rawPrompts.split("\n"); } }
3e1fa55af14cb4f435f17b26f57014e0e5305cdc
3,493
java
Java
src/main/java/com/c8db/internal/C8KeyValueImpl.java
Macrometacorp/C84j
05cb270aa5cca25d21d0c5e3ff26b4e006923cf8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/c8db/internal/C8KeyValueImpl.java
Macrometacorp/C84j
05cb270aa5cca25d21d0c5e3ff26b4e006923cf8
[ "Apache-2.0" ]
2
2020-03-04T22:51:56.000Z
2020-05-15T22:00:40.000Z
src/main/java/com/c8db/internal/C8KeyValueImpl.java
Macrometacorp/C84j
05cb270aa5cca25d21d0c5e3ff26b4e006923cf8
[ "Apache-2.0" ]
null
null
null
36.768421
123
0.681649
13,364
/* * Copyright (c) 2022 Macrometa Corp All rights reserved. */ package com.c8db.internal; import com.c8db.C8DBException; import com.c8db.C8KeyValue; import com.c8db.entity.MultiDocumentEntity; import com.c8db.entity.BaseKeyValue; import com.c8db.entity.C8KVEntity; import com.c8db.entity.DocumentCreateEntity; import com.c8db.entity.DocumentDeleteEntity; import com.c8db.internal.util.DocumentUtil; import com.c8db.model.C8KVPairReadOptions; import com.c8db.model.CollectionCreateOptions; import com.c8db.model.DocumentCreateOptions; import com.c8db.model.DocumentDeleteOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; public class C8KeyValueImpl extends InternalC8KeyValue<C8DBImpl, C8DatabaseImpl, C8ExecutorSync> implements C8KeyValue { private static final Logger LOGGER = LoggerFactory.getLogger(C8KeyValueImpl.class); protected C8KeyValueImpl(final C8DatabaseImpl db, final String name) { super(db, name); } @Override public C8KVEntity create(final Boolean expiration, CollectionCreateOptions options) throws C8DBException { return executor.execute(createRequest(name, expiration, options), C8KVEntity.class); } @Override public void drop() throws C8DBException { executor.execute(dropRequest(), Void.class); } @Override public C8KVEntity truncate() throws C8DBException { return executor.execute(truncateRequest(), Void.class); } @Override public <T> MultiDocumentEntity<DocumentCreateEntity<T>> insertKVPairs(final Collection<T> values, DocumentCreateOptions options) throws C8DBException { return executor.execute(insertKVPairsRequest(values, options), insertKVPairsResponseDeserializer(values, options)); } @Override public DocumentDeleteEntity<Void> deleteKVPair(String key) throws C8DBException { return executor.execute(deleteKVPairRequest(key, new DocumentDeleteOptions()), deleteKVPairResponseDeserializer(Void.class)); } @Override public MultiDocumentEntity<DocumentDeleteEntity<Void>> deleteKVPairs(Collection<?> values) throws C8DBException { return executor.execute(deleteKVPairsRequest(values, new DocumentDeleteOptions()), deleteKVPairsResponseDeserializer(Void.class)); } @Override public <T> T getKVPair(String key) throws C8DBException { DocumentUtil.validateDocumentKey(key); try { return executor.execute(getKVPairRequest(key), BaseKeyValue.class); } catch (final C8DBException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(e.getMessage(), e); } // handle Response: 404, Error: 1655 - transaction not found if (e.getErrorNum() != null && e.getErrorNum() == 1655) { throw e; } if ((e.getResponseCode() != null && (e.getResponseCode() == 404 || e.getResponseCode() == 304 || e.getResponseCode() == 412))) { return null; } throw e; } } @Override public <T> MultiDocumentEntity<T> getKVPairs(final Collection<String> keys, final C8KVPairReadOptions options) throws C8DBException { return executor.execute(getKVPairsRequest(keys, options), getKVPairsResponseDeserializer()); } }
3e1fa654177471a5384ecabc31ddacb7d09cd3da
57,420
java
Java
core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/AbstractCoordinateOperation.java
Geomatys/sis
b94a500b295b52b9fbaf0bb8fdbf43c0ce4e7746
[ "Apache-2.0" ]
83
2015-02-12T21:51:54.000Z
2021-12-10T09:44:30.000Z
core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/AbstractCoordinateOperation.java
Geomatys/sis
b94a500b295b52b9fbaf0bb8fdbf43c0ce4e7746
[ "Apache-2.0" ]
11
2017-06-01T21:55:07.000Z
2021-10-19T15:18:40.000Z
core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/AbstractCoordinateOperation.java
apache/sis
e621d10a14072fc1f41aedab2c4a2cfab50ca5ec
[ "Apache-2.0" ]
63
2015-03-30T08:40:14.000Z
2021-11-06T22:54:18.000Z
49.118905
130
0.634378
13,365
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sis.referencing.operation; import java.util.Map; import java.util.Set; import java.util.Objects; import java.util.Collection; import java.util.Collections; import java.io.IOException; import java.io.ObjectInputStream; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.measure.IncommensurableException; import org.opengis.util.InternationalString; import org.opengis.metadata.Identifier; import org.opengis.metadata.extent.Extent; import org.opengis.metadata.quality.PositionalAccuracy; import org.opengis.referencing.IdentifiedObject; import org.opengis.referencing.crs.GeneralDerivedCRS; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.ConcatenatedOperation; import org.opengis.referencing.operation.CoordinateOperation; import org.opengis.referencing.operation.OperationMethod; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.PassThroughOperation; import org.opengis.parameter.GeneralParameterValue; import org.opengis.parameter.ParameterDescriptorGroup; import org.opengis.parameter.ParameterValueGroup; import org.apache.sis.io.wkt.Formatter; import org.apache.sis.io.wkt.FormattableObject; import org.apache.sis.util.iso.Types; import org.apache.sis.util.Classes; import org.apache.sis.util.ComparisonMode; import org.apache.sis.util.collection.Containers; import org.apache.sis.util.UnsupportedImplementationException; import org.apache.sis.util.logging.Logging; import org.apache.sis.util.resources.Errors; import org.apache.sis.parameter.Parameterized; import org.apache.sis.metadata.iso.citation.Citations; import org.apache.sis.referencing.cs.CoordinateSystems; import org.apache.sis.referencing.AbstractIdentifiedObject; import org.apache.sis.referencing.operation.transform.MathTransforms; import org.apache.sis.referencing.operation.transform.PassThroughTransform; import org.apache.sis.internal.referencing.PositionalAccuracyConstant; import org.apache.sis.internal.referencing.CoordinateOperations; import org.apache.sis.internal.referencing.ReferencingUtilities; import org.apache.sis.internal.referencing.Resources; import org.apache.sis.internal.referencing.WKTUtilities; import org.apache.sis.internal.referencing.WKTKeywords; import org.apache.sis.internal.metadata.MetadataUtilities; import org.apache.sis.internal.util.Constants; import org.apache.sis.internal.util.CollectionsExt; import org.apache.sis.internal.util.UnmodifiableArrayList; import org.apache.sis.internal.system.Semaphores; import org.apache.sis.internal.system.Loggers; import static org.apache.sis.util.Utilities.deepEquals; /** * Describes the operation for transforming coordinates in the source CRS to coordinates in the target CRS. * Coordinate operations contain a {@linkplain org.apache.sis.referencing.operation.transform.AbstractMathTransform * math transform}, which does the actual work of transforming coordinates, together with the following information: * * <ul> * <li>The {@linkplain #getSourceCRS() source} and {@linkplain #getTargetCRS() target CRS}.</li> * <li>The {@linkplain #getInterpolationCRS() interpolation CRS} if a CRS other than source and target is needed * for interpolating.</li> * <li>In {@linkplain DefaultConversion conversion} and {@linkplain DefaultTransformation transformation} subclasses, * a description of the {@linkplain DefaultOperationMethod operation method} together with the parameter values.</li> * <li>The {@linkplain #getDomainOfValidity() domain of validity}.</li> * <li>An estimation of the {@linkplain #getCoordinateOperationAccuracy() operation accuracy}.</li> * </ul> * * <h2>Instantiation</h2> * This class is conceptually <cite>abstract</cite>, even if it is technically possible to instantiate it. * Typical applications should create instances of the most specific subclass prefixed by {@code Default} instead. * An exception to this rule may occur when it is not possible to identify the exact operation type. * * <h2>Immutability and thread safety</h2> * This base class is immutable and thus thread-safe if the property <em>values</em> (not necessarily the map itself) * given to the constructor are also immutable. Most SIS subclasses and related classes are immutable under similar * conditions. This means that unless otherwise noted in the javadoc, {@code CoordinateOperation} instances created * using only SIS factories and static constants can be shared by many objects and passed between threads without * synchronization. * * @author Martin Desruisseaux (IRD, Geomatys) * @version 0.8 * @since 0.6 * @module */ @XmlType(name = "AbstractCoordinateOperationType", propOrder = { "domainOfValidity", "scope", "operationVersion", "accuracy", "source", "target" }) @XmlRootElement(name = "AbstractCoordinateOperation") @XmlSeeAlso({ AbstractSingleOperation.class, DefaultPassThroughOperation.class, DefaultConcatenatedOperation.class }) public class AbstractCoordinateOperation extends AbstractIdentifiedObject implements CoordinateOperation { /** * Serial number for inter-operability with different versions. */ private static final long serialVersionUID = 1237358357729193885L; /** * The source CRS, or {@code null} if not available. * * <p><b>Consider this field as final!</b> * This field is non-final only for the convenience of constructors and for initialization * at XML unmarshalling time by {@link #setSource(CoordinateReferenceSystem)}.</p> * * @see #getSourceCRS() */ CoordinateReferenceSystem sourceCRS; /** * The target CRS, or {@code null} if not available. * * <p><b>Consider this field as final!</b> * This field is non-final only for the convenience of constructors and for initialization * at XML unmarshalling time by {@link #setTarget(CoordinateReferenceSystem)}.</p> * * @see #getTargetCRS() */ CoordinateReferenceSystem targetCRS; /** * The CRS which is neither the {@linkplain #getSourceCRS() source CRS} or * {@linkplain #getTargetCRS() target CRS} but still required for performing the operation. * * <p><b>Consider this field as final!</b> * This field is non-final only for the convenience of constructors.</p> * * @see #getInterpolationCRS() */ private CoordinateReferenceSystem interpolationCRS; /** * Version of the coordinate transformation * (i.e., instantiation due to the stochastic nature of the parameters). * * <p><b>Consider this field as final!</b> * This field is modified only at unmarshalling time by {@link #setOperationVersion(String)}.</p> * * @see #getOperationVersion() */ private String operationVersion; /** * Estimate(s) of the impact of this operation on point accuracy, or {@code null} if none. * * <p><b>Consider this field as final!</b> * This field is non-final only for the convenience of constructors and for initialization * at XML unmarshalling time by {@link #setAccuracy(PositionalAccuracy[])}.</p> * * @see #getCoordinateOperationAccuracy() */ Collection<PositionalAccuracy> coordinateOperationAccuracy; /** * Area in which this operation is valid, or {@code null} if not available. * * <p><b>Consider this field as final!</b> * This field is non-final only for the convenience of constructors and for initialization * at XML unmarshalling time by {@link #setDomainOfValidity(Extent)}.</p> * * @see #getDomainOfValidity() */ Extent domainOfValidity; /** * Description of domain of usage, or limitations of usage, for which this operation is valid. * * <p><b>Consider this field as final!</b> * This field is modified only at unmarshalling time by {@link #setScope(InternationalString)}.</p> * * @see #getScope() */ private InternationalString scope; /** * Transform from positions in the {@linkplain #getSourceCRS source coordinate reference system} * to positions in the {@linkplain #getTargetCRS target coordinate reference system}. * * <p><b>Consider this field as final!</b> * This field is non-final only for the convenience of constructors and for initialization * at XML unmarshalling time by {@link AbstractSingleOperation#afterUnmarshal(Unmarshaller, Object)}.</p> */ MathTransform transform; /** * Indices of target dimensions where "wrap around" may happen as a result of this coordinate operation. * This is usually the longitude axis when the source CRS uses the [-180 … +180]° range and the target * CRS uses the [0 … 360]° range, or the converse. If there is no change, then this is an empty set. * * @see #getWrapAroundChanges() * @see #computeTransientFields() */ private transient Set<Integer> wrapAroundChanges; /** * Creates a new coordinate operation initialized from the given properties. * It is caller's responsibility to: * * <ul> * <li>Set the following fields:<ul> * <li>{@link #sourceCRS}</li> * <li>{@link #targetCRS}</li> * <li>{@link #transform}</li> * </ul></li> * <li>Invoke {@link #checkDimensions(Map)} after the above-cited fields have been set.</li> * </ul> */ AbstractCoordinateOperation(final Map<String,?> properties) { super(properties); this.scope = Types.toInternationalString(properties, SCOPE_KEY); this.domainOfValidity = Containers.property(properties, DOMAIN_OF_VALIDITY_KEY, Extent.class); this.operationVersion = Containers.property(properties, OPERATION_VERSION_KEY, String.class); Object value = properties.get(COORDINATE_OPERATION_ACCURACY_KEY); if (value != null) { if (value instanceof PositionalAccuracy[]) { coordinateOperationAccuracy = CollectionsExt.nonEmptySet((PositionalAccuracy[]) value); } else { coordinateOperationAccuracy = Collections.singleton((PositionalAccuracy) value); } } } /** * Creates a coordinate operation from the given properties. * The properties given in argument follow the same rules than for the * {@linkplain AbstractIdentifiedObject#AbstractIdentifiedObject(Map) super-class constructor}. * Additionally, the following properties are understood by this constructor: * * <table class="sis"> * <caption>Recognized properties (non exhaustive list)</caption> * <tr> * <th>Property name</th> * <th>Value type</th> * <th>Returned by</th> * </tr> * <tr> * <td>{@value org.opengis.referencing.operation.CoordinateOperation#OPERATION_VERSION_KEY}</td> * <td>{@link String}</td> * <td>{@link #getOperationVersion()}</td> * </tr> * <tr> * <td>{@value org.opengis.referencing.operation.CoordinateOperation#COORDINATE_OPERATION_ACCURACY_KEY}</td> * <td>{@link PositionalAccuracy} (optionally as array)</td> * <td>{@link #getCoordinateOperationAccuracy()}</td> * </tr> * <tr> * <td>{@value org.opengis.referencing.operation.CoordinateOperation#DOMAIN_OF_VALIDITY_KEY}</td> * <td>{@link Extent}</td> * <td>{@link #getDomainOfValidity()}</td> * </tr> * <tr> * <td>{@value org.opengis.referencing.operation.CoordinateOperation#SCOPE_KEY}</td> * <td>{@link InternationalString} or {@link String}</td> * <td>{@link #getScope()}</td> * </tr> * <tr> * <th colspan="3" class="hsep">Defined in parent class (reminder)</th> * </tr> * <tr> * <td>{@value org.opengis.referencing.IdentifiedObject#NAME_KEY}</td> * <td>{@link Identifier} or {@link String}</td> * <td>{@link #getName()}</td> * </tr> * <tr> * <td>{@value org.opengis.referencing.IdentifiedObject#ALIAS_KEY}</td> * <td>{@link org.opengis.util.GenericName} or {@link CharSequence} (optionally as array)</td> * <td>{@link #getAlias()}</td> * </tr> * <tr> * <td>{@value org.opengis.referencing.IdentifiedObject#IDENTIFIERS_KEY}</td> * <td>{@link Identifier} (optionally as array)</td> * <td>{@link #getIdentifiers()}</td> * </tr> * <tr> * <td>{@value org.opengis.referencing.IdentifiedObject#REMARKS_KEY}</td> * <td>{@link InternationalString} or {@link String}</td> * <td>{@link #getRemarks()}</td> * </tr> * </table> * * <h4>Constraints</h4> * All arguments except {@code properties} can be {@code null}. * If non-null, the dimension of CRS arguments shall be related to the {@code transform} argument as below: * * <ul> * <li>Dimension of {@code sourceCRS} shall be equal to the transform * {@linkplain org.apache.sis.referencing.operation.transform.AbstractMathTransform#getSourceDimensions() * source dimension} minus the dimension of the {@code interpolationCRS} (if any).</li> * <li>Dimension of {@code targetCRS} shall be equal to the transform * {@linkplain org.apache.sis.referencing.operation.transform.AbstractMathTransform#getTargetDimensions() * target dimension}, minus the dimension of the {@code interpolationCRS} (if any).</li> * </ul> * * If the {@code interpolationCRS} is non-null, then the given {@code transform} shall expect input coordinates * in the following order: * * <ol> * <li>Coordinates of the interpolation CRS. Example: (<var>x</var>,<var>y</var>) in a vertical transform.</li> * <li>Coordinates of the source CRS. Example: (<var>z</var>) in a vertical transform.</li> * </ol> * * The math transform shall let the interpolation coordinates {@linkplain DefaultPassThroughOperation pass through * the operation}. * * @param properties the properties to be given to the identified object. * @param sourceCRS the source CRS, or {@code null} if unspecified. * @param targetCRS the target CRS, or {@code null} if unspecified. * @param interpolationCRS the CRS of additional coordinates needed for the operation, or {@code null} if none. * @param transform transform from positions in the source CRS to positions in the target CRS, * or {@code null} if unspecified. */ public AbstractCoordinateOperation(final Map<String,?> properties, final CoordinateReferenceSystem sourceCRS, final CoordinateReferenceSystem targetCRS, final CoordinateReferenceSystem interpolationCRS, final MathTransform transform) { this(properties); this.sourceCRS = sourceCRS; this.targetCRS = targetCRS; this.interpolationCRS = interpolationCRS; this.transform = transform; checkDimensions(properties); } /** * Ensures that {@link #sourceCRS}, {@link #targetCRS} and {@link #interpolationCRS} dimensions * are consistent with {@link #transform} input and output dimensions. */ final void checkDimensions(final Map<String,?> properties) { final MathTransform transform = this.transform; // Protect from changes. if (transform != null) { final int interpDim = ReferencingUtilities.getDimension(interpolationCRS); check: for (int isTarget=0; ; isTarget++) { // 0 == source check; 1 == target check. final CoordinateReferenceSystem crs; // Will determine the expected dimensions. int actual; // The MathTransform number of dimensions. switch (isTarget) { case 0: crs = sourceCRS; actual = transform.getSourceDimensions(); break; case 1: crs = targetCRS; actual = transform.getTargetDimensions(); break; default: break check; } int expected = ReferencingUtilities.getDimension(crs); if (interpDim != 0) { if (actual == expected || actual < interpDim) { // This check is not strictly necessary as the next check below would catch the error, // but we provide here a hopefully more helpful error message for a common mistake. throw new IllegalArgumentException(Resources.forProperties(properties) .getString(Resources.Keys.MissingInterpolationOrdinates)); } expected += interpDim; } if (crs != null && actual != expected) { throw new IllegalArgumentException(Errors.getResources(properties).getString( Errors.Keys.MismatchedTransformDimension_4, super.getName().getCode(), isTarget, expected, actual)); } } } computeTransientFields(); } /** * Computes the {@link #wrapAroundChanges} field after we verified that the coordinate operation is valid. */ final void computeTransientFields() { if (sourceCRS != null && targetCRS != null) { wrapAroundChanges = CoordinateOperations.wrapAroundChanges(sourceCRS, targetCRS.getCoordinateSystem()); } else { wrapAroundChanges = Collections.emptySet(); } } /** * Computes transient fields after deserialization. * * @param in the input stream from which to deserialize a coordinate operation. * @throws IOException if an I/O error occurred while reading or if the stream contains invalid data. * @throws ClassNotFoundException if the class serialized on the stream is not on the classpath. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); computeTransientFields(); } /** * Creates a new coordinate operation with the same values than the specified one. * This copy constructor provides a way to convert an arbitrary implementation into a SIS one * or a user-defined one (as a subclass), usually in order to leverage some implementation-specific API. * * <p>This constructor performs a shallow copy, i.e. the properties are not cloned.</p> * * @param operation the coordinate operation to copy. * * @see #castOrCopy(CoordinateOperation) */ protected AbstractCoordinateOperation(final CoordinateOperation operation) { super(operation); sourceCRS = operation.getSourceCRS(); targetCRS = operation.getTargetCRS(); interpolationCRS = getInterpolationCRS(operation); operationVersion = operation.getOperationVersion(); coordinateOperationAccuracy = operation.getCoordinateOperationAccuracy(); domainOfValidity = operation.getDomainOfValidity(); scope = operation.getScope(); transform = operation.getMathTransform(); if (operation instanceof AbstractCoordinateOperation) { wrapAroundChanges = ((AbstractCoordinateOperation) operation).wrapAroundChanges; } else { computeTransientFields(); } } /** * Returns a SIS coordinate operation implementation with the values of the given arbitrary implementation. * This method performs the first applicable action in the following choices: * * <ul> * <li>If the given object is {@code null}, then this method returns {@code null}.</li> * <li>Otherwise if the given object is an instance of * {@link org.opengis.referencing.operation.Transformation}, * {@link org.opengis.referencing.operation.Conversion}, * {@link org.opengis.referencing.operation.Projection}, * {@link org.opengis.referencing.operation.CylindricalProjection}, * {@link org.opengis.referencing.operation.ConicProjection}, * {@link org.opengis.referencing.operation.PlanarProjection}, * {@link org.opengis.referencing.operation.PassThroughOperation} or * {@link org.opengis.referencing.operation.ConcatenatedOperation}, * then this method delegates to the {@code castOrCopy(…)} method of the corresponding SIS subclass. * Note that if the given object implements more than one of the above-cited interfaces, * then the {@code castOrCopy(…)} method to be used is unspecified.</li> * <li>Otherwise if the given object is already an instance of * {@code AbstractCoordinateOperation}, then it is returned unchanged.</li> * <li>Otherwise a new {@code AbstractCoordinateOperation} instance is created using the * {@linkplain #AbstractCoordinateOperation(CoordinateOperation) copy constructor} * and returned. Note that this is a <cite>shallow</cite> copy operation, since the other * properties contained in the given object are not recursively copied.</li> * </ul> * * @param object the object to get as a SIS implementation, or {@code null} if none. * @return a SIS implementation containing the values of the given object (may be the * given object itself), or {@code null} if the argument was null. */ public static AbstractCoordinateOperation castOrCopy(final CoordinateOperation object) { return SubTypes.castOrCopy(object); } /** * Returns the GeoAPI interface implemented by this class. * The default implementation returns {@code CoordinateOperation.class}. * Subclasses implementing a more specific GeoAPI interface shall override this method. * * @return the coordinate operation interface implemented by this class. */ @Override public Class<? extends CoordinateOperation> getInterface() { return CoordinateOperation.class; } /** * Returns {@code true} if this coordinate operation is for the definition of a * {@linkplain org.apache.sis.referencing.crs.DefaultDerivedCRS derived} or * {@linkplain org.apache.sis.referencing.crs.DefaultProjectedCRS projected CRS}. * The standard (ISO 19111) approach constructs <cite>defining conversion</cite> * as an operation of type {@link org.opengis.referencing.operation.Conversion} * with null {@linkplain #getSourceCRS() source} and {@linkplain #getTargetCRS() target CRS}. * But SIS supports also defining conversions with non-null CRS provided that: * * <ul> * <li>{@link GeneralDerivedCRS#getBaseCRS()} is the {@linkplain #getSourceCRS() source CRS} of this operation, and</li> * <li>{@link GeneralDerivedCRS#getConversionFromBase()} is this operation instance.</li> * </ul> * * When this method returns {@code true}, the source and target CRS are not marshalled in XML documents. * * @return {@code true} if this coordinate operation is for the definition of a derived or projected CRS. */ public boolean isDefiningConversion() { /* * Trick: we do not need to verify if (this instanceof Conversion) because: * - Only DefaultConversion constructor accepts null source and target CRS. * - GeneralDerivedCRS.getConversionFromBase() return type is Conversion. */ return (sourceCRS == null && targetCRS == null) || ((targetCRS instanceof GeneralDerivedCRS) && ((GeneralDerivedCRS) targetCRS).getBaseCRS() == sourceCRS && ((GeneralDerivedCRS) targetCRS).getConversionFromBase() == this); } /** * Returns the source CRS, or {@code null} if unspecified. * The source CRS is mandatory for {@linkplain DefaultTransformation transformations} only. * This information is optional for {@linkplain DefaultConversion conversions} according * the ISO 19111 standard, but Apache SIS tries to provide that CRS in most cases anyway. * * @return the source CRS, or {@code null} if not available. */ @Override public CoordinateReferenceSystem getSourceCRS() { return sourceCRS; } /** * Returns the target CRS, or {@code null} if unspecified. * The target CRS is mandatory for {@linkplain DefaultTransformation transformations} only. * This information is optional for {@linkplain DefaultConversion conversions} according * the ISO 19111 standard, but Apache SIS tries to provide that CRS in most cases anyway. * * @return the target CRS, or {@code null} if not available. */ @Override public CoordinateReferenceSystem getTargetCRS() { return targetCRS; } /** * Returns the CRS which is neither the {@linkplain #getSourceCRS() source CRS} or * {@linkplain #getTargetCRS() target CRS} but still required for performing the operation. * * <div class="note"><b>Example:</b> * some transformations of vertical coordinates (<var>h</var>) require the horizontal coordinates (φ,λ) * in order to interpolate in a grid. This method returns the CRS of the grid where such interpolations * are performed.</div> * * @return the CRS (neither source or target CRS) required for interpolating the values, or {@code null} if none. */ public CoordinateReferenceSystem getInterpolationCRS() { return interpolationCRS; } /** * Returns the interpolation CRS of the given coordinate operation, or {@code null} if none. */ static CoordinateReferenceSystem getInterpolationCRS(final CoordinateOperation operation) { return (operation instanceof AbstractCoordinateOperation) ? ((AbstractCoordinateOperation) operation).getInterpolationCRS() : null; } /** * Returns the version of the coordinate operation. Different versions of a coordinate * {@linkplain DefaultTransformation transformation} may exist because of the stochastic * nature of the parameters. In principle this property is irrelevant to coordinate * {@linkplain DefaultConversion conversions}, but Apache SIS accepts it anyway. * * @return the coordinate operation version, or {@code null} in none. */ @Override @XmlElement(name = "operationVersion") public String getOperationVersion() { return operationVersion; } /** * Returns an estimation of the impact of this operation on point accuracy. * The positional accuracy gives position error estimates for target coordinates * of this coordinate operation, assuming no errors in source coordinates. * * @return the position error estimations, or an empty collection if not available. * * @see #getLinearAccuracy() */ @Override public Collection<PositionalAccuracy> getCoordinateOperationAccuracy() { return CollectionsExt.nonNull(coordinateOperationAccuracy); } /** * Returns an estimation of positional accuracy in metres, or {@code NaN} if unknown. * The default implementation tries to infer a value from the metadata returned by * {@link #getCoordinateOperationAccuracy()} using SIS-specific heuristics. * * <h4>Current implementation</h4> * The current implementation uses the heuristic rules listed below. * Note that those rules may change in any future SIS version. * * <ul> * <li>If at least one {@linkplain org.apache.sis.metadata.iso.quality.DefaultQuantitativeResult quantitative * result} is found with a linear unit, then returns the largest result value converted to metres.</li> * * <li>Otherwise if the operation is a {@linkplain DefaultConversion conversion}, * then returns 0 since a conversion is by definition accurate up to rounding errors.</li> * * <li>Otherwise if the operation is a {@linkplain DefaultTransformation transformation}, * then checks if the datum shift were applied with the help of Bursa-Wolf parameters. * If a datum shift has been applied, returns 25 meters. * If a datum shift should have been applied but has been omitted, returns 3000 meters. * * <div class="note"><b>Note:</b> * the 3000 meters value is higher than the highest value (999 meters) found in the EPSG * database version 6.7. The 25 meters value is the next highest value found in the EPSG * database for a significant number of transformations.</div> * * <li>Otherwise if the operation is a {@linkplain DefaultConcatenatedOperation concatenated operation}, * returns the sum of the accuracy of all components. * This is a conservative scenario where we assume that errors cumulate linearly. * * <div class="note"><b>Note:</b> * this is not necessarily the "worst case" scenario since the accuracy could be worst * if the math transforms are highly non-linear.</div></li> * </ul> * * @return the accuracy estimation (always in meters), or NaN if unknown. * * @see org.apache.sis.referencing.CRS#getLinearAccuracy(CoordinateOperation) */ public double getLinearAccuracy() { return PositionalAccuracyConstant.getLinearAccuracy(this); } /** * Returns the area or region or timeframe in which this coordinate operation is valid. * * @return the coordinate operation valid domain, or {@code null} if not available. */ @Override @XmlElement(name = "domainOfValidity") public Extent getDomainOfValidity() { return domainOfValidity; } /** * Returns a description of domain of usage, or limitations of usage, for which this operation is valid. * * @return a description of domain of usage, or {@code null} if none. */ @Override @XmlElement(name = "scope", required = true) public InternationalString getScope() { return scope; } /** * Returns the object for transforming coordinates in the {@linkplain #getSourceCRS() source CRS} * to coordinates in the {@linkplain #getTargetCRS() target CRS}. * * <h4>Use with interpolation CRS</h4> * If the {@linkplain #getInterpolationCRS() interpolation CRS} is non-null, then the math transform * input coordinates shall by (<var>interpolation</var>, <var>source</var>) tuples: for each value * to transform, the interpolation point coordinates shall be first, followed by the source coordinates. * * <div class="note"><b>Example:</b> * in a transformation between two {@linkplain org.apache.sis.referencing.crs.DefaultVerticalCRS vertical CRS}, * if the {@linkplain #getSourceCRS() source} coordinates are (<var>z</var>) values but the coordinate operation * additionally requires (<var>x</var>,<var>y</var>) values for {@linkplain #getInterpolationCRS() interpolation} * purpose, then the math transform input coordinates shall be (<var>x</var>,<var>y</var>,<var>z</var>) tuples in * that order.</div> * * The interpolation coordinates will {@linkplain DefaultPassThroughOperation pass through the operation} * and appear in the math transform outputs, in the same order than inputs. * * @return the transform from source to target CRS, or {@code null} if not applicable. */ @Override public MathTransform getMathTransform() { return transform; } /** * Returns the operation method. This apply only to {@link AbstractSingleOperation} subclasses, * which will make this method public. * * @return the operation method, or {@code null} if none. */ OperationMethod getMethod() { return null; } /** * Returns the parameter descriptor. The default implementation infers the descriptor from the * {@linkplain #transform}, if possible. If no descriptor can be inferred from the math transform, * then this method fallback on the {@link OperationMethod} parameters. */ ParameterDescriptorGroup getParameterDescriptors() { ParameterDescriptorGroup descriptor = getParameterDescriptors(transform); if (descriptor == null) { final OperationMethod method = getMethod(); if (method != null) { descriptor = method.getParameters(); } } return descriptor; } /** * Returns the parameter descriptors for the given transform, or {@code null} if unknown. */ static ParameterDescriptorGroup getParameterDescriptors(MathTransform transform) { while (transform != null) { if (transform instanceof Parameterized) { final ParameterDescriptorGroup param; if (Semaphores.queryAndSet(Semaphores.ENCLOSED_IN_OPERATION)) { throw new AssertionError(); // Should never happen. } try { param = ((Parameterized) transform).getParameterDescriptors(); } finally { Semaphores.clear(Semaphores.ENCLOSED_IN_OPERATION); } if (param != null) { return param; } } if (transform instanceof PassThroughTransform) { transform = ((PassThroughTransform) transform).getSubTransform(); } else { break; } } return null; } /** * Returns the parameter values. The default implementation infers the * parameter values from the {@linkplain #transform}, if possible. * * @return the parameter values (never {@code null}). * @throws UnsupportedOperationException if the parameter values can not * be determined for the current math transform implementation. */ ParameterValueGroup getParameterValues() throws UnsupportedOperationException { MathTransform mt = transform; while (mt != null) { if (mt instanceof Parameterized) { final ParameterValueGroup param; if (Semaphores.queryAndSet(Semaphores.ENCLOSED_IN_OPERATION)) { throw new AssertionError(); // Should never happen. } try { param = ((Parameterized) mt).getParameterValues(); } finally { Semaphores.clear(Semaphores.ENCLOSED_IN_OPERATION); } if (param != null) { return param; } } if (mt instanceof PassThroughTransform) { mt = ((PassThroughTransform) mt).getSubTransform(); } else { break; } } throw new UnsupportedImplementationException(Classes.getClass(mt)); } /** * Returns the indices of target dimensions where "wrap around" may happen as a result of this coordinate operation. * If such change exists, then this is usually the longitude axis when the source CRS uses the [-180 … +180]° range * and the target CRS uses the [0 … 360]° range, or the converse. If there is no change, then this is an empty set. * * <div class="note"><b>Inverse relationship:</b> * sometime the target dimensions returned by this method can be mapped directly to wraparound axes in source CRS, * but this is not always the case. For example consider the following operation chain: * * <div style="text-align:center">source projected CRS ⟶ base CRS ⟶ target geographic CRS</div> * * In this example, a wraparound axis in the target CRS (the longitude) can be mapped to a wraparound axis in * the {@linkplain org.apache.sis.referencing.crs.DefaultProjectedCRS#getBaseCRS() base CRS}. But there is no * corresponding wraparound axis in the source CRS because the <em>easting</em> axis in projected CRS does not * have a wraparound range meaning. We could argue that * {@linkplain org.apache.sis.referencing.cs.DefaultCoordinateSystemAxis#getDirection() axis directions} match, * but such matching is not guaranteed to exist since {@code ProjectedCRS} is a special case of * {@code GeneralDerivedCRS} and derived CRS can have rotations.</div> * * <p>The default implementation infers this set by inspecting the source and target coordinate system axes. * It returns the indices of all target axes having {@link org.opengis.referencing.cs.RangeMeaning#WRAPAROUND} * and for which the following condition holds: a colinear source axis exists with compatible unit of measurement, * and the range (taking unit conversions in account) or range meaning of those source and target axes are not * the same.</p> * * @return indices of target dimensions where "wrap around" may happen as a result of this coordinate operation. * * @since 0.8 */ @SuppressWarnings("ReturnOfCollectionOrArrayField") public Set<Integer> getWrapAroundChanges() { return wrapAroundChanges; } /** * Compares this coordinate operation with the specified object for equality. If the {@code mode} argument * is {@link ComparisonMode#STRICT} or {@link ComparisonMode#BY_CONTRACT BY_CONTRACT}, then all available * properties are compared including the {@linkplain #getDomainOfValidity() domain of validity} and the * {@linkplain #getScope() scope}. * * @param object the object to compare to {@code this}. * @param mode {@link ComparisonMode#STRICT STRICT} for performing a strict comparison, or * {@link ComparisonMode#IGNORE_METADATA IGNORE_METADATA} for ignoring properties * that do not make a difference in the numerical results of coordinate operations. * @return {@code true} if both objects are equal for the given comparison mode. */ @Override public boolean equals(final Object object, ComparisonMode mode) { if (super.equals(object, mode)) { if (mode == ComparisonMode.STRICT) { final AbstractCoordinateOperation that = (AbstractCoordinateOperation) object; if (Objects.equals(sourceCRS, that.sourceCRS) && Objects.equals(interpolationCRS, that.interpolationCRS) && Objects.equals(transform, that.transform) && Objects.equals(scope, that.scope) && Objects.equals(domainOfValidity, that.domainOfValidity) && Objects.equals(coordinateOperationAccuracy, that.coordinateOperationAccuracy)) { // Check against never-ending recursivity with DerivedCRS. if (Semaphores.queryAndSet(Semaphores.CONVERSION_AND_CRS)) { return true; } else try { return Objects.equals(targetCRS, that.targetCRS); } finally { Semaphores.clear(Semaphores.CONVERSION_AND_CRS); } } } else { /* * This block is for all ComparisonModes other than STRICT. At this point we know that the metadata * properties (class, name, identifiers, etc.) match the criterion of the given comparison mode. * Before to continue perform the following checks: * * - Scope, domain and accuracy properties only if NOT in "ignore metadata" mode. * - Interpolation CRS in all cases (regardless if ignoring metadata or not). */ final CoordinateOperation that = (CoordinateOperation) object; if ((mode.isIgnoringMetadata() || (deepEquals(getScope(), that.getScope(), mode) && deepEquals(getDomainOfValidity(), that.getDomainOfValidity(), mode) && deepEquals(getCoordinateOperationAccuracy(), that.getCoordinateOperationAccuracy(), mode))) && deepEquals(getInterpolationCRS(), getInterpolationCRS(that), mode)) { /* * At this point all metadata match or can be ignored. First, compare the targetCRS. * We need to perform this comparison only if this 'equals(…)' method is not invoked * from AbstractDerivedCRS, otherwise we would fall in an infinite recursive loop * (because targetCRS is the DerivedCRS, which in turn wants to compare this operation). * * We also opportunistically use this "anti-recursivity" check for another purpose. * The Semaphores.COMPARING flag should be set only when AbstractDerivedCRS is comparing * its "from base" conversion. The flag should never be set in any other circumstance, * since this is an internal Apache SIS mechanism. If we know that we are comparing the * AbstractDerivedCRS.fromBase conversion, then (in the way Apache SIS is implemented) * this.sourceCRS == AbstractDerivedCRS.baseCRS. Consequently we can relax the check of * sourceCRS axis order if the mode is ComparisonMode.IGNORE_METADATA. */ boolean debug = false; if (Semaphores.queryAndSet(Semaphores.CONVERSION_AND_CRS)) { if (mode.isIgnoringMetadata()) { debug = (mode == ComparisonMode.DEBUG); mode = ComparisonMode.ALLOW_VARIANT; } } else try { if (!deepEquals(getTargetCRS(), that.getTargetCRS(), mode)) { return false; } } finally { Semaphores.clear(Semaphores.CONVERSION_AND_CRS); } /* * Now compare the sourceCRS, potentially with a relaxed ComparisonMode (see above comment). * If the comparison mode allows the two CRS to have different axis order and units, then we * need to take in account those difference before to compare the MathTransform. We proceed * by modifying 'tr2' as if it was a MathTransform with crs1 as the source instead of crs2. */ final CoordinateReferenceSystem crs1 = this.getSourceCRS(); final CoordinateReferenceSystem crs2 = that.getSourceCRS(); if (deepEquals(crs1, crs2, mode)) { MathTransform tr1 = this.getMathTransform(); MathTransform tr2 = that.getMathTransform(); if (mode == ComparisonMode.ALLOW_VARIANT) try { final MathTransform before = MathTransforms.linear( CoordinateSystems.swapAndScaleAxes(crs1.getCoordinateSystem(), crs2.getCoordinateSystem())); final MathTransform after = MathTransforms.linear( CoordinateSystems.swapAndScaleAxes(that.getTargetCRS().getCoordinateSystem(), this.getTargetCRS().getCoordinateSystem())); tr2 = MathTransforms.concatenate(before, tr2, after); } catch (IncommensurableException | RuntimeException e) { Logging.recoverableException(Logging.getLogger(Loggers.COORDINATE_OPERATION), AbstractCoordinateOperation.class, "equals", e); } if (deepEquals(tr1, tr2, mode)) return true; assert !debug || deepEquals(tr1, tr2, ComparisonMode.DEBUG); // For locating the mismatch. } } } } return false; } /** * Invoked by {@code hashCode()} for computing the hash code when first needed. * See {@link AbstractIdentifiedObject#computeHashCode()} for more information. * * @return the hash code value. This value may change in any future Apache SIS version. */ @Override protected long computeHashCode() { /* * Do NOT take 'getMethod()' in account in hash code calculation. See the comment * inside the above 'equals(Object, ComparisonMode)' method for more information. * Note that we use the 'transform' hash code, which should be sufficient. */ return super.computeHashCode() + Objects.hash(sourceCRS, targetCRS, interpolationCRS, transform); } /** * Formats this coordinate operation in Well Known Text (WKT) version 2 format. * * @param formatter the formatter to use. * @return {@code "CoordinateOperation"}. * * @see <a href="http://docs.opengeospatial.org/is/12-063r5/12-063r5.html#113">WKT 2 specification §17</a> */ @Override protected String formatTo(final Formatter formatter) { super.formatTo(formatter); formatter.newLine(); /* * If the WKT is a component of a ConcatenatedOperation, do not format the source CRS since it is identical * to the target CRS of the previous step, or to the source CRS of the enclosing "ConcatenatedOperation" if * this step is the first step. * * This decision is SIS-specific since the WKT 2 specification does not define concatenated operations. * This choice may change in any future SIS version. */ final FormattableObject enclosing = formatter.getEnclosingElement(1); final boolean isSubOperation = (enclosing instanceof PassThroughOperation); final boolean isComponent = (enclosing instanceof ConcatenatedOperation); if (!isSubOperation && !isComponent) { append(formatter, getSourceCRS(), WKTKeywords.SourceCRS); append(formatter, getTargetCRS(), WKTKeywords.TargetCRS); } final OperationMethod method = getMethod(); if (method != null) { formatter.append(DefaultOperationMethod.castOrCopy(method)); ParameterValueGroup parameters; try { parameters = getParameterValues(); } catch (UnsupportedOperationException e) { final IdentifiedObject c = getParameterDescriptors(); formatter.setInvalidWKT(c != null ? c : this, e); parameters = null; } if (parameters != null) { /* * Format the parameter values. Apache SIS uses the EPSG geodetic dataset as the main source of * parameter definitions. When a parameter is defined by both OGC and EPSG with different names, * the Formatter class is responsible for choosing an appropriate name. But when the difference * is more fundamental, we may have duplication. For example in the "Molodensky" operation, OGC * uses source and target axis lengths while EPSG uses only difference between those lengths. * In this case, OGC and EPSG parameters are defined separately and are redundant. To simplify * the CoordinateOperation WKT, we omit non-EPSG parameters when we have determined that we are * about to describe an EPSG operation. We could generalize this filtering to any authority, but * we don't because few authorities are as complete as EPSG, so other authorities are more likely * to mix EPSG or someone else components with their own. Note also that we don't apply filtering * on MathTransform WKT neither for more reliable debugging. */ final boolean filter = WKTUtilities.isEPSG(parameters.getDescriptor(), false) && // NOT method.getName() Constants.EPSG.equalsIgnoreCase(Citations.toCodeSpace(formatter.getNameAuthority())); formatter.newLine(); formatter.indent(+1); for (final GeneralParameterValue param : parameters.values()) { if (!filter || WKTUtilities.isEPSG(param.getDescriptor(), true)) { WKTUtilities.append(param, formatter); } } formatter.indent(-1); } } if (!isSubOperation && !(this instanceof ConcatenatedOperation)) { append(formatter, getInterpolationCRS(), WKTKeywords.InterpolationCRS); final double accuracy = getLinearAccuracy(); if (accuracy > 0) { formatter.append(new FormattableObject() { @Override protected String formatTo(final Formatter formatter) { formatter.append(accuracy); return WKTKeywords.OperationAccuracy; } }); } } if (formatter.getConvention().majorVersion() == 1) { formatter.setInvalidWKT(this, null); } if (isComponent) { formatter.setInvalidWKT(this, null); return "CoordinateOperationStep"; } return WKTKeywords.CoordinateOperation; } /** * Appends the given CRS (if non-null) wrapped in an element of the given name. * * @param formatter the formatter where to append the object name. * @param crs the object to append, or {@code null} if none. * @param type the keyword to write before the object. */ private static void append(final Formatter formatter, final CoordinateReferenceSystem crs, final String type) { if (crs != null) { formatter.append(new FormattableObject() { @Override protected String formatTo(final Formatter formatter) { formatter.indent(-1); formatter.append(WKTUtilities.toFormattable(crs)); formatter.indent(+1); return type; } }); formatter.newLine(); } } ////////////////////////////////////////////////////////////////////////////////////////////////// //////// //////// //////// XML support with JAXB //////// //////// //////// //////// The following methods are invoked by JAXB using reflection (even if //////// //////// they are private) or are helpers for other methods invoked by JAXB. //////// //////// Those methods can be safely removed if Geographic Markup Language //////// //////// (GML) support is not needed. //////// //////// //////// ////////////////////////////////////////////////////////////////////////////////////////////////// /** * Creates a new object in which every attributes are set to a null value. * <strong>This is not a valid object.</strong> This constructor is strictly * reserved to JAXB, which will assign values to the fields using reflexion. */ AbstractCoordinateOperation() { super(org.apache.sis.internal.referencing.NilReferencingObject.INSTANCE); } /** * Invoked by JAXB for getting the source CRS to marshal. */ @XmlElement(name = "sourceCRS") private CoordinateReferenceSystem getSource() { return isDefiningConversion() ? null : getSourceCRS(); } /** * Invoked by JAXB at marshalling time for setting the source CRS. */ private void setSource(final CoordinateReferenceSystem crs) { if (sourceCRS == null) { sourceCRS = crs; } else if (!sourceCRS.equals(crs)) { // Could be defined by ConcatenatedOperation. MetadataUtilities.propertyAlreadySet(AbstractCoordinateOperation.class, "setSource", "sourceCRS"); } } /** * Invoked by JAXB for getting the target CRS to marshal. */ @XmlElement(name = "targetCRS") private CoordinateReferenceSystem getTarget() { return isDefiningConversion() ? null : getTargetCRS(); } /** * Invoked by JAXB at unmarshalling time for setting the target CRS. */ private void setTarget(final CoordinateReferenceSystem crs) { if (targetCRS == null) { targetCRS = crs; } else if (!targetCRS.equals(crs)) { // Could be defined by ConcatenatedOperation. MetadataUtilities.propertyAlreadySet(AbstractCoordinateOperation.class, "setTarget", "targetCRS"); } } /** * Invoked by JAXB only at marshalling time. */ @XmlElement(name = "coordinateOperationAccuracy") private PositionalAccuracy[] getAccuracy() { final Collection<PositionalAccuracy> accuracy = getCoordinateOperationAccuracy(); final int size = accuracy.size(); return (size != 0) ? accuracy.toArray(new PositionalAccuracy[size]) : null; } /** * Invoked by JAXB only at unmarshalling time. */ private void setAccuracy(final PositionalAccuracy[] values) { if (coordinateOperationAccuracy == null) { coordinateOperationAccuracy = UnmodifiableArrayList.wrap(values); } else { MetadataUtilities.propertyAlreadySet(AbstractCoordinateOperation.class, "setAccuracy", "coordinateOperationAccuracy"); } } /** * Invoked by JAXB only at unmarshalling time. * * @see #getOperationVersion() */ private void setOperationVersion(final String value) { if (operationVersion == null) { operationVersion = value; } else { MetadataUtilities.propertyAlreadySet(AbstractCoordinateOperation.class, "setOperationVersion", "operationVersion"); } } /** * Invoked by JAXB only at unmarshalling time. * * @see #getDomainOfValidity() */ private void setDomainOfValidity(final Extent value) { if (domainOfValidity == null) { domainOfValidity = value; } else { MetadataUtilities.propertyAlreadySet(AbstractCoordinateOperation.class, "setDomainOfValidity", "domainOfValidity"); } } /** * Invoked by JAXB only at unmarshalling time. * * @see #getScope() */ private void setScope(final InternationalString value) { if (scope == null) { scope = value; } else { MetadataUtilities.propertyAlreadySet(AbstractCoordinateOperation.class, "setScope", "scope"); } } /** * Invoked by JAXB after unmarshalling. */ void afterUnmarshal(Unmarshaller unmarshaller, Object parent) { computeTransientFields(); } }
3e1fa6ee0b4178fc7246252baa7b01cd3a0073f8
9,083
java
Java
apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/NamespaceBranchController.java
dondwu/apollo
7d01f7aad1ab6907a9aa26adb74d501d1e524475
[ "Apache-2.0" ]
26,901
2016-03-13T01:01:57.000Z
2021-08-25T15:03:54.000Z
apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/NamespaceBranchController.java
dondwu/apollo
7d01f7aad1ab6907a9aa26adb74d501d1e524475
[ "Apache-2.0" ]
3,462
2016-03-18T08:07:01.000Z
2021-08-24T12:55:21.000Z
apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/NamespaceBranchController.java
dondwu/apollo
7d01f7aad1ab6907a9aa26adb74d501d1e524475
[ "Apache-2.0" ]
10,122
2016-03-12T05:23:46.000Z
2021-08-25T11:34:13.000Z
54.716867
170
0.699769
13,366
/* * Copyright 2021 Apollo Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.ctrip.framework.apollo.openapi.v1.controller; import com.ctrip.framework.apollo.common.dto.GrayReleaseRuleDTO; import com.ctrip.framework.apollo.common.dto.NamespaceDTO; import com.ctrip.framework.apollo.common.exception.BadRequestException; import com.ctrip.framework.apollo.common.utils.BeanUtils; import com.ctrip.framework.apollo.common.utils.RequestPrecondition; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.openapi.auth.ConsumerPermissionValidator; import com.ctrip.framework.apollo.openapi.dto.OpenGrayReleaseRuleDTO; import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceDTO; import com.ctrip.framework.apollo.openapi.util.OpenApiBeanUtils; import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO; import com.ctrip.framework.apollo.portal.service.NamespaceBranchService; import com.ctrip.framework.apollo.portal.service.ReleaseService; import com.ctrip.framework.apollo.portal.spi.UserService; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.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 javax.servlet.http.HttpServletRequest; @RestController("openapiNamespaceBranchController") @RequestMapping("/openapi/v1/envs/{env}") public class NamespaceBranchController { private final ConsumerPermissionValidator consumerPermissionValidator; private final ReleaseService releaseService; private final NamespaceBranchService namespaceBranchService; private final UserService userService; public NamespaceBranchController( final ConsumerPermissionValidator consumerPermissionValidator, final ReleaseService releaseService, final NamespaceBranchService namespaceBranchService, final UserService userService) { this.consumerPermissionValidator = consumerPermissionValidator; this.releaseService = releaseService; this.namespaceBranchService = namespaceBranchService; this.userService = userService; } @GetMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches") public OpenNamespaceDTO findBranch(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName) { NamespaceBO namespaceBO = namespaceBranchService.findBranch(appId, Env.valueOf(env.toUpperCase()), clusterName, namespaceName); if (namespaceBO == null) { return null; } return OpenApiBeanUtils.transformFromNamespaceBO(namespaceBO); } @PreAuthorize(value = "@consumerPermissionValidator.hasCreateNamespacePermission(#request, #appId)") @PostMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches") public OpenNamespaceDTO createBranch(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @RequestParam("operator") String operator, HttpServletRequest request) { RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(operator),"operator can not be empty"); if (userService.findByUserId(operator) == null) { throw new BadRequestException("operator " + operator + " not exists"); } NamespaceDTO namespaceDTO = namespaceBranchService.createBranch(appId, Env.valueOf(env.toUpperCase()), clusterName, namespaceName, operator); if (namespaceDTO == null) { return null; } return BeanUtils.transform(OpenNamespaceDTO.class, namespaceDTO); } @PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)") @DeleteMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}") public void deleteBranch(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @PathVariable String branchName, @RequestParam("operator") String operator, HttpServletRequest request) { RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(operator),"operator can not be empty"); if (userService.findByUserId(operator) == null) { throw new BadRequestException("operator " + operator + " not exists"); } boolean canDelete = consumerPermissionValidator.hasReleaseNamespacePermission(request, appId, namespaceName, env) || (consumerPermissionValidator.hasModifyNamespacePermission(request, appId, namespaceName, env) && releaseService.loadLatestRelease(appId, Env.valueOf(env), branchName, namespaceName) == null); if (!canDelete) { throw new AccessDeniedException("Forbidden operation. " + "Caused by: 1.you don't have release permission " + "or 2. you don't have modification permission " + "or 3. you have modification permission but branch has been released"); } namespaceBranchService.deleteBranch(appId, Env.valueOf(env.toUpperCase()), clusterName, namespaceName, branchName, operator); } @GetMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/rules") public OpenGrayReleaseRuleDTO getBranchGrayRules(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @PathVariable String branchName) { GrayReleaseRuleDTO grayReleaseRuleDTO = namespaceBranchService.findBranchGrayRules(appId, Env.valueOf(env.toUpperCase()), clusterName, namespaceName, branchName); if (grayReleaseRuleDTO == null) { return null; } return OpenApiBeanUtils.transformFromGrayReleaseRuleDTO(grayReleaseRuleDTO); } @PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)") @PutMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/rules") public void updateBranchRules(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @PathVariable String branchName, @RequestBody OpenGrayReleaseRuleDTO rules, @RequestParam("operator") String operator, HttpServletRequest request) { RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(operator),"operator can not be empty"); if (userService.findByUserId(operator) == null) { throw new BadRequestException("operator " + operator + " not exists"); } rules.setAppId(appId); rules.setClusterName(clusterName); rules.setNamespaceName(namespaceName); rules.setBranchName(branchName); GrayReleaseRuleDTO grayReleaseRuleDTO = OpenApiBeanUtils.transformToGrayReleaseRuleDTO(rules); namespaceBranchService .updateBranchGrayRules(appId, Env.valueOf(env.toUpperCase()), clusterName, namespaceName, branchName, grayReleaseRuleDTO, operator); } }
3e1fa7077d0ed0fa5cfdf222336a679f9ae0d8db
687
java
Java
src/main/java/org/scaffoldeditor/worldexport/mixins/QuadrupedModelAccessor.java
Sam54123/mc-world-export
b82632d76f012121de389276880ddb2eed9e6661
[ "MIT" ]
2
2021-11-30T20:59:36.000Z
2022-03-09T18:43:23.000Z
src/main/java/org/scaffoldeditor/worldexport/mixins/QuadrupedModelAccessor.java
Sam54123/mc-world-export
b82632d76f012121de389276880ddb2eed9e6661
[ "MIT" ]
2
2021-11-04T03:45:42.000Z
2022-03-27T00:23:16.000Z
src/main/java/org/scaffoldeditor/worldexport/mixins/QuadrupedModelAccessor.java
Sam54123/mc-world-export
b82632d76f012121de389276880ddb2eed9e6661
[ "MIT" ]
null
null
null
22.9
69
0.749636
13,367
package org.scaffoldeditor.worldexport.mixins; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; import net.minecraft.client.model.ModelPart; import net.minecraft.client.render.entity.model.QuadrupedEntityModel; @Mixin(QuadrupedEntityModel.class) public interface QuadrupedModelAccessor { @Accessor("head") ModelPart getHead(); @Accessor("body") ModelPart getBody(); @Accessor("rightHindLeg") ModelPart getRightHindLeg(); @Accessor("leftHindLeg") ModelPart getLeftHindLeg(); @Accessor("rightFrontLeg") ModelPart getRightFrontLeg(); @Accessor("leftFrontLeg") ModelPart getLeftFrontLeg(); }
3e1fa9201e0451ef31e10acf8292660181cc0c5d
2,857
java
Java
mantis-tests/src/test/java/ru/stqa/pft/soap/appmanager/ApplicationManager.java
SergeyTsiganovskiy/javatraining
8874c7d7682e53df4bcf19abc14f6d77e6cc9ceb
[ "Apache-2.0" ]
1
2017-07-07T19:42:48.000Z
2017-07-07T19:42:48.000Z
mantis-tests/src/test/java/ru/stqa/pft/soap/appmanager/ApplicationManager.java
SergeyTsiganovskiy/javatraining
8874c7d7682e53df4bcf19abc14f6d77e6cc9ceb
[ "Apache-2.0" ]
null
null
null
mantis-tests/src/test/java/ru/stqa/pft/soap/appmanager/ApplicationManager.java
SergeyTsiganovskiy/javatraining
8874c7d7682e53df4bcf19abc14f6d77e6cc9ceb
[ "Apache-2.0" ]
null
null
null
24.62931
105
0.680784
13,368
package ru.stqa.pft.soap.appmanager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.BrowserType; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import java.util.concurrent.TimeUnit; public class ApplicationManager { private final Properties properties; private WebDriver wd; private String browser; private RegistrationHelper registrationHelper; private FtpHelper ftp; private MailHelper mailHelper; private JamesHelper jamesHelper; private LoginHelper loginHelper; private DbHelper dbHelper; private SoapHelper soapHelper; public ApplicationManager(String browser) { this.browser = browser; properties = new Properties(); } public void init() throws IOException { String target = System.getProperty("target", "local"); properties.load(new FileReader(new File(String.format("src/test/resources/%s.properties", target)))); } public void stop() { if (wd != null) { wd.quit(); } } public HttpSession newSession() { return new HttpSession(this); } public String getProperty(String key) { return properties.getProperty(key); } public RegistrationHelper registration() { if (registrationHelper == null) { registrationHelper = new RegistrationHelper(this); } return registrationHelper; } public FtpHelper ftp(){ if (ftp == null){ ftp = new FtpHelper(this); } return ftp; } public WebDriver getDriver() { if (wd == null) { if (browser.equals(BrowserType.FIREFOX)) { wd = new FirefoxDriver(new FirefoxOptions().setLegacy(true)); } else if (browser.equals(BrowserType.CHROME)) { wd = new ChromeDriver(); } else { wd = new InternetExplorerDriver(); } wd.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); wd.manage().window().maximize(); wd.get(properties.getProperty("web.baseUrl")); } return wd; } public MailHelper mail(){ if (mailHelper == null){ mailHelper = new MailHelper(this); } return mailHelper; } public JamesHelper james(){ if (jamesHelper == null){ jamesHelper = new JamesHelper(this); } return jamesHelper; } public LoginHelper login(){ if (loginHelper == null){ loginHelper = new LoginHelper(this); } return loginHelper; } public DbHelper db(){ if (dbHelper == null){ dbHelper = new DbHelper(this); } return dbHelper; } public SoapHelper soap(){ if (soapHelper == null){ soapHelper = new SoapHelper(this); } return soapHelper; } }
3e1fa97690fbdaa7cb5ba2691f6eda86b40b73b1
1,528
java
Java
plugins/bluenimble-plugin-database.orientdb/src/main/java/com/bluenimble/platform/plugins/database/orientdb/tests/FindOne.java
bluenimble/serverless
909d8ec243e055f74c6bceaee475fdcb4a2db3de
[ "Apache-2.0" ]
38
2018-03-08T14:46:02.000Z
2019-05-04T00:28:56.000Z
plugins/bluenimble-plugin-database.orientdb/src/main/java/com/bluenimble/platform/plugins/database/orientdb/tests/FindOne.java
bluenimble/serverless
909d8ec243e055f74c6bceaee475fdcb4a2db3de
[ "Apache-2.0" ]
13
2020-03-04T21:53:20.000Z
2022-03-30T04:04:25.000Z
plugins/bluenimble-plugin-database.orientdb/src/main/java/com/bluenimble/platform/plugins/database/orientdb/tests/FindOne.java
bluenimble/serverless
909d8ec243e055f74c6bceaee475fdcb4a2db3de
[ "Apache-2.0" ]
4
2018-06-14T02:52:10.000Z
2018-09-10T17:43:34.000Z
38.2
81
0.760471
13,369
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bluenimble.platform.plugins.database.orientdb.tests; import com.bluenimble.platform.db.Database; import com.bluenimble.platform.db.DatabaseException; import com.bluenimble.platform.db.DatabaseObject; import com.bluenimble.platform.json.JsonObject; import com.bluenimble.platform.query.impls.JsonQuery; import com.bluenimble.platform.reflect.beans.impls.DefaultBeanSerializer; public class FindOne { public static void main (String [] args) throws DatabaseException { Database db = new DatabaseServer ().get (); DatabaseObject city = db.findOne ("Cities", new JsonQuery (new JsonObject ())); if (city != null) { System.out.println (city.toJson (new DefaultBeanSerializer (2, 2))); } } }
3e1fa9c8ee04c3770d273530368c748c3c13373b
2,249
java
Java
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/RolePermissionService.java
kubaobaokuiii/apollo
1ff70ccce250e0bec82162c8b9b41d9117ae2270
[ "Apache-2.0" ]
null
null
null
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/RolePermissionService.java
kubaobaokuiii/apollo
1ff70ccce250e0bec82162c8b9b41d9117ae2270
[ "Apache-2.0" ]
null
null
null
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/RolePermissionService.java
kubaobaokuiii/apollo
1ff70ccce250e0bec82162c8b9b41d9117ae2270
[ "Apache-2.0" ]
null
null
null
24.977778
108
0.673488
13,370
package com.ctrip.framework.apollo.portal.service; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.entity.po.Permission; import com.ctrip.framework.apollo.portal.entity.po.Role; import java.util.List; import java.util.Set; /** * @author Jason Song(nnheo@example.com) * */ public interface RolePermissionService { /** * Create role with permissions, note that role name should be unique */ public Role createRoleWithPermissions(Role role, Set<Long> permissionIds); // =====================用户角色相关================== /** * Assign role to users * * @return the users assigned roles */ public Set<String> assignRoleToUsers(String roleName, Set<String> userIds, String operatorUserId); /** * Remove role from users */ public void removeRoleFromUsers(String roleName, Set<String> userIds, String operatorUserId); /** * Query users with role */ public Set<UserInfo> queryUsersWithRole(String roleName); /** * Find role by role name, note that roleName should be unique */ public Role findRoleByRoleName(String roleName); // ===================== UserPermission 相关================== /** * Check whether user has the permission */ public boolean userHasPermission(String userId, String permissionType, String targetId); /** * Find the user's roles */ public List<Role> findUserRoles(String userId); /** * 校验是否为超级管理员 * @param userId * @return */ public boolean isSuperAdmin(String userId); // ========== Permission 相关 ========== /** * Create permission, note that permissionType + targetId should be unique */ public Permission createPermission(Permission permission); /** * Create permissions, note that permissionType + targetId should be unique */ public Set<Permission> createPermissions(Set<Permission> permissions); /** * delete permissions when delete app. */ public void deleteRolePermissionsByAppId(String appId, String operator); /** * delete permissions when delete app namespace. */ public void deleteRolePermissionsByAppIdAndNamespace(String appId, String namespaceName, String operator); }
3e1faa577ffbbf1ecafb12cee453663788913689
120
java
Java
Android/java/patrick/pramedia/wire/adapter/interfaceRVTimer.java
ProtoZxn99/WiRe
9b62576c3598f0b9d82609002383c53f4a2a347b
[ "MIT" ]
null
null
null
Android/java/patrick/pramedia/wire/adapter/interfaceRVTimer.java
ProtoZxn99/WiRe
9b62576c3598f0b9d82609002383c53f4a2a347b
[ "MIT" ]
null
null
null
Android/java/patrick/pramedia/wire/adapter/interfaceRVTimer.java
ProtoZxn99/WiRe
9b62576c3598f0b9d82609002383c53f4a2a347b
[ "MIT" ]
null
null
null
20
39
0.75
13,371
package patrick.pramedia.wire.adapter; public interface interfaceRVTimer { public void click(int position); }
3e1faa8f2150eae239c3d181634116109f517cd8
12,434
java
Java
opensrp-opd/src/main/java/org/smartregister/opd/presenter/OpdProfileActivityPresenter.java
opensrp/opensrp-client-opd
28d8bfdbadc0a62ee06e6a74e58de8503ab890a3
[ "Apache-2.0" ]
null
null
null
opensrp-opd/src/main/java/org/smartregister/opd/presenter/OpdProfileActivityPresenter.java
opensrp/opensrp-client-opd
28d8bfdbadc0a62ee06e6a74e58de8503ab890a3
[ "Apache-2.0" ]
53
2019-09-16T09:06:00.000Z
2020-09-02T15:29:20.000Z
opensrp-opd/src/main/java/org/smartregister/opd/presenter/OpdProfileActivityPresenter.java
opensrp/opensrp-client-opd
28d8bfdbadc0a62ee06e6a74e58de8503ab890a3
[ "Apache-2.0" ]
1
2019-10-12T08:58:53.000Z
2019-10-12T08:58:53.000Z
39.09434
176
0.662243
13,372
package org.smartregister.opd.presenter; import android.app.Activity; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.vijay.jsonwizard.constants.JsonFormConstants; import com.vijay.jsonwizard.domain.Form; import org.json.JSONException; import org.json.JSONObject; import org.smartregister.AllConstants; import org.smartregister.clientandeventmodel.Event; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.domain.tag.FormTag; import org.smartregister.opd.OpdLibrary; import org.smartregister.opd.R; import org.smartregister.opd.contract.OpdProfileActivityContract; import org.smartregister.opd.interactor.OpdProfileInteractor; import org.smartregister.opd.listener.OpdEventActionCallBack; import org.smartregister.opd.model.OpdProfileActivityModel; import org.smartregister.opd.pojo.OpdDiagnosisAndTreatmentForm; import org.smartregister.opd.pojo.OpdEventClient; import org.smartregister.opd.pojo.OpdMetadata; import org.smartregister.opd.pojo.RegisterParams; import org.smartregister.opd.tasks.FetchRegistrationDataTask; import org.smartregister.opd.utils.AppExecutors; import org.smartregister.opd.utils.OpdConstants; import org.smartregister.opd.utils.OpdDbConstants; import org.smartregister.opd.utils.OpdEventUtils; import org.smartregister.opd.utils.OpdJsonFormUtils; import org.smartregister.opd.utils.OpdUtils; import org.smartregister.util.Utils; import java.lang.ref.WeakReference; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import timber.log.Timber; /** * Created by Ephraim Kigamba - efpyi@example.com on 2019-09-27 */ public class OpdProfileActivityPresenter implements OpdProfileActivityContract.Presenter, OpdProfileActivityContract.InteractorCallBack, OpdEventActionCallBack { private WeakReference<OpdProfileActivityContract.View> mProfileView; private OpdProfileActivityContract.Interactor mProfileInteractor; private OpdProfileActivityModel model; private JSONObject form = null; public OpdProfileActivityPresenter(OpdProfileActivityContract.View profileView) { mProfileView = new WeakReference<>(profileView); mProfileInteractor = new OpdProfileInteractor(this); model = new OpdProfileActivityModel(); } @Override public void onDestroy(boolean isChangingConfiguration) { mProfileView = null;//set to null on destroy // Inform interactor if (mProfileInteractor != null) { mProfileInteractor.onDestroy(isChangingConfiguration); } // Activity destroyed set interactor to null if (!isChangingConfiguration) { mProfileInteractor = null; } } @Nullable @Override public OpdProfileActivityContract.View getProfileView() { if (mProfileView != null) { return mProfileView.get(); } return null; } @Override public void onRegistrationSaved(@Nullable CommonPersonObjectClient client, boolean isEdit) { CommonPersonObjectClient reassignableClient = client; if (getProfileView() != null) { getProfileView().hideProgressDialog(); if (reassignableClient != null) { getProfileView().setClient(reassignableClient); } else { reassignableClient = getProfileView().getClient(); } if (isEdit && reassignableClient != null) { refreshProfileTopSection(reassignableClient.getColumnmaps()); } } } @Override public void onFetchedSavedDiagnosisAndTreatmentForm(@Nullable OpdDiagnosisAndTreatmentForm diagnosisAndTreatmentForm, @NonNull String caseId, @NonNull String entityTable) { try { if (diagnosisAndTreatmentForm != null) { form = new JSONObject(diagnosisAndTreatmentForm.getForm()); } startFormActivity(form, caseId, entityTable); } catch (JSONException ex) { Timber.e(ex); } } @Override public void startFormActivity(@Nullable JSONObject form, @NonNull String caseId, @NonNull String entityTable) { if (getProfileView() != null && form != null) { HashMap<String, String> intentKeys = new HashMap<>(); intentKeys.put(OpdConstants.IntentKey.BASE_ENTITY_ID, caseId); intentKeys.put(OpdConstants.IntentKey.ENTITY_TABLE, entityTable); getProfileView().startFormActivity(form, intentKeys); } } @Override public void refreshProfileTopSection(@NonNull Map<String, String> client) { OpdProfileActivityContract.View profileView = getProfileView(); if (profileView != null) { profileView.setProfileName(client.get(OpdDbConstants.KEY.FIRST_NAME) + " " + client.get(OpdDbConstants.KEY.LAST_NAME)); String translatedYearInitial = profileView.getString(R.string.abbrv_years); String dobString = client.get(OpdConstants.KEY.DOB); if (dobString != null) { String clientAge = OpdUtils.getClientAge(Utils.getDuration(dobString), translatedYearInitial); profileView.setProfileAge(clientAge); } String gender = ""; try { gender = Utils.getValue(client, OpdDbConstants.KEY.GENDER, true); profileView.setProfileGender(gender); } catch (Exception e) { Timber.e(e); profileView.setProfileGender(gender); } profileView.setProfileID(Utils.getValue(client, OpdDbConstants.KEY.REGISTER_ID, false)); int defaultImage = gender.equalsIgnoreCase("Male") ? R.drawable.avatar_man : R.drawable.avatar_woman; profileView.setProfileImage(Utils.getValue(client, OpdDbConstants.KEY.ID, false), defaultImage); } } @Override public void startForm(@NonNull String formName, @NonNull CommonPersonObjectClient commonPersonObjectClient) { Map<String, String> clientMap = commonPersonObjectClient.getColumnmaps(); String entityTable = clientMap.get(OpdConstants.IntentKey.ENTITY_TABLE); HashMap<String, String> injectedValues = getInjectedFields(formName, commonPersonObjectClient.getCaseId()); startFormActivity(formName, commonPersonObjectClient.getCaseId(), entityTable, injectedValues); } @Override public HashMap<String, String> getInjectedFields(@NonNull String formName, @NonNull String entityId) { return OpdUtils.getInjectableFields(formName, entityId); } public void startFormActivity(@NonNull String formName, @NonNull String caseId, @NonNull String entityTable, @Nullable HashMap<String, String> injectedValues) { if (mProfileView != null) { form = null; try { String locationId = OpdUtils.context().allSharedPreferences().getPreference(AllConstants.CURRENT_LOCATION_ID); form = model.getFormAsJson(formName, caseId, locationId, injectedValues); // Fetch saved form & continue editing if (formName.equals(OpdConstants.Form.OPD_DIAGNOSIS_AND_TREAT)) { mProfileInteractor.fetchSavedDiagnosisAndTreatmentForm(caseId, entityTable); } else { startFormActivity(form, caseId, entityTable); } } catch (JSONException e) { Timber.e(e); } } } @Override public void saveVisitOrDiagnosisForm(@NonNull String eventType, @Nullable Intent data) { String jsonString = null; OpdEventUtils opdEventUtils = new OpdEventUtils(new AppExecutors()); if (data != null) { jsonString = data.getStringExtra(OpdConstants.JSON_FORM_EXTRA.JSON); } if (jsonString == null) { return; } if (eventType.equals(OpdConstants.EventType.CHECK_IN)) { try { Event opdVisitEvent = OpdLibrary.getInstance().processOpdCheckInForm(eventType, jsonString, data); opdEventUtils.saveEvents(Collections.singletonList(opdVisitEvent), this); } catch (JSONException e) { Timber.e(e); } } else if (eventType.equals(OpdConstants.EventType.DIAGNOSIS_AND_TREAT)) { try { List<Event> opdDiagnosisAndTreatment = OpdLibrary.getInstance().processOpdForm(jsonString, data); opdEventUtils.saveEvents(opdDiagnosisAndTreatment, this); } catch (JSONException e) { Timber.e(e); } } } @Override public void saveUpdateRegistrationForm(@NonNull String jsonString, @NonNull RegisterParams registerParams) { try { if (registerParams.getFormTag() == null) { registerParams.setFormTag(OpdJsonFormUtils.formTag(OpdUtils.getAllSharedPreferences())); } OpdEventClient opdEventClient = processRegistration(jsonString, registerParams.getFormTag()); if (opdEventClient == null) { return; } mProfileInteractor.saveRegistration(opdEventClient, jsonString, registerParams, this); } catch (Exception e) { Timber.e(e); } } @Nullable @Override public OpdEventClient processRegistration(@NonNull String jsonString, @NonNull FormTag formTag) { OpdEventClient opdEventClient = OpdJsonFormUtils.processOpdDetailsForm(jsonString, formTag); //TODO: Show the user this error toast //showErrorToast(); if (opdEventClient == null) { return null; } return opdEventClient; } @Override public void onOpdEventSaved() { OpdProfileActivityContract.View view = getProfileView(); if (view != null) { view.getActionListenerForProfileOverview().onActionReceive(); view.getActionListenerForVisitFragment().onActionReceive(); view.hideProgressDialog(); } } @Override public void onUpdateRegistrationBtnCLicked(@NonNull String baseEntityId) { if (getProfileView() != null) { Utils.startAsyncTask(new FetchRegistrationDataTask(new WeakReference<>(getProfileView()), jsonForm -> { OpdMetadata metadata = OpdUtils.metadata(); OpdProfileActivityContract.View profileView = getProfileView(); if (profileView != null && metadata != null && jsonForm != null) { Context context = profileView.getContext(); Intent intent = new Intent(context, metadata.getOpdFormActivity()); Form formParam = new Form(); formParam.setWizard(false); formParam.setHideSaveLabel(true); formParam.setNextLabel(""); intent.putExtra(JsonFormConstants.JSON_FORM_KEY.FORM, formParam); intent.putExtra(JsonFormConstants.JSON_FORM_KEY.JSON, jsonForm); profileView.startActivityForResult(intent, OpdJsonFormUtils.REQUEST_CODE_GET_JSON); } }), new String[]{baseEntityId}); } } public void saveCloseForm(String encounterType, Intent data) { String jsonString = null; if (data != null) { jsonString = data.getStringExtra(OpdConstants.JSON_FORM_EXTRA.JSON); } if (jsonString == null) { return; } try { List<Event> pncFormEvent = OpdLibrary.getInstance().processOpdForm(jsonString, data); mProfileInteractor.saveEvents(pncFormEvent, this); } catch (JSONException e) { Timber.e(e); } } @Override public void onEventSaved(List<Event> events) { OpdProfileActivityContract.View view = getProfileView(); if (view != null) { view.hideProgressDialog(); } for (Event event : events) { if (OpdConstants.EventType.OPD_CLOSE.equals(event.getEventType()) || OpdConstants.EventType.DEATH.equals(event.getEventType())) { ((Activity) getProfileView()).finish(); break; } } } }
3e1fac44ecef3d92a894838c41e903df4d5afaac
1,632
java
Java
samples/forum/src/main/java/org/apache/polygene/sample/forum/rest/resource/forum/ForumResource.java
apache/polygene-java
031beef870302a0bd01bd5895ce849e00f2d5d5b
[ "MIT" ]
60
2017-02-06T10:42:51.000Z
2022-02-12T14:41:17.000Z
samples/forum/src/main/java/org/apache/polygene/sample/forum/rest/resource/forum/ForumResource.java
DalavanCloud/attic-polygene-java
031beef870302a0bd01bd5895ce849e00f2d5d5b
[ "MIT" ]
3
2015-07-28T10:23:31.000Z
2016-12-03T14:56:17.000Z
samples/forum/src/main/java/org/apache/polygene/sample/forum/rest/resource/forum/ForumResource.java
DalavanCloud/attic-polygene-java
031beef870302a0bd01bd5895ce849e00f2d5d5b
[ "MIT" ]
17
2015-07-26T14:19:10.000Z
2016-11-29T17:38:05.000Z
37.090909
129
0.752451
13,373
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package org.apache.polygene.sample.forum.rest.resource.forum; import org.apache.polygene.api.identity.StringIdentity; import org.apache.polygene.library.rest.server.api.ContextResource; import org.apache.polygene.library.rest.server.api.ObjectSelection; import org.apache.polygene.library.rest.server.api.SubResources; import org.apache.polygene.sample.forum.data.entity.Forum; import org.restlet.resource.ResourceException; /** * TODO */ public class ForumResource extends ContextResource implements SubResources { @Override public void resource( String segment ) throws ResourceException { selectFromManyAssociation( ObjectSelection.current().get( Forum.class ).boards(), StringIdentity.identityOf( segment ) ); subResource( BoardResource.class ); } }
3e1fac836c0a8637e4fabe2059bc6b954ae03ec8
1,190
java
Java
src/javasource/slackmessage/proxies/Enum_SlashCommand_ResponseVisibility.java
ppoetsma/SlackMessage
f76d53418c0187f86032fe71b54d2a94a4044b11
[ "Apache-2.0" ]
null
null
null
src/javasource/slackmessage/proxies/Enum_SlashCommand_ResponseVisibility.java
ppoetsma/SlackMessage
f76d53418c0187f86032fe71b54d2a94a4044b11
[ "Apache-2.0" ]
null
null
null
src/javasource/slackmessage/proxies/Enum_SlashCommand_ResponseVisibility.java
ppoetsma/SlackMessage
f76d53418c0187f86032fe71b54d2a94a4044b11
[ "Apache-2.0" ]
null
null
null
36.060606
181
0.731092
13,374
// This file was generated by Mendix Modeler. // // WARNING: Code you write here will be lost the next time you deploy the project. package slackmessage.proxies; public enum Enum_SlashCommand_ResponseVisibility { ephemeral(new java.lang.String[][] { new java.lang.String[] { "en_US", "Visibile to the user only" }, new java.lang.String[] { "nl_NL", "Alle voor de gebruiker zichtbaar" } }), in_channel(new java.lang.String[][] { new java.lang.String[] { "en_US", "Visibile in the channel" }, new java.lang.String[] { "nl_NL", "Zichtbaar voor iedereen in het kanaal" } }); private java.util.Map<java.lang.String, java.lang.String> captions; private Enum_SlashCommand_ResponseVisibility(java.lang.String[][] captionStrings) { this.captions = new java.util.HashMap<java.lang.String, java.lang.String>(); for (java.lang.String[] captionString : captionStrings) captions.put(captionString[0], captionString[1]); } public java.lang.String getCaption(java.lang.String languageCode) { if (captions.containsKey(languageCode)) return captions.get(languageCode); return captions.get("en_US"); } public java.lang.String getCaption() { return captions.get("en_US"); } }
3e1facf9e29407d76acbb2c6d70b753f40d87814
14,604
java
Java
src/main/java/com/seismicgames/spark_annotations/Setup.java
SeismicGames/spark_annotations
a309ad3f64f10119ae39c241ffaa4626c3f19d2e
[ "MIT" ]
null
null
null
src/main/java/com/seismicgames/spark_annotations/Setup.java
SeismicGames/spark_annotations
a309ad3f64f10119ae39c241ffaa4626c3f19d2e
[ "MIT" ]
null
null
null
src/main/java/com/seismicgames/spark_annotations/Setup.java
SeismicGames/spark_annotations
a309ad3f64f10119ae39c241ffaa4626c3f19d2e
[ "MIT" ]
null
null
null
39.684783
140
0.582169
13,375
package com.seismicgames.spark_annotations; import com.google.gson.Gson; import com.seismicgames.spark_annotations.annotations.Controller; import com.seismicgames.spark_annotations.annotations.Filter; import com.seismicgames.spark_annotations.annotations.Route; import com.seismicgames.spark_annotations.annotations.SparkWebSocket; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.reflections.Reflections; import org.reflections.scanners.MethodAnnotationsScanner; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import com.seismicgames.spark_annotations.exceptions.RouteException; import com.seismicgames.spark_annotations.handlers.WebSocketHandler; import spark.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Set; public class Setup { private static class BackupTemplateEngine extends TemplateEngine { @Override public String render(ModelAndView modelAndView) { LOGGER.error("Something went wrong, can't render to the registered TemplateEngine"); return new Gson().toJson(modelAndView.getModel()); } } // const private static final Logger LOGGER = LogManager.getLogger(Setup.class); // static parameters private static boolean initialized = false; private static String controllerPackage; private static String filterPackage; private static String wsPackage; private static Class<? extends TemplateEngine> templateEngine; private static String mainTemplate; // for when you want to search your entire package for controllers, Shofilters and websockets public static synchronized void Init(String packageName, int maxThreads, int minThreads, int timeout, Class<? extends TemplateEngine> templateEngine, String mainTemplate) { Setup.Init(packageName, packageName, packageName, maxThreads, minThreads, timeout, templateEngine, mainTemplate); } public static synchronized void Init(String controllerPackage, String filterPackage, String wsPackage, int maxThreads, int minThreads, int timeout, Class<? extends TemplateEngine> templateEngine, String mainTemplate) { if(initialized) { return; } Setup.controllerPackage = controllerPackage; Setup.filterPackage = filterPackage; Setup.wsPackage = wsPackage; Setup.templateEngine = templateEngine; Setup.mainTemplate = mainTemplate; // set up the server Spark.threadPool(maxThreads, minThreads, timeout); // set up static files Spark.staticFiles.location("/public"); // set up 500 error handling Spark.internalServerError(Setup::internalErrorRender); Spark.notFound(Setup::notFoundErrorRender); // set up exception catching Spark.exception(RouteException.class, Setup::handleError); Spark.exception(InvocationTargetException.class, (exception, request, response) -> { InvocationTargetException ex = (InvocationTargetException) exception; handleError(ex.getCause(), request, response); }); // set up web socket handlers wsSetup(); // set up the filters filterSetup(); // set up the routes routeSetup(); Spark.init(); LOGGER.debug("Started cps server..."); initialized = true; } // routes private static void routeSetup() { LOGGER.debug("Setting up routes"); Reflections reflections = new Reflections(controllerPackage); Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Controller.class); for (Class clazz : classes) { LOGGER.debug("Adding controller {}", clazz.getSimpleName()); // get class path Controller controller = (Controller) clazz.getAnnotation(Controller.class); String path = controller.path(); if (path.endsWith("/")) { path = path.substring(0, -1); } for (Method method : clazz.getMethods()) { if (!method.isAnnotationPresent(Route.class)) { continue; } if (!isValidRouteMethod(clazz, method)) { continue; } Object obj; try { obj = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.error("Couldn't create controller {}", clazz.getSimpleName()); LOGGER.error(e); continue; } Route route = method.getAnnotation(Route.class); final String fullPath = path + route.path(); LOGGER.debug("Adding route: {}, path: {} method: {}", method.getName(), path, route.method()); TemplateEngine engine; try { engine = templateEngine.newInstance(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.error("Couldn't instantiate Template Engine "); engine = new BackupTemplateEngine(); } switch (route.method()) { case get: Spark.get(fullPath, (request, response) -> { LOGGER.debug("GET - path: {}", fullPath); return new ModelAndView(method.invoke(obj, request, response), route.template()); }, engine ); break; case post: Spark.post(fullPath, (request, response) -> { LOGGER.debug("POST - path: {}", fullPath); return new ModelAndView(method.invoke(obj, request, response), route.template()); }, engine ); break; case put: Spark.put(fullPath, (request, response) -> { LOGGER.debug("PUT - path: {}", fullPath); return new ModelAndView(method.invoke(obj, request, response), route.template()); }, engine ); break; case delete: Spark.delete(fullPath, (request, response) -> { LOGGER.debug("DELETE - path: {}", fullPath); return new ModelAndView(method.invoke(obj, request, response), route.template()); }, engine ); break; case options: // TODO: do we need this? Spark.options(fullPath, (request, response) -> { LOGGER.debug("OPTIONS - path: {}", fullPath); return new ModelAndView(method.invoke(obj, request, response), route.template()); }, engine ); break; } } } LOGGER.debug("Finished setting up routes"); } private static boolean isValidRouteMethod(Class clazz, Method method) { // TODO: validate controller class ? // validate controller methods Class[] classes = method.getParameterTypes(); if (!classes[0].equals(Request.class)) { LOGGER.warn("Couldn't register method {} for controller {}, invalid first parameter", method.getName(), clazz.getSimpleName()); return false; } if (!classes[1].equals(Response.class)) { LOGGER.warn("Couldn't register method {} for controller {}, invalid second parameter", method.getName(), clazz.getSimpleName()); return false; } if (!method.getReturnType().equals(Map.class)) { LOGGER.warn("Couldn't register method {} for controller {}, invalid return type", method.getName(), clazz.getSimpleName()); return false; } return true; } // end routes // filters private static void filterSetup() { LOGGER.debug("Setting up filters"); Reflections reflections = new Reflections(filterPackage, new MethodAnnotationsScanner()); Set<Method> methods = reflections.getMethodsAnnotatedWith(Filter.class); for(Method method : methods) { if(!Setup.isValidFilterMethod(method.getDeclaringClass(), method)) { continue; } Object obj; try { obj = method.getDeclaringClass().newInstance(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.error("Couldn't create filter class {}", method.getDeclaringClass().getSimpleName()); LOGGER.error(e); continue; } Filter filter = method.getAnnotation(com.seismicgames.spark_annotations.annotations.Filter.class); LOGGER.debug("Adding filter: {}, class: {} when: {}", method.getName(), method.getDeclaringClass().getSimpleName(), filter.when()); switch (filter.when()) { case before: Spark.before((request, response) -> method.invoke(obj, request, response)); break; case after: Spark.after((request, response) -> method.invoke(obj, request, response)); break; } } LOGGER.debug("Finished setting up filters"); } private static boolean isValidFilterMethod(Class clazz, Method method) { // validate controller methods Class[] classes = method.getParameterTypes(); if (!classes[0].equals(Request.class)) { LOGGER.warn("Couldn't register method {} for filter {}, invalid first parameter", method.getName(), clazz.getSimpleName()); return false; } if (!classes[1].equals(Response.class)) { LOGGER.warn("Couldn't register method {} for filter {}, invalid second parameter", method.getName(), clazz.getSimpleName()); return false; } return true; } // end filters // websockets private static void wsSetup() { LOGGER.debug("Setting up websocket handlers"); Reflections reflections = new Reflections(wsPackage, new MethodAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner()); Set<Class<?>> classes = reflections.getTypesAnnotatedWith(SparkWebSocket.class); for (Class clazz : classes) { if(!clazz.isAnnotationPresent(WebSocket.class)) { //websocket needs to have both continue; } SparkWebSocket sws = (SparkWebSocket) clazz.getAnnotation(SparkWebSocket.class); LOGGER.debug("Adding websocket handler {}", clazz.getSimpleName()); if(!Setup.isValidWebSocketClass(clazz)) { continue; } WebSocketHandler.IWebSocket obj; try { obj = (WebSocketHandler.IWebSocket) clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.error("Couldn't create websocket class {}", clazz.getSimpleName()); LOGGER.error(e); continue; } WebSocketHandler.getInstance().addHandler(obj); Spark.webSocket(sws.path(), obj); } } private static boolean isValidWebSocketClass(Class clazz) { return WebSocketHandler.IWebSocket.class.isAssignableFrom(clazz); } // end websockets // error handlers private static String internalErrorRender(Request request, Response response) { TemplateEngine engine; try { engine = templateEngine.newInstance(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.error("Couldn't instantiate Template Engine ", e); engine = new BackupTemplateEngine(); } HashMap<String , String> map = new HashMap<>(); map.put("error", "true"); map.put("errorMsg", "There as an error on the server"); map.put("code", "500"); return engine.render(new ModelAndView(map, Setup.mainTemplate)); } private static String notFoundErrorRender(Request request, Response response) { TemplateEngine engine; try { engine = templateEngine.newInstance(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.error("Couldn't instantiate Template Engine ", e); engine = new BackupTemplateEngine(); } HashMap<String, String> map = new HashMap<>(); map.put("error", "true"); map.put("errorMsg", "The page you were looking for was not found"); map.put("code", "404"); return engine.render(new ModelAndView(map, Setup.mainTemplate)); } private static void handleError(Throwable exception, Request request, Response response) { RouteException re = (RouteException) exception; TemplateEngine engine; try { engine = templateEngine.newInstance(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.error("Couldn't instantiate Template Engine ", e); engine = new BackupTemplateEngine(); } HashMap<String, String> map = new HashMap<>(); map.put("error", "true"); map.put("errorMsg",re.getMessage()); StringBuilder sb = new StringBuilder(); for (StackTraceElement st : re.getStackTrace()) { sb.append(st.toString()).append("<br />"); } map.put("errorStack", sb.toString()); map.put("code", Integer.toString(re.code)); response.status(re.code); response.body(engine.render(new ModelAndView(map, Setup.mainTemplate))); } // end error handlers }
3e1fad17bbbe3a420bb01f2c62e57659800b33c5
25,542
java
Java
infrastructure/src/main/java/org/corfudb/infrastructure/ServerContext.java
CorfuDB/CORFU
8a113dffb26dfc889c9e7a5c39d606b9f441dc79
[ "Apache-2.0" ]
null
null
null
infrastructure/src/main/java/org/corfudb/infrastructure/ServerContext.java
CorfuDB/CORFU
8a113dffb26dfc889c9e7a5c39d606b9f441dc79
[ "Apache-2.0" ]
null
null
null
infrastructure/src/main/java/org/corfudb/infrastructure/ServerContext.java
CorfuDB/CORFU
8a113dffb26dfc889c9e7a5c39d606b9f441dc79
[ "Apache-2.0" ]
null
null
null
36.751079
109
0.638008
13,376
package org.corfudb.infrastructure; import static org.corfudb.infrastructure.logreplication.LogReplicationConfig.DEFAULT_MAX_NUM_MSG_PER_BATCH; import static org.corfudb.infrastructure.logreplication.LogReplicationConfig.MAX_DATA_MSG_SIZE_SUPPORTED; import static org.corfudb.infrastructure.logreplication.LogReplicationConfig.MAX_CACHE_NUM_ENTRIES; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.netty.channel.EventLoopGroup; import java.io.File; import java.nio.file.Files; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nonnull; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.corfudb.comm.ChannelImplementation; import org.corfudb.infrastructure.datastore.DataStore; import org.corfudb.infrastructure.datastore.KvDataStore.KvRecord; import org.corfudb.infrastructure.paxos.PaxosDataStore; import org.corfudb.runtime.CorfuRuntime; import org.corfudb.runtime.CorfuRuntime.CorfuRuntimeParameters; import org.corfudb.runtime.exceptions.WrongEpochException; import org.corfudb.runtime.proto.service.CorfuMessage.PriorityLevel; import org.corfudb.runtime.view.ConservativeFailureHandlerPolicy; import org.corfudb.runtime.view.IReconfigurationHandlerPolicy; import org.corfudb.runtime.view.Layout; import org.corfudb.runtime.view.Layout.LayoutSegment; import org.corfudb.util.NodeLocator; import org.corfudb.util.UuidUtils; import org.corfudb.utils.lock.Lock; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Server Context: * <ul> * <li>Contains the common node level {@link DataStore}</li> * <li>Responsible for Server level EPOCH </li> * <li>Should contain common services/utilities that the different Servers in a node require.</li> * </ul> * * <p>Note: * It is created in {@link CorfuServer} and then * passed to all the servers including {@link NettyServerRouter}. * * <p>Created by mdhawan on 8/5/16. */ @Slf4j public class ServerContext implements AutoCloseable { // Layout Server private static final String PREFIX_EPOCH = "SERVER_EPOCH"; private static final String KEY_EPOCH = "CURRENT"; private static final String PREFIX_LAYOUT = "LAYOUT"; private static final String KEY_LAYOUT = "CURRENT"; private static final String PREFIX_LAYOUTS = "LAYOUTS"; // Sequencer Server private static final String KEY_SEQUENCER = "SEQUENCER"; private static final String PREFIX_SEQUENCER_EPOCH = "EPOCH"; // Management Server private static final String PREFIX_MANAGEMENT = "MANAGEMENT"; private static final String MANAGEMENT_LAYOUT = "LAYOUT"; // LogUnit Server private static final String PREFIX_LOGUNIT = "LOGUNIT"; private static final String EPOCH_WATER_MARK = "EPOCH_WATER_MARK"; // Corfu Replication Server public static final String PLUGIN_CONFIG_FILE_PATH = "../resources/corfu_plugin_config.properties"; /** The node Id, stored as a base64 string. */ private static final String NODE_ID = "NODE_ID"; private static final KvRecord<String> NODE_ID_RECORD = KvRecord.of(NODE_ID, String.class); private static final KvRecord<Layout> CURR_LAYOUT_RECORD = KvRecord.of( PREFIX_LAYOUT, KEY_LAYOUT, Layout.class ); private static final KvRecord<Long> SERVER_EPOCH_RECORD= KvRecord.of( PREFIX_EPOCH, KEY_EPOCH, Long.class ); private static final KvRecord<Long> SEQUENCER_RECORD = KvRecord.of( KEY_SEQUENCER, PREFIX_SEQUENCER_EPOCH, Long.class ); public static final KvRecord<Layout> MANAGEMENT_LAYOUT_RECORD = KvRecord.of( PREFIX_MANAGEMENT, MANAGEMENT_LAYOUT, Layout.class ); private static final KvRecord<Long> LOG_UNIT_WATERMARK_RECORD = KvRecord.of( PREFIX_LOGUNIT, EPOCH_WATER_MARK, Long.class ); /** * various duration constants. */ public static final Duration SHUTDOWN_TIMER = Duration.ofSeconds(5); @Getter private final Map<String, Object> serverConfig; @Getter private final DataStore dataStore; @Getter @Setter private IServerRouter serverRouter; @Getter @Setter private IReconfigurationHandlerPolicy failureHandlerPolicy; @Getter private final EventLoopGroup clientGroup; @Getter private final EventLoopGroup workerGroup; @Getter (AccessLevel.PACKAGE) private final NodeLocator nodeLocator; @Getter private final String localEndpoint; @Getter private final Set<String> dsFilePrefixesForCleanup = Sets.newHashSet(PaxosDataStore.PREFIX_PHASE_1, PaxosDataStore.PREFIX_PHASE_2, PREFIX_LAYOUTS); /** * Returns a new ServerContext. * * @param serverConfig map of configuration strings to objects */ public ServerContext(Map<String, Object> serverConfig) { this.serverConfig = serverConfig; this.dataStore = new DataStore(serverConfig, this::dataStoreFileCleanup); generateNodeId(); this.failureHandlerPolicy = new ConservativeFailureHandlerPolicy(); // Setup the netty event loops. In tests, these loops may be provided by // a test framework to save resources. final boolean providedEventLoops = getChannelImplementation().equals(ChannelImplementation.LOCAL); if (providedEventLoops) { clientGroup = getServerConfig(EventLoopGroup.class, "client"); workerGroup = getServerConfig(EventLoopGroup.class, "worker"); } else { clientGroup = getNewClientGroup(); workerGroup = getNewWorkerGroup(); } nodeLocator = NodeLocator .parseString(serverConfig.get("--address") + ":" + serverConfig.get("<port>")); localEndpoint = nodeLocator.toEndpointUrl(); } int getBaseServerThreadCount() { Optional<String> threadCount = getServerConfig("--base-server-threads"); return threadCount.map(Integer::parseInt).orElse(1); } public int getLogUnitThreadCount() { Optional<String> threadCount = getServerConfig("--logunit-threads"); return threadCount.map(Integer::parseInt).orElse(Runtime.getRuntime().availableProcessors() * 2); } public int getManagementServerThreadCount() { Optional<String> threadCount = getServerConfig("--management-server-threads"); return threadCount.map(Integer::parseInt).orElse(4); } public String getPluginConfigFilePath() { String pluginConfigFilePath = getServerConfig(String.class, "--plugin"); return pluginConfigFilePath == null ? PLUGIN_CONFIG_FILE_PATH : pluginConfigFilePath; } /** * Get an ExecutorService that can be used by the servers to * process RPCs. Uses a ServerThreadFactory as the underlying * thread factory. * @param threadCount The number of threads to use in the pool * @param threadPrefix The naming prefix * @return The newly created ExecutorService */ public ExecutorService getExecutorService(int threadCount, String threadPrefix) { return getExecutorService(threadCount, new ServerThreadFactory(threadPrefix, new ServerThreadFactory.ExceptionHandler())); } /** * Get an ExecutorService that can be used by the servers to * process RPCs. * @param threadCount The number of threads to use in the pool * @param threadFactory The underlying thread factory * @return The newly created ExecutorService */ public ExecutorService getExecutorService(int threadCount, @Nonnull ThreadFactory threadFactory) { return Executors.newFixedThreadPool(threadCount, threadFactory); } /** * Get the max number of messages can be sent over per batch. * @return */ public int getLogReplicationMaxNumMsgPerBatch() { String val = getServerConfig(String.class, "--snapshot-batch"); return val == null ? DEFAULT_MAX_NUM_MSG_PER_BATCH : Integer.parseInt(val); } public int getLockLeaseDuration() { Integer lockLeaseDuration; try { lockLeaseDuration = getServerConfig(Integer.class, "--lock-lease"); } catch (ClassCastException e) { // In the testing framework we only support Strings lockLeaseDuration = Integer.valueOf(getServerConfig(String.class, "--lock-lease")); } return lockLeaseDuration == null ? Lock.leaseDuration : lockLeaseDuration; } /** * Get the max size of the log replication data message used by both snapshot data message and * log entry sync data message. * * @return max data message size */ public int getLogReplicationMaxDataMessageSize() { String val = getServerConfig(String.class, "--max-replication-data-message-size"); return val == null ? MAX_DATA_MSG_SIZE_SUPPORTED : Integer.parseInt(val); } /** * Get the max size of LR's runtime cache in number of entries. * * @return max cache number of entries */ public int getLogReplicationCacheMaxSize() { String val = getServerConfig(String.class, "--lrCacheSize"); return val == null ? MAX_CACHE_NUM_ENTRIES : Integer.parseInt(val); } /** * Cleanup the DataStore files with names that are prefixes of the specified * fileName when so that the number of these files don't exceed the user-defined * retention limit. Cleanup is always done on files with lower epochs. */ private void dataStoreFileCleanup(String fileName) { String logDirPath = getServerConfig(String.class, "--log-path"); if (logDirPath == null) { return; } File logDir = new File(logDirPath); Set<String> prefixesToClean = getDsFilePrefixesForCleanup(); int numRetention = Integer.parseInt(getServerConfig(String.class, "--metadata-retention")); prefixesToClean.stream() .filter(fileName::startsWith) .forEach(prefix -> { File[] foundFiles = logDir.listFiles((dir, name) -> name.startsWith(prefix)); if (foundFiles == null || foundFiles.length <= numRetention) { log.debug("DataStore cleanup not started for prefix: {}.", prefix); return; } log.debug("Start cleaning up DataStore files with prefix: {}.", prefix); Arrays.stream(foundFiles) .sorted(Comparator.comparingInt(file -> { // Extract epoch number from file name and cast to int for comparision Matcher matcher = Pattern.compile("\\d+").matcher(file.getName()); return matcher.find(prefix.length()) ? Integer.parseInt(matcher.group()) : 0; })) .limit(foundFiles.length - numRetention) .forEach(file -> { try { if (Files.deleteIfExists(file.toPath())) { log.info("Removed DataStore file: {}", file.getName()); } } catch (Exception e) { log.error("Error when cleaning up DataStore files", e); } }); }); } /** * Get the {@link ChannelImplementation} to use. * * @return The server channel type. */ public ChannelImplementation getChannelImplementation() { final String type = getServerConfig(String.class, "--implementation"); return ChannelImplementation.valueOf(type.toUpperCase()); } /** * Get an instance of {@link CorfuRuntimeParameters} representing the default Corfu Runtime's * parameters. * * @return an instance of {@link CorfuRuntimeParameters} */ public CorfuRuntimeParameters getManagementRuntimeParameters() { return CorfuRuntime.CorfuRuntimeParameters.builder() .priorityLevel(PriorityLevel.HIGH) .nettyEventLoop(clientGroup) .shutdownNettyEventLoop(false) .tlsEnabled((Boolean) serverConfig.get("--enable-tls")) .keyStore((String) serverConfig.get("--keystore")) .ksPasswordFile((String) serverConfig.get("--keystore-password-file")) .trustStore((String) serverConfig.get("--truststore")) .tsPasswordFile((String) serverConfig.get("--truststore-password-file")) .saslPlainTextEnabled((Boolean) serverConfig.get("--enable-sasl-plain-text-auth")) .usernameFile((String) serverConfig.get("--sasl-plain-text-username-file")) .passwordFile((String) serverConfig.get("--sasl-plain-text-password-file")) .bulkReadSize(Integer.parseInt((String) serverConfig.get("--batch-size"))) .build(); } /** * Generate a Node Id if not present. */ private void generateNodeId() { String currentId = getDataStore().get(NODE_ID_RECORD); if (currentId == null) { String idString = UuidUtils.asBase64(UUID.randomUUID()); log.info("No Node Id, setting to new Id={}", idString); getDataStore().put(NODE_ID_RECORD, idString); } else { log.info("Node Id = {}", currentId); } } /** * Get the node id as an UUID. * * @return A UUID for this node. */ public UUID getNodeId() { return UuidUtils.fromBase64(getNodeIdBase64()); } /** Get the node id as a base64 string. * * @return A node ID for this node, as a base64 string. */ public String getNodeIdBase64() { return getDataStore().get(NODE_ID_RECORD); } /** * Get a field from the server configuration map. * * @param type The type of the field. * @param optionName The name of the option to retrieve. * @param <T> The type of the field to return. * @return The field with the give option name. */ @SuppressWarnings("unchecked") public <T> T getServerConfig(Class<T> type, String optionName) { return (T) getServerConfig().get(optionName); } /** * Get a field from the server configuration map. * * @param optionName The name of the option to retrieve. * @param <T> The type of the field to return. * @return The field with the give option name. */ @SuppressWarnings("unchecked") public <T> Optional<T> getServerConfig(String optionName) { return Optional.ofNullable((T) getServerConfig().get(optionName)); } /** * Install a single node layout if and only if no layout is currently installed. * Synchronized, so this method is thread-safe. * * @return True, if a new layout was installed, false otherwise. */ public synchronized boolean installSingleNodeLayoutIfAbsent() { if (isSingleNodeSetup() && getCurrentLayout() == null) { setCurrentLayout(getNewSingleNodeLayout()); return true; } return false; } /** * Check if it's a single node setup. * @return True if it is, false otherwise. */ public boolean isSingleNodeSetup(){ return (Boolean) getServerConfig().get("--single"); } /** * Get a new single node layout used for self-bootstrapping a server started with * the -s flag. * * @returns A new single node layout with a unique cluster Id * @throws IllegalArgumentException If the cluster id was not auto, base64 or a UUID string */ public Layout getNewSingleNodeLayout() { final String clusterIdString = (String) getServerConfig().get("--cluster-id"); UUID clusterId; if (clusterIdString.equals("auto")) { clusterId = UUID.randomUUID(); } else { // Is it a UUID? try { clusterId = UUID.fromString(clusterIdString); } catch (IllegalArgumentException ignore) { // Must be a base64 id, otherwise we will throw InvalidArgumentException again clusterId = UuidUtils.fromBase64(clusterIdString); } } log.info("getNewSingleNodeLayout: Bootstrapping with cluster Id {} [{}]", clusterId, UuidUtils.asBase64(clusterId)); String localAddress = getServerConfig().get("--address") + ":" + getServerConfig().get("<port>"); return new Layout( Collections.singletonList(localAddress), Collections.singletonList(localAddress), Collections.singletonList(new LayoutSegment( Layout.ReplicationMode.CHAIN_REPLICATION, 0L, -1L, Collections.singletonList( new Layout.LayoutStripe( Collections.singletonList(localAddress) ) ) )), 0L, clusterId ); } /** * Get the current {@link Layout} stored in the {@link DataStore}. * * @return The current stored {@link Layout} */ public Layout getCurrentLayout() { return dataStore.get(CURR_LAYOUT_RECORD); } /** * Set the current {@link Layout} stored in the {@link DataStore}. * * @param layout The {@link Layout} to set in the {@link DataStore}. */ public void setCurrentLayout(Layout layout) { getDataStore().put(CURR_LAYOUT_RECORD, layout); } /** * Get the list of servers registered in serverRouter * * @return A list of servers registered in serverRouter */ public List<AbstractServer> getServers() { return serverRouter.getServers(); } /** * The epoch of this router. This is managed by the base server implementation. */ public synchronized long getServerEpoch() { Long epoch = dataStore.get(SERVER_EPOCH_RECORD); return epoch == null ? Layout.INVALID_EPOCH : epoch; } /** * Set the serverRouter epoch. * * @param serverEpoch the epoch to set */ public synchronized void setServerEpoch(long serverEpoch, IServerRouter r) { Long lastEpoch = dataStore.get(SERVER_EPOCH_RECORD); if (lastEpoch == null || lastEpoch < serverEpoch) { dataStore.put(SERVER_EPOCH_RECORD, serverEpoch); r.setServerEpoch(serverEpoch); getServers().forEach(s -> s.sealServerWithEpoch(serverEpoch)); } else if (lastEpoch > serverEpoch){ // Regressing, throw an exception. throw new WrongEpochException(lastEpoch); } // If both epochs are same then no need to do anything. } public void setLayoutInHistory(Layout layout) { KvRecord<Layout> currLayoutRecord = KvRecord.of( PREFIX_LAYOUTS, String.valueOf(layout.getEpoch()), Layout.class ); dataStore.put(currLayoutRecord, layout); } /** * Persists the sequencer epoch. This is set only by the SequencerServer in the resetServer. * No lock required as it relies on the resetServer lock. * * @param sequencerEpoch Epoch to persist. */ public void setSequencerEpoch(long sequencerEpoch) { dataStore.put(SEQUENCER_RECORD, sequencerEpoch); } /** * Fetch the persisted sequencer epoch. * * @return Sequencer epoch. */ public long getSequencerEpoch() { Long epoch = dataStore.get(SEQUENCER_RECORD); return epoch == null ? Layout.INVALID_EPOCH : epoch; } /** * Sets the management layout in the persistent datastore. * * @param newLayout Layout to be persisted */ public synchronized Layout saveManagementLayout(Layout newLayout) { Layout currentLayout = copyManagementLayout(); // Cannot update with a null layout. if (newLayout == null) { log.warn("Attempted to update with null. Current layout: {}", currentLayout); return currentLayout; } // Update only if new layout has a higher epoch than the existing layout. if (currentLayout == null || newLayout.getEpoch() > currentLayout.getEpoch()) { dataStore.put(MANAGEMENT_LAYOUT_RECORD, newLayout); currentLayout = copyManagementLayout(); log.info("Update to new layout at epoch {}", currentLayout.getEpoch()); return currentLayout; } return currentLayout; } /** * Fetches the management layout from the persistent datastore. * * @return The last persisted layout */ public Layout getManagementLayout() { return dataStore.get(MANAGEMENT_LAYOUT_RECORD); } /** * Sets the log unit epoch water mark. * * @param resetEpoch Epoch at which the reset command was received. */ public synchronized void setLogUnitEpochWaterMark(long resetEpoch) { dataStore.put(LOG_UNIT_WATERMARK_RECORD, resetEpoch); } /** * Fetches the epoch at which the last epochWaterMark operation was received. * * @return Reset epoch. */ public synchronized long getLogUnitEpochWaterMark() { Long resetEpoch = dataStore.get(LOG_UNIT_WATERMARK_RECORD); return resetEpoch == null ? Layout.INVALID_EPOCH : resetEpoch; } /** * Fetches and creates a copy of the Management Layout from the local datastore. * * @return Copy of the management layout from the datastore. */ public Layout copyManagementLayout() { Layout l = getManagementLayout(); if (l != null) { return new Layout(l); } else { return null; } } /** * Get a new "worker" group, which services incoming requests. * * @return A worker group. */ private @Nonnull EventLoopGroup getNewWorkerGroup() { final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat(getThreadPrefix() + "worker-%d") .build(); final int requestedThreads = Integer.parseInt(getServerConfig(String.class, "--Threads")); final int numThreads = requestedThreads == 0 ? Runtime.getRuntime().availableProcessors() * 2 : requestedThreads; EventLoopGroup group = getChannelImplementation().getGenerator() .generate(numThreads, threadFactory); log.info("getWorkerGroup: Type {} with {} threads", group.getClass().getSimpleName(), numThreads); return group; } /** * Get a new "client" group, which services incoming client requests. * * @return A worker group. */ private @Nonnull EventLoopGroup getNewClientGroup() { final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat(getThreadPrefix() + "client-%d") .build(); final int requestedThreads = Integer.parseInt(getServerConfig(String.class, "--Threads")); final int numThreads = requestedThreads == 0 ? Runtime.getRuntime().availableProcessors() * 2 : requestedThreads; EventLoopGroup group = getChannelImplementation().getGenerator() .generate(numThreads, threadFactory); log.info("getClientGroup: Type {} with {} threads", group.getClass().getSimpleName(), numThreads); return group; } /** * Get the prefix for threads this server creates. * * @return A string that should be prepended to threads this server creates. */ public @Nonnull String getThreadPrefix() { final String prefix = getServerConfig(String.class, "--Prefix"); if (prefix.equals("")) { return ""; } else { return prefix + "-"; } } /** * {@inheritDoc} * * <p>Cleans up and releases all resources (such as thread pools and files) opened * by this {@link ServerContext}. */ @Override public void close() { CorfuRuntimeParameters params = getManagementRuntimeParameters(); // Shutdown the active event loops unless they were provided to us if (!getChannelImplementation().equals(ChannelImplementation.LOCAL)) { clientGroup.shutdownGracefully( params.getNettyShutdownQuitePeriod(), params.getNettyShutdownTimeout(), TimeUnit.MILLISECONDS ); workerGroup.shutdownGracefully( params.getNettyShutdownQuitePeriod(), params.getNettyShutdownTimeout(), TimeUnit.MILLISECONDS ); } } }
3e1fad3c7fd6bb7a834261d96a39297c20466145
3,427
java
Java
core/src/main/java/org/md2k/mcerebrum/api/core/datakitapi/aidl/_DataSourceOut.java
hippietilley/mCerebrum-API-android
c0582fbc871c053df3496cc50e0ad2ddb655096c
[ "BSD-2-Clause" ]
null
null
null
core/src/main/java/org/md2k/mcerebrum/api/core/datakitapi/aidl/_DataSourceOut.java
hippietilley/mCerebrum-API-android
c0582fbc871c053df3496cc50e0ad2ddb655096c
[ "BSD-2-Clause" ]
null
null
null
core/src/main/java/org/md2k/mcerebrum/api/core/datakitapi/aidl/_DataSourceOut.java
hippietilley/mCerebrum-API-android
c0582fbc871c053df3496cc50e0ad2ddb655096c
[ "BSD-2-Clause" ]
null
null
null
30.945946
89
0.696652
13,377
package org.md2k.mcerebrum.api.core.datakitapi.aidl; import android.os.Parcel; import android.os.Parcelable; /* * Copyright (c) 2016, The University of Memphis, MD2K Center * - Syed Monowar Hossain <lyhxr@example.com> * 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. * * 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 HOLDER 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. */ public class _DataSourceOut implements Parcelable { private int dsId = -1; private long creationTime = -1; private long lastActiveTime = -1; private _DataSourceIn dataSourceIn; @Override public int describeContents() { return 0; } public static final Creator<_DataSourceOut> CREATOR = new Creator<_DataSourceOut>() { @Override public _DataSourceOut createFromParcel(Parcel in) { return new _DataSourceOut(in); } @Override public _DataSourceOut[] newArray(int size) { return new _DataSourceOut[size]; } }; public int getDsId() { return dsId; } public void setDsId(int dsId) { this.dsId = dsId; } public long getCreationTime() { return creationTime; } public void setCreationTime(long creationTime) { this.creationTime = creationTime; } public long getLastActiveTime() { return lastActiveTime; } public void setLastActiveTime(long lastActiveTime) { this.lastActiveTime = lastActiveTime; } public _DataSourceIn getDataSourceIn() { return dataSourceIn; } public void setDataSourceIn(_DataSourceIn dataSourceIn) { this.dataSourceIn = dataSourceIn; } public _DataSourceOut() { } public void readFromParcel(Parcel in) { dsId = in.readInt(); creationTime = in.readLong(); lastActiveTime = in.readLong(); dataSourceIn = in.readParcelable(_DataSourceIn.class.getClassLoader()); } _DataSourceOut(Parcel in) { readFromParcel(in); } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(dsId); parcel.writeLong(creationTime); parcel.writeLong(lastActiveTime); parcel.writeParcelable(dataSourceIn, i); } }
3e1fae524d3c03c46b93404ab6e7e309b3a54a8e
225
java
Java
src/test/java/com/example/kafkaload/KafkaLoadApplicationTests.java
vladislav-sidorovich/data-cnosuming-and-grouping
28d9e17b2b538f8e1fac96846eb43542448ae79a
[ "MIT" ]
null
null
null
src/test/java/com/example/kafkaload/KafkaLoadApplicationTests.java
vladislav-sidorovich/data-cnosuming-and-grouping
28d9e17b2b538f8e1fac96846eb43542448ae79a
[ "MIT" ]
null
null
null
src/test/java/com/example/kafkaload/KafkaLoadApplicationTests.java
vladislav-sidorovich/data-cnosuming-and-grouping
28d9e17b2b538f8e1fac96846eb43542448ae79a
[ "MIT" ]
null
null
null
16.071429
60
0.76
13,378
package com.example.kafkaload; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class KafkaLoadApplicationTests { @Test void contextLoads() { } }
3e1fae6df0a621f56ec5396a47ef82ff8a0e6dac
1,297
java
Java
src/main/java/com/intellij/debugger/streams/test/JdkManager.java
Roenke/stream-debugger-plugin
1e4184d83eb0bbc99e878fccb59236937d50c7a1
[ "Apache-2.0" ]
7
2019-03-21T10:10:25.000Z
2021-07-05T17:11:43.000Z
src/main/java/com/intellij/debugger/streams/test/JdkManager.java
Roenke/stream-debugger-plugin
1e4184d83eb0bbc99e878fccb59236937d50c7a1
[ "Apache-2.0" ]
1
2017-07-01T10:06:06.000Z
2017-07-01T10:06:06.000Z
src/main/java/com/intellij/debugger/streams/test/JdkManager.java
Roenke/stream-debugger-plugin
1e4184d83eb0bbc99e878fccb59236937d50c7a1
[ "Apache-2.0" ]
5
2019-06-26T18:26:53.000Z
2021-12-31T21:10:53.000Z
29.477273
111
0.739399
13,379
/* * Copyright 2000-2018 JetBrains s.r.o. * * 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.intellij.debugger.streams.test; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.JavaSdkImpl; import java.io.File; /** * @author Vitaliy.Bibaev */ class JdkManager { static final String JDK18_PATH; private static final String MOCK_JDK_DIR_NAME_PREFIX = "mockJDK-"; private static class Holder { static final Sdk JDK18 = ((JavaSdkImpl)JavaSdk.getInstance()).createMockJdk("java 1.8", JDK18_PATH, false); } static { JDK18_PATH = new File("java/" + MOCK_JDK_DIR_NAME_PREFIX + "1.8").getAbsolutePath(); } static Sdk getMockJdk18() { return Holder.JDK18; } }
3e1faeae2525eaa247c9467436661f82f5912514
310
java
Java
sintefMMsrc/no/sintef/model/GasParticle.java
SINTEF-EnvironmentalTechnology/GRF2NETCDF
9673fb7733c9fff5ca20c9a0a9f7713e9978398e
[ "BSD-3-Clause" ]
1
2015-11-30T06:40:53.000Z
2015-11-30T06:40:53.000Z
sintefMMsrc/no/sintef/model/GasParticle.java
SINTEF-EnvironmentalTechnology/GRF2NETCDF
9673fb7733c9fff5ca20c9a0a9f7713e9978398e
[ "BSD-3-Clause" ]
null
null
null
sintefMMsrc/no/sintef/model/GasParticle.java
SINTEF-EnvironmentalTechnology/GRF2NETCDF
9673fb7733c9fff5ca20c9a0a9f7713e9978398e
[ "BSD-3-Clause" ]
null
null
null
12.4
54
0.719355
13,380
package no.sintef.model; /** * @author ubr * */ public class GasParticle extends ParticleCloud { private float bubbleDiameter; public void setBubbleDiameter(float bubbleDiameter) { this.bubbleDiameter = bubbleDiameter; } public float getBubbleDiameter() { return bubbleDiameter; } }
3e1faec13864aa28ce642e42a547808d9501deca
5,080
java
Java
sourcedata/xerces2-j-Xerces-J_1_3_0/src/org/apache/xml/serialize/XHTMLSerializer.java
DXYyang/SDP
6ad0daf242d4062888ceca6d4a1bd4c41fd99b63
[ "Apache-2.0" ]
6
2020-10-27T06:11:59.000Z
2021-09-09T13:52:42.000Z
sourcedata/xerces2-j-Xerces-J_1_3_0/src/org/apache/xml/serialize/XHTMLSerializer.java
DXYyang/SDP
6ad0daf242d4062888ceca6d4a1bd4c41fd99b63
[ "Apache-2.0" ]
8
2020-11-16T20:41:38.000Z
2022-02-01T01:05:45.000Z
sourcedata/xerces2-j-Xerces-J_1_3_0/src/org/apache/xml/serialize/XHTMLSerializer.java
DXYyang/SDP
6ad0daf242d4062888ceca6d4a1bd4c41fd99b63
[ "Apache-2.0" ]
null
null
null
36.028369
105
0.695276
13,381
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact efpyi@example.com. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xml.serialize; import java.io.OutputStream; import java.io.Writer; import java.io.UnsupportedEncodingException; /** * Implements an XHTML serializer supporting both DOM and SAX * pretty serializing. For usage instructions see either {@link * Serializer} or {@link BaseMarkupSerializer}. * * * @version $Revision$ $Date$ * @author <a href="mailto:kenaa@example.com">Assaf Arkin</a> * @see Serializer */ public final class XHTMLSerializer extends HTMLSerializer { /** * Constructs a new serializer. The serializer cannot be used without * calling {@link #setOutputCharStream} or {@link #setOutputByteStream} * first. */ public XHTMLSerializer() { super( true, new OutputFormat( Method.XHTML, null, false ) ); } /** * Constructs a new serializer. The serializer cannot be used without * calling {@link #setOutputCharStream} or {@link #setOutputByteStream} * first. */ public XHTMLSerializer( OutputFormat format ) { super( true, format != null ? format : new OutputFormat( Method.XHTML, null, false ) ); } /** * Constructs a new serializer that writes to the specified writer * using the specified output format. If <tt>format</tt> is null, * will use a default output format. * * @param writer The writer to use * @param format The output format to use, null for the default */ public XHTMLSerializer( Writer writer, OutputFormat format ) { super( true, format != null ? format : new OutputFormat( Method.XHTML, null, false ) ); setOutputCharStream( writer ); } /** * Constructs a new serializer that writes to the specified output * stream using the specified output format. If <tt>format</tt> * is null, will use a default output format. * * @param output The output stream to use * @param format The output format to use, null for the default */ public XHTMLSerializer( OutputStream output, OutputFormat format ) { super( true, format != null ? format : new OutputFormat( Method.XHTML, null, false ) ); setOutputByteStream( output ); } public void setOutputFormat( OutputFormat format ) { super.setOutputFormat( format != null ? format : new OutputFormat( Method.XHTML, null, false ) ); } }
3e1faee7aa7d1d7d63414a9828ea3ec0c0b1ea8b
6,653
java
Java
server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/shard/TransportGetShardSnapshotAction.java
diwasjoshi/elasticsearch
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
[ "Apache-2.0" ]
null
null
null
server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/shard/TransportGetShardSnapshotAction.java
diwasjoshi/elasticsearch
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
[ "Apache-2.0" ]
null
null
null
server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/shard/TransportGetShardSnapshotAction.java
diwasjoshi/elasticsearch
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
[ "Apache-2.0" ]
null
null
null
41.842767
139
0.725988
13,382
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.action.admin.cluster.snapshots.get.shard; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.GroupedActionListener; import org.elasticsearch.action.support.master.TransportMasterNodeAction; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.RepositoriesMetadata; import org.elasticsearch.cluster.metadata.RepositoryMetadata; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.core.Tuple; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.repositories.IndexSnapshotsService; import org.elasticsearch.repositories.RepositoriesService; import org.elasticsearch.repositories.RepositoryException; import org.elasticsearch.repositories.ShardSnapshotInfo; import org.elasticsearch.tasks.Task; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.function.Function; import java.util.stream.Collectors; public class TransportGetShardSnapshotAction extends TransportMasterNodeAction<GetShardSnapshotRequest, GetShardSnapshotResponse> { private static final Comparator<ShardSnapshotInfo> LATEST_SNAPSHOT_COMPARATOR = Comparator.comparing(ShardSnapshotInfo::getStartedAt) .thenComparing(snapshotInfo -> snapshotInfo.getSnapshot().getSnapshotId()); private final IndexSnapshotsService indexSnapshotsService; @Inject public TransportGetShardSnapshotAction( TransportService transportService, ClusterService clusterService, ThreadPool threadPool, RepositoriesService repositoriesService, ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver ) { super( GetShardSnapshotAction.NAME, transportService, clusterService, threadPool, actionFilters, GetShardSnapshotRequest::new, indexNameExpressionResolver, GetShardSnapshotResponse::new, ThreadPool.Names.SAME ); this.indexSnapshotsService = new IndexSnapshotsService(repositoriesService); } @Override protected void masterOperation( Task task, GetShardSnapshotRequest request, ClusterState state, ActionListener<GetShardSnapshotResponse> listener ) throws Exception { final Set<String> repositories = getRequestedRepositories(request, state); final ShardId shardId = request.getShardId(); if (repositories.isEmpty()) { listener.onResponse(GetShardSnapshotResponse.EMPTY); return; } GroupedActionListener<Tuple<Optional<ShardSnapshotInfo>, RepositoryException>> groupedActionListener = new GroupedActionListener<>( listener.map(this::transformToResponse), repositories.size() ); BlockingQueue<String> repositoriesQueue = new LinkedBlockingQueue<>(repositories); getShardSnapshots(repositoriesQueue, shardId, new ActionListener<>() { @Override public void onResponse(Optional<ShardSnapshotInfo> shardSnapshotInfo) { groupedActionListener.onResponse(Tuple.tuple(shardSnapshotInfo, null)); } @Override public void onFailure(Exception err) { if (request.isSingleRepositoryRequest() == false && err instanceof RepositoryException) { groupedActionListener.onResponse(Tuple.tuple(Optional.empty(), (RepositoryException) err)); } else { groupedActionListener.onFailure(err); } } }); } private void getShardSnapshots( BlockingQueue<String> repositories, ShardId shardId, ActionListener<Optional<ShardSnapshotInfo>> listener ) { final String repository = repositories.poll(); if (repository == null) { return; } indexSnapshotsService.getLatestSuccessfulSnapshotForShard( repository, shardId, ActionListener.runAfter(listener, () -> getShardSnapshots(repositories, shardId, listener)) ); } private GetShardSnapshotResponse transformToResponse( Collection<Tuple<Optional<ShardSnapshotInfo>, RepositoryException>> shardSnapshots ) { final Optional<ShardSnapshotInfo> latestSnapshot = shardSnapshots.stream() .map(Tuple::v1) .filter(Objects::nonNull) .filter(Optional::isPresent) .map(Optional::get) .max(LATEST_SNAPSHOT_COMPARATOR); final Map<String, RepositoryException> failures = shardSnapshots.stream() .map(Tuple::v2) .filter(Objects::nonNull) .collect(Collectors.toMap(RepositoryException::repository, Function.identity())); return new GetShardSnapshotResponse(latestSnapshot.orElse(null), failures); } private Set<String> getRequestedRepositories(GetShardSnapshotRequest request, ClusterState state) { RepositoriesMetadata repositories = state.metadata().custom(RepositoriesMetadata.TYPE, RepositoriesMetadata.EMPTY); if (request.getFromAllRepositories()) { return repositories.repositories().stream().map(RepositoryMetadata::name).collect(Collectors.toUnmodifiableSet()); } return request.getRepositories().stream().filter(Objects::nonNull).collect(Collectors.toUnmodifiableSet()); } @Override protected ClusterBlockException checkBlock(GetShardSnapshotRequest request, ClusterState state) { return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); } }
3e1fafb10086d76d63e24cd782ce94732232582e
912
java
Java
com.alcatel.as.service.api/src/com/alcatel/as/service/metering/Counter.java
nokia/osgi-microfeatures
50120f20cf929a966364550ca5829ef348d82670
[ "Apache-2.0" ]
null
null
null
com.alcatel.as.service.api/src/com/alcatel/as/service/metering/Counter.java
nokia/osgi-microfeatures
50120f20cf929a966364550ca5829ef348d82670
[ "Apache-2.0" ]
null
null
null
com.alcatel.as.service.api/src/com/alcatel/as/service/metering/Counter.java
nokia/osgi-microfeatures
50120f20cf929a966364550ca5829ef348d82670
[ "Apache-2.0" ]
null
null
null
30.4
95
0.703947
13,383
// Copyright 2000-2021 Nokia // // Licensed under the Apache License 2.0 // SPDX-License-Identifier: Apache-2.0 // package com.alcatel.as.service.metering; /** * Counter used to expose cumulative events. The value of the counter will grow during the life * cycle of the application. For example, use Counters for metering method execution elapsed * time, number of message received, etc ... Notice that, if you need to count event occurrence * per seconds, then you can use {@link Rate} instead of this class. */ public interface Counter extends Meter { /** * Accumulates a value into that counter. * * @param value a Value to be added into this counter. */ void add(long value); /** * Starts a stopwatch used to measure the time elapsed by a method (in millis.) * * @return A StopWatch for measuring the time elapsed by a method (in millis.). */ StopWatch start(); }
3e1fb02951688d1e094c2820977f04de0f81e9e5
2,413
java
Java
src/test/java/com/twilio/rest/pricing/v1/voice/NumberTest.java
duttonw/twilio-java
87e51c729aa882926eeb59114be3488423d750ad
[ "MIT" ]
295
2015-01-04T17:00:48.000Z
2022-03-29T21:51:49.000Z
src/test/java/com/twilio/rest/pricing/v1/voice/NumberTest.java
duttonw/twilio-java
87e51c729aa882926eeb59114be3488423d750ad
[ "MIT" ]
349
2015-01-14T19:08:16.000Z
2022-03-09T15:50:13.000Z
src/test/java/com/twilio/rest/pricing/v1/voice/NumberTest.java
duttonw/twilio-java
87e51c729aa882926eeb59114be3488423d750ad
[ "MIT" ]
376
2015-01-03T22:31:01.000Z
2022-03-31T08:23:17.000Z
34.471429
417
0.628264
13,384
/** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ package com.twilio.rest.pricing.v1.voice; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.Twilio; import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.TwilioException; import com.twilio.http.HttpMethod; import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; import mockit.Mocked; import mockit.NonStrictExpectations; import org.junit.Before; import org.junit.Test; import java.net.URI; import static com.twilio.TwilioTest.serialize; import static org.junit.Assert.*; public class NumberTest { @Mocked private TwilioRestClient twilioRestClient; @Before public void setUp() throws Exception { Twilio.init("AC123", "AUTH TOKEN"); } @Test public void testFetchRequest() { new NonStrictExpectations() {{ Request request = new Request(HttpMethod.GET, Domains.PRICING.toString(), "/v1/Voice/Numbers/%2B15017122661"); twilioRestClient.request(request); times = 1; result = new Response("", 500); twilioRestClient.getAccountSid(); result = "AC123"; }}; try { Number.fetcher(new com.twilio.type.PhoneNumber("+15017122661")).fetch(); fail("Expected TwilioException to be thrown for 500"); } catch (TwilioException e) {} } @Test public void testFetchResponse() { new NonStrictExpectations() {{ twilioRestClient.request((Request) any); result = new Response("{\"country\": \"Iran\",\"inbound_call_price\": {\"base_price\": null,\"current_price\": null,\"number_type\": null},\"iso_country\": \"IR\",\"number\": \"+987654321\",\"outbound_call_price\": {\"base_price\": \"0.255\",\"current_price\": \"0.255\"},\"price_unit\": \"USD\",\"url\": \"https://pricing.twilio.com/v1/Voice/Numbers/+987654321\"}", TwilioRestClient.HTTP_STATUS_CODE_OK); twilioRestClient.getObjectMapper(); result = new ObjectMapper(); }}; assertNotNull(Number.fetcher(new com.twilio.type.PhoneNumber("+15017122661")).fetch()); } }
3e1fb043216ea66b02a27715e202e70e92ebb448
3,866
java
Java
Benchmarks_with_Functional_Bugs/Java/Bears-184/src/src/test/java/org/springframework/data/jpa/repository/query/ParameterMetadataProviderIntegrationTests.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
null
null
null
Benchmarks_with_Functional_Bugs/Java/Bears-184/src/src/test/java/org/springframework/data/jpa/repository/query/ParameterMetadataProviderIntegrationTests.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
null
null
null
Benchmarks_with_Functional_Bugs/Java/Bears-184/src/src/test/java/org/springframework/data/jpa/repository/query/ParameterMetadataProviderIntegrationTests.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
2
2020-11-26T13:27:14.000Z
2022-03-20T02:12:55.000Z
37.173077
116
0.793585
13,385
/* * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.springframework.data.jpa.repository.query; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.data.jpa.domain.sample.User; import org.springframework.data.jpa.provider.PersistenceProvider; import org.springframework.data.jpa.repository.query.ParameterMetadataProvider.ParameterMetadata; import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Parameters; import org.springframework.data.repository.query.parser.Part; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.util.ReflectionTestUtils; /** * Integration tests for {@link ParameterMetadataProvider}. * * @author Oliver Gierke * @author Jens Schauder * @soundtrack Elephants Crossing - We are (Irrelephant) */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:infrastructure.xml") public class ParameterMetadataProviderIntegrationTests { @PersistenceContext EntityManager em; @Test // DATAJPA-758 public void forwardsParameterNameIfTransparentlyNamed() throws Exception { ParameterMetadataProvider provider = createProvider(Sample.class.getMethod("findByFirstname", String.class)); ParameterMetadata<Object> metadata = provider.next(new Part("firstname", User.class)); assertThat(metadata.getExpression().getName()).isEqualTo("name"); } @Test // DATAJPA-758 public void forwardsParameterNameIfExplicitlyAnnotated() throws Exception { ParameterMetadataProvider provider = createProvider(Sample.class.getMethod("findByLastname", String.class)); ParameterMetadata<Object> metadata = provider.next(new Part("lastname", User.class)); assertThat(metadata.getExpression().getName()).isNull(); } @Test // DATAJPA-772 public void doesNotApplyLikeExpansionOnNonStringProperties() throws Exception { ParameterMetadataProvider provider = createProvider(Sample.class.getMethod("findByAgeContaining", Integer.class)); ParameterMetadata<Object> metadata = provider.next(new Part("ageContaining", User.class)); assertThat(metadata.prepare(1)).isEqualTo(1); } private ParameterMetadataProvider createProvider(Method method) { JpaParameters parameters = new JpaParameters(method); simulateDiscoveredParametername(parameters); return new ParameterMetadataProvider(em.getCriteriaBuilder(), parameters, PersistenceProvider.fromEntityManager(em)); } @SuppressWarnings({ "unchecked", "ConstantConditions" }) private static void simulateDiscoveredParametername(Parameters<?, ?> parameters) { List<Object> list = (List<Object>) ReflectionTestUtils.getField(parameters, "parameters"); Object parameter = ReflectionTestUtils.getField(list.get(0), "parameter"); ReflectionTestUtils.setField(parameter, "parameterName", "name"); } interface Sample { User findByFirstname(@Param("name") String firstname); User findByLastname(String lastname); User findByAgeContaining(@Param("age") Integer age); } }
3e1fb050e6ab524a07f4dc03a2ae169a84e36e8b
322
java
Java
library/src/test/java/com/tekartik/testmenu/TestUnitTest.java
tekartik/test.android
eb0d86f8d09e13b336cfaecb7df3fe585785551a
[ "BSD-2-Clause" ]
null
null
null
library/src/test/java/com/tekartik/testmenu/TestUnitTest.java
tekartik/test.android
eb0d86f8d09e13b336cfaecb7df3fe585785551a
[ "BSD-2-Clause" ]
null
null
null
library/src/test/java/com/tekartik/testmenu/TestUnitTest.java
tekartik/test.android
eb0d86f8d09e13b336cfaecb7df3fe585785551a
[ "BSD-2-Clause" ]
null
null
null
21.466667
78
0.704969
13,386
package com.tekartik.testmenu; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class TestUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
3e1fb1c67e7ef65e6bc38485972e9c245675d26f
1,110
java
Java
src/test/java/seedu/homerce/logic/parser/expense/SortExpenseCommandParserTest.java
yanlynnnnn/tp
e959a69b8e5e698a4802477ffa208f48dfceea6c
[ "MIT" ]
1
2020-10-12T07:28:09.000Z
2020-10-12T07:28:09.000Z
src/test/java/seedu/homerce/logic/parser/expense/SortExpenseCommandParserTest.java
yanlynnnnn/tp
e959a69b8e5e698a4802477ffa208f48dfceea6c
[ "MIT" ]
265
2020-09-17T09:42:36.000Z
2020-11-09T13:19:30.000Z
src/test/java/seedu/homerce/logic/parser/expense/SortExpenseCommandParserTest.java
yanlynnnnn/tp
e959a69b8e5e698a4802477ffa208f48dfceea6c
[ "MIT" ]
7
2020-09-13T10:25:39.000Z
2021-04-05T12:53:43.000Z
30
77
0.740541
13,387
package seedu.homerce.logic.parser.expense; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.homerce.testutil.Assert.assertThrows; import org.junit.jupiter.api.Test; import seedu.homerce.logic.commands.expense.SortExpenseCommand; import seedu.homerce.logic.parser.exceptions.ParseException; public class SortExpenseCommandParserTest { private SortExpenseCommandParser parser = new SortExpenseCommandParser(); @Test public void parse_validArgsAsc_success()throws ParseException { SortExpenseCommand command = parser.parse("asc"); assertTrue(command.isAscending); } @Test public void parse_validArgsDesc_success()throws ParseException { SortExpenseCommand command = parser.parse("desc"); assertTrue(!command.isAscending); } @Test public void parse_invalidArgs_throwsParseException() { assertThrows(ParseException.class, () -> parser.parse("abc")); } @Test public void parse_emptyArgs_throwsParseException() { assertThrows(ParseException.class, () -> parser.parse("")); } }
3e1fb1fdeaf13ee1d2abf5ca3048337f4782fc5a
444
java
Java
instrumentation/gwt-2.0/javaagent/src/testapp/java/test/gwt/shared/MessageService.java
onespacer/opentelemetry-java-instrumentation
5c15f5e29fd71d9afd4e10dcad13fb123ceb24ff
[ "ECL-2.0", "Apache-2.0", "BSD-3-Clause", "MIT" ]
null
null
null
instrumentation/gwt-2.0/javaagent/src/testapp/java/test/gwt/shared/MessageService.java
onespacer/opentelemetry-java-instrumentation
5c15f5e29fd71d9afd4e10dcad13fb123ceb24ff
[ "ECL-2.0", "Apache-2.0", "BSD-3-Clause", "MIT" ]
30
2020-11-16T07:41:11.000Z
2022-03-11T03:25:10.000Z
instrumentation/gwt-2.0/javaagent/src/testapp/java/test/gwt/shared/MessageService.java
dengliming/opentelemetry-java-instrumentation
f11bd75710f2fef603d325793cef6b388754a1eb
[ "MIT", "ECL-2.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
27.75
69
0.795045
13,388
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package test.gwt.shared; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** The client-side stub for the RPC service. */ @RemoteServiceRelativePath("greet") public interface MessageService extends RemoteService { String sendMessage(String message) throws IllegalArgumentException; }
3e1fb205d6e37eb92e38cc9cd28f57837d05f1e8
2,068
java
Java
src/test/java/org/assertj/core/internal/doublearrays/DoubleArrays_assertNotEmpty_Test.java
glhez/assertj-core
d3e70030999cb3aaa090b9797d00892fcae57896
[ "Apache-2.0" ]
1,607
2015-01-06T13:35:38.000Z
2020-09-22T08:20:41.000Z
src/test/java/org/assertj/core/internal/doublearrays/DoubleArrays_assertNotEmpty_Test.java
glhez/assertj-core
d3e70030999cb3aaa090b9797d00892fcae57896
[ "Apache-2.0" ]
1,604
2015-01-01T04:10:21.000Z
2020-09-22T10:09:26.000Z
src/test/java/org/assertj/core/internal/doublearrays/DoubleArrays_assertNotEmpty_Test.java
glhez/assertj-core
d3e70030999cb3aaa090b9797d00892fcae57896
[ "Apache-2.0" ]
523
2015-01-07T16:57:54.000Z
2020-09-20T03:01:39.000Z
39.018868
118
0.742263
13,389
/* * 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. * * Copyright 2012-2022 the original author or authors. */ package org.assertj.core.internal.doublearrays; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.error.ShouldNotBeEmpty.shouldNotBeEmpty; import static org.assertj.core.test.DoubleArrays.arrayOf; import static org.assertj.core.test.DoubleArrays.emptyArray; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.FailureMessages.actualIsNull; import org.assertj.core.api.AssertionInfo; import org.assertj.core.internal.DoubleArrays; import org.assertj.core.internal.DoubleArraysBaseTest; import org.junit.jupiter.api.Test; /** * Tests for <code>{@link DoubleArrays#assertNotEmpty(AssertionInfo, double[])}</code>. * * @author Alex Ruiz * @author Joel Costigliola */ class DoubleArrays_assertNotEmpty_Test extends DoubleArraysBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertNotEmpty(someInfo(), null)) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_is_empty() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertNotEmpty(someInfo(), emptyArray())) .withMessage(shouldNotBeEmpty().create()); } @Test void should_pass_if_actual_is_not_empty() { arrays.assertNotEmpty(someInfo(), arrayOf(8d)); } }
3e1fb20b8746e9216c95db2b3b19b329b637f201
1,002
java
Java
src/main/java/pt/pcaleia/arg/assertion/StringArgumentAssertions.java
pedrocaleia/argument-assertions
db60b4bc2d3f29d12c5a7b1e8f707f3565cb6947
[ "MIT" ]
null
null
null
src/main/java/pt/pcaleia/arg/assertion/StringArgumentAssertions.java
pedrocaleia/argument-assertions
db60b4bc2d3f29d12c5a7b1e8f707f3565cb6947
[ "MIT" ]
null
null
null
src/main/java/pt/pcaleia/arg/assertion/StringArgumentAssertions.java
pedrocaleia/argument-assertions
db60b4bc2d3f29d12c5a7b1e8f707f3565cb6947
[ "MIT" ]
null
null
null
26.368421
112
0.715569
13,390
package pt.pcaleia.arg.assertion; /** * @author Pedro Caleia */ public final class StringArgumentAssertions { private static final String NULL_OR_EMPTY_MESSAGE = "The '%s' argument cannot be null or empty."; private StringArgumentAssertions() { throw new AssertionError( StringArgumentAssertions.class.getSimpleName() + " class cannot be instantiated." ); } /** * Assert that the given String is not null and contains at least one non white space character. * * @param argument * @param argumentName */ public static void assertNotEmpty( String argument, String argumentName ) { if( argumentName == null || argumentName.trim().isEmpty() ) { String message = String.format( NULL_OR_EMPTY_MESSAGE, "argumentName" ); throw new IllegalArgumentException( message ); } if( argument == null || argument.trim().isEmpty() ) { String message = String.format( NULL_OR_EMPTY_MESSAGE, argumentName ); throw new IllegalArgumentException( message ); } } }
3e1fb2cfe3bc0d9875b7d2e3bfe833ba91327e25
818
java
Java
src/main/java/com/algorithm/space/hancock/offer/solution/SolutionOf30.java
BBHNation/AlgorithmSpace
f5a51266eb09c2a89dfd9e884b0bab07c1bf8fb9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/algorithm/space/hancock/offer/solution/SolutionOf30.java
BBHNation/AlgorithmSpace
f5a51266eb09c2a89dfd9e884b0bab07c1bf8fb9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/algorithm/space/hancock/offer/solution/SolutionOf30.java
BBHNation/AlgorithmSpace
f5a51266eb09c2a89dfd9e884b0bab07c1bf8fb9
[ "Apache-2.0" ]
null
null
null
19.023256
51
0.584352
13,391
package com.algorithm.space.hancock.offer.solution; import java.util.Deque; import java.util.LinkedList; public class SolutionOf30 { private SolutionOf30() {} public static class MinStack { private final Deque<Integer> mainStack; private int minNum; /** initialize your data structure here. */ public MinStack() { mainStack = new LinkedList<>(); minNum = Integer.MAX_VALUE; } public void push(int x) { if (x <= minNum) { mainStack.push(minNum); minNum = x; } mainStack.push(x); } public void pop() { Integer pop = mainStack.pop(); if (pop == minNum) { minNum = mainStack.pop(); } } public int top() { return mainStack.peek(); } public int min() { return minNum; } } }
3e1fb2d2ff613e58107a2c0046f4ae6249a3f82a
1,011
java
Java
src/main/java/com/extr/persistence/CommentMapper.java
CL-CodeLegend/exam
d4147f107d5f3be34df3521749798642625771d1
[ "MIT" ]
null
null
null
src/main/java/com/extr/persistence/CommentMapper.java
CL-CodeLegend/exam
d4147f107d5f3be34df3521749798642625771d1
[ "MIT" ]
7
2020-06-30T23:23:55.000Z
2021-08-25T15:41:39.000Z
src/main/java/com/extr/persistence/CommentMapper.java
CL-CodeLegend/exam
d4147f107d5f3be34df3521749798642625771d1
[ "MIT" ]
null
null
null
28.083333
104
0.789318
13,392
package com.extr.persistence; import java.util.List; import org.apache.ibatis.annotations.Param; import com.extr.controller.domain.QuestionFilter; import com.extr.controller.domain.QuestionImproveResult; import com.extr.controller.domain.QuestionQueryResult; import com.extr.domain.question.Comment; import com.extr.domain.question.Field; import com.extr.domain.question.KnowledgePoint; import com.extr.domain.question.Question; import com.extr.domain.question.QuestionStruts; import com.extr.domain.question.QuestionType; import com.extr.domain.question.UserQuestionHistory; import com.extr.util.Page; /** * @author Ocelot * @date 2014年6月8日 下午8:32:33 */ public interface CommentMapper { List<Comment> getCommentByQuestionId(@Param("questionId") int questionId,@Param("indexId") int indexId, @Param("page") Page<Comment> page); /** * 添加评论 * @param comment */ public void addComment(Comment comment); public Integer getMaxCommentIndexByQuestionId(@Param("questionId") int questionId); }
3e1fb316e3635346590b12a7bf9478fa02db4e51
991
java
Java
trace-sdk/src/test/java/io/bitrise/trace/data/management/formatter/device/DeviceIdDataFormatterTest.java
bitrise-io/trace-android-sdk
cbcd711adf4d918188581d89ac692364b20e0042
[ "MIT" ]
1
2021-09-01T09:55:04.000Z
2021-09-01T09:55:04.000Z
trace-sdk/src/test/java/io/bitrise/trace/data/management/formatter/device/DeviceIdDataFormatterTest.java
bitrise-io/trace-android-sdk
cbcd711adf4d918188581d89ac692364b20e0042
[ "MIT" ]
35
2021-04-06T11:30:46.000Z
2021-08-25T13:47:32.000Z
trace-sdk/src/test/java/io/bitrise/trace/data/management/formatter/device/DeviceIdDataFormatterTest.java
bitrise-io/trace-android-sdk
cbcd711adf4d918188581d89ac692364b20e0042
[ "MIT" ]
null
null
null
33.033333
95
0.785066
13,393
package io.bitrise.trace.data.management.formatter.device; import static org.junit.Assert.assertEquals; import io.bitrise.trace.data.collector.device.DeviceIdDataCollector; import io.bitrise.trace.data.dto.Data; import io.bitrise.trace.data.dto.FormattedData; import io.bitrise.trace.data.management.formatter.BaseDataFormatterTest; import io.bitrise.trace.data.resource.ResourceEntity; import java.util.UUID; import org.junit.Test; /** * Tests for {@link DeviceIdDataFormatter}. */ public class DeviceIdDataFormatterTest extends BaseDataFormatterTest { @Test public void formatData() { final String devideId = UUID.randomUUID().toString(); final Data inputData = new Data(DeviceIdDataCollector.class); inputData.setContent(devideId); final FormattedData[] outputData = new DeviceIdDataFormatter().formatData(inputData); assertEquals(1, outputData.length); assertEquals(new ResourceEntity("device.id", devideId), outputData[0].getResourceEntity()); } }
3e1fb3a71399c33c627f98d32d0ce68a2ca58692
1,192
java
Java
src/main/java/io/renren/modules/product/dao/BoxAddLeaveDao.java
389091912/renren-fast
3acdd6470d9d9f6afee3576c926f6497eda3a9d2
[ "Apache-2.0" ]
1
2019-06-09T06:43:48.000Z
2019-06-09T06:43:48.000Z
src/main/java/io/renren/modules/product/dao/BoxAddLeaveDao.java
389091912/renren-fast
3acdd6470d9d9f6afee3576c926f6497eda3a9d2
[ "Apache-2.0" ]
2
2021-04-22T16:46:40.000Z
2021-09-20T20:45:29.000Z
src/main/java/io/renren/modules/product/dao/BoxAddLeaveDao.java
389091912/renren-fast
3acdd6470d9d9f6afee3576c926f6497eda3a9d2
[ "Apache-2.0" ]
1
2019-06-09T06:43:39.000Z
2019-06-09T06:43:39.000Z
30.538462
125
0.769941
13,394
package io.renren.modules.product.dao; import io.renren.modules.product.entity.BoxAddLeaveEntity; import com.baomidou.mybatisplus.mapper.BaseMapper; import io.renren.modules.product.entity.vo.DictVo; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * * * @author wsy * @email efpyi@example.com * @date 2019-01-30 02:41:40 */ @Mapper public interface BoxAddLeaveDao extends BaseMapper<BoxAddLeaveEntity> { BoxAddLeaveEntity addBoxNumberCount(@Param( "boxNo" ) String boxNo); BoxAddLeaveEntity addBoxNumberCount1(@Param("params")Map<String,Object> params); BoxAddLeaveEntity addBoxNumberCount2(@Param("boxNo") String boxNo, @Param("factoryId") Integer factoryId); BoxAddLeaveEntity leaveBoxNumberCount(@Param( "boxNo" ) String boxNo); BoxAddLeaveEntity leaveBoxNumberCount1(@Param("params")Map<String,Object> params); BoxAddLeaveEntity leaveBoxNumberCount2(@Param( "boxNo" ) String boxNo, @Param("factoryId") Integer factoryId); Integer countAddBoxNumberByOrderIdAndProductId(@Param("orderId") Integer orderId, @Param("productId") Integer productId); }
3e1fb3cfd530a7fed852dc4374190b7179d4b2bb
814
java
Java
src/main/java/com/moarperipherals/handler/IDeathHook.java
theoriginalbit/MoarPeripherals
4708f1764a8776f7c03028c236104709f37c8a32
[ "Apache-2.0" ]
13
2015-01-21T02:53:04.000Z
2021-12-24T17:13:02.000Z
src/main/java/com/moarperipherals/handler/IDeathHook.java
theoriginalbit/MoarPeripherals
4708f1764a8776f7c03028c236104709f37c8a32
[ "Apache-2.0" ]
41
2015-01-09T18:16:48.000Z
2018-07-18T23:47:52.000Z
src/main/java/com/moarperipherals/handler/IDeathHook.java
theoriginalbit/MoarPeripherals
4708f1764a8776f7c03028c236104709f37c8a32
[ "Apache-2.0" ]
17
2015-01-21T02:59:18.000Z
2020-05-11T19:39:24.000Z
35.391304
75
0.751843
13,395
/** * Copyright 2014-2015 Joshua Asbury (@theoriginalbit) * <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.moarperipherals.handler; import net.minecraftforge.event.entity.living.LivingDeathEvent; public interface IDeathHook { void onDeathEvent(LivingDeathEvent event); }
3e1fb3ecd364b6166139ae26dee8e73df6245275
1,533
java
Java
chat-service/src/main/java/eu/stefanangelov/chatbot/chatservice/controller/MessagesApi.java
cefothe/distributed-chat-system
f02e76b9b5dd3d0cd63d6ea16c2973c993615df4
[ "Apache-2.0" ]
2
2019-03-01T14:09:02.000Z
2019-03-25T09:59:58.000Z
chat-service/src/main/java/eu/stefanangelov/chatbot/chatservice/controller/MessagesApi.java
cefothe/distributed-chat-system
f02e76b9b5dd3d0cd63d6ea16c2973c993615df4
[ "Apache-2.0" ]
23
2018-12-25T23:30:30.000Z
2019-12-29T23:15:41.000Z
chat-service/src/main/java/eu/stefanangelov/chatbot/chatservice/controller/MessagesApi.java
cefothe/distributed-chat-system
f02e76b9b5dd3d0cd63d6ea16c2973c993615df4
[ "Apache-2.0" ]
null
null
null
41.432432
182
0.711676
13,396
/** * NOTE: This class is auto generated by the swagger code generator program (3.0.4-SNAPSHOT). * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ package eu.stefanangelov.chatbot.chatservice.controller; import eu.stefanangelov.chatbot.chatservice.to.MessageTO; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.validation.Valid; import java.util.List; /** * Define message api interface */ public interface MessagesApi { @ApiOperation(value = "Get all user messages", nickname = "messagesGet", notes = "", responseContainer = "List", response = MessageTO.class, authorizations = { @Authorization(value = "bearerAuth") }, tags = {}) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = MessageTO.class), @ApiResponse(code = 401, message = "Authorization information is missing or invalid."), @ApiResponse(code = 500, message = "Unexpected error.")}) @RequestMapping(value = "/messages", produces = {"application/json"}, method = RequestMethod.GET) ResponseEntity<List<MessageTO>> messagesGet(@ApiParam(value = "subset of the results to return") @Valid @RequestParam(value = "queryRange", required = false) Integer queryRange); }
3e1fb5c598c020dcb57a9008cba58194335fdbad
14,606
java
Java
src/main/java/org/nbandroid/netbeans/gradle/v2/sdk/ui/SDKVisualPanelInstall.java
netmackan/NBANDROID-V2
512eecf2fbb3a7a72cba17ba366904bf023ad694
[ "Apache-2.0" ]
92
2017-10-25T09:05:40.000Z
2022-03-14T21:05:04.000Z
src/main/java/org/nbandroid/netbeans/gradle/v2/sdk/ui/SDKVisualPanelInstall.java
netmackan/NBANDROID-V2
512eecf2fbb3a7a72cba17ba366904bf023ad694
[ "Apache-2.0" ]
148
2017-10-24T20:23:40.000Z
2022-03-14T12:34:50.000Z
src/main/java/org/nbandroid/netbeans/gradle/v2/sdk/ui/SDKVisualPanelInstall.java
netmackan/NBANDROID-V2
512eecf2fbb3a7a72cba17ba366904bf023ad694
[ "Apache-2.0" ]
28
2017-10-24T20:03:26.000Z
2022-02-16T15:25:38.000Z
47.116129
195
0.661304
13,397
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.nbandroid.netbeans.gradle.v2.sdk.ui; import java.io.File; import java.io.IOException; import javax.swing.JPanel; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.nbandroid.netbeans.gradle.v2.maven.MavenDownloader; import org.openide.WizardDescriptor; import org.openide.filesystems.FileChooserBuilder; /** * @author ArSi */ public final class SDKVisualPanelInstall extends JPanel implements DocumentListener { private File tools; private File platformTools; private boolean sdkInstalled = false; public static final String SDK_INSTALLED = "SDK_INSTALLED"; /** * Creates new form SDKVisualPanel3 */ public SDKVisualPanelInstall() { initComponents(); putClientProperty(WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, 2); putClientProperty(WizardDescriptor.PROP_AUTO_WIZARD_STYLE, true); putClientProperty(WizardDescriptor.PROP_CONTENT_DISPLAYED, true); putClientProperty(WizardDescriptor.PROP_CONTENT_NUMBERED, true); warning.setVisible(false); install.setEnabled(false); path.getDocument().addDocumentListener(this); sdkName.getDocument().addDocumentListener(this); } @Override public String getName() { return "Install SDK"; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ public boolean isSdkInstalled() { return sdkInstalled && !sdkName.getText().isEmpty(); } public String getSdkPath() { return path.getText(); } public String getSdkName() { return sdkName.getText(); } // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); browse = new javax.swing.JButton(); install = new javax.swing.JButton(); path = new javax.swing.JTextField(); progress = new javax.swing.JProgressBar(); warning = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); sdkName = new javax.swing.JTextField(); setMaximumSize(new java.awt.Dimension(611, 154)); jLabel2.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(SDKVisualPanelInstall.class, "SDKVisualPanelInstall.jLabel2.text")); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(SDKVisualPanelInstall.class, "SDKVisualPanelInstall.jLabel3.text")); // NOI18N jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(SDKVisualPanelInstall.class, "SDKVisualPanelInstall.jPanel1.border.title"))); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(browse, org.openide.util.NbBundle.getMessage(SDKVisualPanelInstall.class, "SDKVisualPanelInstall.browse.text")); // NOI18N browse.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(install, org.openide.util.NbBundle.getMessage(SDKVisualPanelInstall.class, "SDKVisualPanelInstall.install.text")); // NOI18N install.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { installActionPerformed(evt); } }); path.setText(org.openide.util.NbBundle.getMessage(SDKVisualPanelInstall.class, "SDKVisualPanelInstall.path.text")); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(path) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(browse) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(install)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(progress, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {install, progress}); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(7, 7, 7) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(browse) .addComponent(install) .addComponent(path, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(1, 1, 1) .addComponent(progress, javax.swing.GroupLayout.PREFERRED_SIZE, 5, Short.MAX_VALUE)) ); warning.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/nbandroid/netbeans/gradle/v2/sdk/ui/warning-badge.png"))); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(warning, org.openide.util.NbBundle.getMessage(SDKVisualPanelInstall.class, "SDKVisualPanelInstall.warning.text")); // NOI18N jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(SDKVisualPanelInstall.class, "SDKVisualPanelInstall.jPanel2.border.title"))); // NOI18N sdkName.setText(org.openide.util.NbBundle.getMessage(SDKVisualPanelInstall.class, "SDKVisualPanelInstall.sdkName.text")); // NOI18N javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(sdkName) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(sdkName, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(warning) .addComponent(jLabel2) .addGroup(layout.createSequentialGroup() .addGap(7, 7, 7) .addComponent(jLabel3))) .addGap(0, 243, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(0, 0, 0) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE) .addComponent(warning) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void installActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_installActionPerformed browse.setEnabled(false); install.setEnabled(false); Runnable runnable = new Runnable() { @Override public void run() { progress.setIndeterminate(true); String destDir = path.getText(); try { MavenDownloader.unzip(tools, new File(destDir)); MavenDownloader.unzip(platformTools, new File(destDir)); sdkInstalled = true; } catch (IOException ex) { warning.setText("An error occurred while extracting zip file!"); warning.setVisible(true); sdkInstalled = false; } finally { progress.setIndeterminate(false); progress.setValue(progress.getMaximum()); firePropertyChange(SDK_INSTALLED, false, true); } } }; MavenDownloader.POOL.execute(runnable); }//GEN-LAST:event_installActionPerformed private void browseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseActionPerformed // TODO add your handling code here: FileChooserBuilder chooserBuilder = new FileChooserBuilder(SDKVisualPanelInstall.class); chooserBuilder.setDirectoriesOnly(true); chooserBuilder.setTitle("Choose the folder in which to install Android SDK Tools."); chooserBuilder.setApproveText("OK"); File tmp = chooserBuilder.showOpenDialog(); if (tmp != null) { path.setText(tmp.getAbsolutePath()); } }//GEN-LAST:event_browseActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton browse; private javax.swing.JButton install; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField path; private javax.swing.JProgressBar progress; private javax.swing.JTextField sdkName; private javax.swing.JLabel warning; // End of variables declaration//GEN-END:variables void setZipFiles(File tools, File platformTools) { this.tools = tools; this.platformTools = platformTools; testPath(); } public void testPath() { String text = path.getText(); if (text.isEmpty()) { warning.setText("Please choose a folder to install SDK Tools!"); warning.setVisible(true); } else { File tmp = new File(text); if (!tmp.exists()) { warning.setText("Selected path doesn't exist!"); warning.setVisible(true); } else if (!tmp.isDirectory()) { warning.setText("Selected path is not a directory!"); warning.setVisible(true); } else if (tmp.listFiles().length > 0) { warning.setText("Selected directory is not empty!"); warning.setVisible(true); } else if (sdkName.getText().isEmpty()) { warning.setText("Please choose a Name for SDK!"); warning.setVisible(true); } else { warning.setVisible(false); install.setEnabled(true); } } } @Override public void insertUpdate(DocumentEvent e) { testPath(); } @Override public void removeUpdate(DocumentEvent e) { testPath(); } @Override public void changedUpdate(DocumentEvent e) { testPath(); } }
3e1fb62d38ac09a98c5782f9a88768b0f08a6c34
4,179
java
Java
aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/transform/DescribeRaidArraysRequestMarshaller.java
johndemic/aws-sdk-java
784c5c058be640c5929da0d685e3f12d7b1669b7
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/transform/DescribeRaidArraysRequestMarshaller.java
johndemic/aws-sdk-java
784c5c058be640c5929da0d685e3f12d7b1669b7
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/transform/DescribeRaidArraysRequestMarshaller.java
johndemic/aws-sdk-java
784c5c058be640c5929da0d685e3f12d7b1669b7
[ "Apache-2.0" ]
null
null
null
37.648649
152
0.668342
13,398
/* * Copyright 2011-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.opsworks.model.transform; import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.opsworks.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.protocol.json.*; /** * DescribeRaidArraysRequest Marshaller */ public class DescribeRaidArraysRequestMarshaller implements Marshaller<Request<DescribeRaidArraysRequest>, DescribeRaidArraysRequest> { private final SdkJsonProtocolFactory protocolFactory; public DescribeRaidArraysRequestMarshaller( SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<DescribeRaidArraysRequest> marshall( DescribeRaidArraysRequest describeRaidArraysRequest) { if (describeRaidArraysRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<DescribeRaidArraysRequest> request = new DefaultRequest<DescribeRaidArraysRequest>( describeRaidArraysRequest, "AWSOpsWorks"); request.addHeader("X-Amz-Target", "OpsWorks_20130218.DescribeRaidArrays"); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { final StructuredJsonGenerator jsonGenerator = protocolFactory .createGenerator(); jsonGenerator.writeStartObject(); if (describeRaidArraysRequest.getInstanceId() != null) { jsonGenerator.writeFieldName("InstanceId").writeValue( describeRaidArraysRequest.getInstanceId()); } if (describeRaidArraysRequest.getStackId() != null) { jsonGenerator.writeFieldName("StackId").writeValue( describeRaidArraysRequest.getStackId()); } com.amazonaws.internal.SdkInternalList<String> raidArrayIdsList = (com.amazonaws.internal.SdkInternalList<String>) describeRaidArraysRequest .getRaidArrayIds(); if (!raidArrayIdsList.isEmpty() || !raidArrayIdsList.isAutoConstruct()) { jsonGenerator.writeFieldName("RaidArrayIds"); jsonGenerator.writeStartArray(); for (String raidArrayIdsListValue : raidArrayIdsList) { if (raidArrayIdsListValue != null) { jsonGenerator.writeValue(raidArrayIdsListValue); } } jsonGenerator.writeEndArray(); } jsonGenerator.writeEndObject(); byte[] content = jsonGenerator.getBytes(); request.setContent(new ByteArrayInputStream(content)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", protocolFactory.getContentType()); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
3e1fb69bef3d4b2c43d55251df0f9fa7a3421aa9
774
java
Java
zeromall-coupon/src/main/java/com/hpr/zeromall/coupon/entity/SeckillPromotionEntity.java
zero-unicorn/zeroMall
036ed16f37735f8d313f8d94119f615a3f2b00ac
[ "Apache-2.0" ]
null
null
null
zeromall-coupon/src/main/java/com/hpr/zeromall/coupon/entity/SeckillPromotionEntity.java
zero-unicorn/zeroMall
036ed16f37735f8d313f8d94119f615a3f2b00ac
[ "Apache-2.0" ]
null
null
null
zeromall-coupon/src/main/java/com/hpr/zeromall/coupon/entity/SeckillPromotionEntity.java
zero-unicorn/zeroMall
036ed16f37735f8d313f8d94119f615a3f2b00ac
[ "Apache-2.0" ]
null
null
null
14.584906
61
0.675291
13,399
package com.hpr.zeromall.coupon.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 秒杀活动 * * @author hpr * @email anpch@example.com * @date 2020-06-11 10:14:07 */ @Data @TableName("sms_seckill_promotion") public class SeckillPromotionEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId private Long id; /** * 活动标题 */ private String title; /** * 开始日期 */ private Date startTime; /** * 结束日期 */ private Date endTime; /** * 上下线状态 */ private Integer status; /** * 创建时间 */ private Date createTime; /** * 创建人 */ private Long userId; }
3e1fb6a9c9c967af045116e61e36ac5902d95a1c
3,473
java
Java
components/devtools_bridge/android/java/src/org/chromium/components/devtools_bridge/AbstractPeerConnection.java
sunjc53yy/chromium
049b380040949089c2a6e447b0cd0ac3c4ece38e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
components/devtools_bridge/android/java/src/org/chromium/components/devtools_bridge/AbstractPeerConnection.java
sunjc53yy/chromium
049b380040949089c2a6e447b0cd0ac3c4ece38e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/devtools_bridge/android/java/src/org/chromium/components/devtools_bridge/AbstractPeerConnection.java
sunjc53yy/chromium
049b380040949089c2a6e447b0cd0ac3c4ece38e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.000Z
32.457944
100
0.657645
13,400
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.devtools_bridge; /** * Limited view on org.webrtc.PeerConnection. Abstraction layer helps with: * 1. Allows both native and Java API implementation. * 2. Hides unused features. * Should be accessed on a single thread. */ public abstract class AbstractPeerConnection { /** * All methods are callen on WebRTC signaling thread. */ public interface Observer { /** * Called when createAndSetLocalDescription or setRemoteDescription failed. */ void onFailure(String description); /** * Called when createAndSetLocalDescription succeeded. */ void onLocalDescriptionCreatedAndSet(SessionDescriptionType type, String description); /** * Called when setRemoteDescription succeeded. */ void onRemoteDescriptionSet(); /** * New ICE candidate available. String representation defined in the IceCandidate class. * To be sent to the remote peer connection. */ void onIceCandidate(String iceCandidate); /** * Called when connected or disconnected. In disconnected state recovery procedure * should only rely on signaling channel. */ void onIceConnectionChange(boolean connected); } /** * Type of session description. */ public enum SessionDescriptionType { OFFER, ANSWER } /** * The result of this method will be invocation onLocalDescriptionCreatedAndSet * or onFailure on the observer. Should not be called when waiting result of * setRemoteDescription. */ public abstract void createAndSetLocalDescription(SessionDescriptionType type); /** * Result of this method will be invocation onRemoteDescriptionSet or onFailure on the observer. */ public abstract void setRemoteDescription(SessionDescriptionType type, String description); /** * Adds a remote ICE candidate. */ public abstract void addIceCandidate(String candidate); /** * Destroys native objects. Synchronized with the signaling thread * (no observer method called when the connection disposed) */ public abstract void dispose(); /** * Creates prenegotiated SCTP data channel. */ public abstract AbstractDataChannel createDataChannel(int channelId); /** * Helper class which enforces string representation of an ICE candidate. */ static class IceCandidate { public final String sdpMid; public final int sdpMLineIndex; public final String sdp; public IceCandidate(String sdpMid, int sdpMLineIndex, String sdp) { this.sdpMid = sdpMid; this.sdpMLineIndex = sdpMLineIndex; this.sdp = sdp; } public String toString() { return sdpMid + ":" + sdpMLineIndex + ":" + sdp; } public static IceCandidate fromString(String candidate) throws IllegalArgumentException { String[] parts = candidate.split(":", 3); if (parts.length != 3) throw new IllegalArgumentException("Expected column separated list."); return new IceCandidate(parts[0], Integer.parseInt(parts[1]), parts[2]); } } }
3e1fb7003630571f8128c6bfade3938234086d2f
696
java
Java
ch12-7/ch12-7-config-client-jwt/src/main/java/cn/springcloud/book/config/jwt/dto/Token.java
shadowedge/spring-cloud-code
1988314ac228b9b60756eaeaad164ac1aa47883b
[ "Apache-2.0" ]
1,932
2018-08-08T03:56:32.000Z
2022-03-29T08:28:14.000Z
ch12-7/ch12-7-config-client-jwt/src/main/java/cn/springcloud/book/config/jwt/dto/Token.java
shadowedge/spring-cloud-code
1988314ac228b9b60756eaeaad164ac1aa47883b
[ "Apache-2.0" ]
43
2018-08-29T14:20:25.000Z
2021-10-14T06:30:45.000Z
ch12-7/ch12-7-config-client-jwt/src/main/java/cn/springcloud/book/config/jwt/dto/Token.java
shadowedge/spring-cloud-code
1988314ac228b9b60756eaeaad164ac1aa47883b
[ "Apache-2.0" ]
1,001
2018-08-27T08:17:27.000Z
2022-03-23T04:42:25.000Z
21.090909
61
0.685345
13,401
package cn.springcloud.book.config.jwt.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author: zzf * @date: 2018/6/23 * @time: 13:44 * @description : do some thing */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class Token { @JsonProperty private String token; public String getToken() { return token; } public void setToken(String token) { this.token = token; } @Override public String toString() { return "Token [token=" + token + "]"; } }
3e1fb72b056c926ee7f0264aa887ce3e044fa2db
3,744
java
Java
sample/src/main/java/io/runtime/mcumgr/sample/fragment/mcumgr/DeviceStatusFragment.java
NordicSemiconductor/mcumgr-android
d377af1c394cd606648fc672cdf21499b91bec56
[ "Apache-2.0" ]
25
2020-07-06T16:56:54.000Z
2022-03-30T00:53:35.000Z
sample/src/main/java/io/runtime/mcumgr/sample/fragment/mcumgr/DeviceStatusFragment.java
NordicSemiconductor/mcumgr-android
d377af1c394cd606648fc672cdf21499b91bec56
[ "Apache-2.0" ]
12
2021-02-03T07:33:17.000Z
2022-03-24T14:26:50.000Z
sample/src/main/java/io/runtime/mcumgr/sample/fragment/mcumgr/DeviceStatusFragment.java
NordicSemiconductor/mcumgr-android
d377af1c394cd606648fc672cdf21499b91bec56
[ "Apache-2.0" ]
14
2020-07-17T02:17:37.000Z
2022-02-24T13:23:00.000Z
36
100
0.634348
13,402
/* * Copyright (c) 2018, Nordic Semiconductor * * SPDX-License-Identifier: Apache-2.0 */ package io.runtime.mcumgr.sample.fragment.mcumgr; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import javax.inject.Inject; import io.runtime.mcumgr.sample.R; import io.runtime.mcumgr.sample.databinding.FragmentCardDeviceStatusBinding; import io.runtime.mcumgr.sample.di.Injectable; import io.runtime.mcumgr.sample.viewmodel.mcumgr.DeviceStatusViewModel; import io.runtime.mcumgr.sample.viewmodel.mcumgr.McuMgrViewModelFactory; public class DeviceStatusFragment extends Fragment implements Injectable { @Inject McuMgrViewModelFactory viewModelFactory; private FragmentCardDeviceStatusBinding binding; private DeviceStatusViewModel viewModel; @Override public void onCreate(@Nullable final Bundle savedInstanceState) { super.onCreate(savedInstanceState); viewModel = new ViewModelProvider(this, viewModelFactory) .get(DeviceStatusViewModel.class); } @Nullable @Override public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) { binding = FragmentCardDeviceStatusBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); viewModel.getConnectionState().observe(getViewLifecycleOwner(), state -> { switch (state) { case CONNECTING: binding.connectionStatus.setText(R.string.status_connecting); break; case INITIALIZING: binding.connectionStatus.setText(R.string.status_initializing); break; case READY: binding.connectionStatus.setText(R.string.status_connected); break; case DISCONNECTING: binding.connectionStatus.setText(R.string.status_disconnecting); break; case DISCONNECTED: binding.connectionStatus.setText(R.string.status_disconnected); break; case TIMEOUT: binding.connectionStatus.setText(R.string.status_connection_timeout); break; case NOT_SUPPORTED: binding.connectionStatus.setText(R.string.status_not_supported); break; } }); viewModel.getBondState().observe(getViewLifecycleOwner(), state -> { switch (state) { case NOT_BONDED: binding.bondingStatus.setText(R.string.status_not_bonded); break; case BONDING: binding.bondingStatus.setText(R.string.status_bonding); break; case BONDED: binding.bondingStatus.setText(R.string.status_bonded); break; } }); viewModel.getBusyState().observe(getViewLifecycleOwner(), busy -> binding.workIndicator.setVisibility(busy ? View.VISIBLE : View.GONE)); } @Override public void onDestroyView() { super.onDestroyView(); binding = null; } }
3e1fb73e72cf588c9e69a67b0c613a1c929f6c83
1,002
java
Java
src/main/java/io/leangen/graphql/GeneratorConfiguration.java
pepijno/graphql-spqr
aba927ebe28586d34e09b8a69998732e4fd94742
[ "Apache-2.0" ]
null
null
null
src/main/java/io/leangen/graphql/GeneratorConfiguration.java
pepijno/graphql-spqr
aba927ebe28586d34e09b8a69998732e4fd94742
[ "Apache-2.0" ]
null
null
null
src/main/java/io/leangen/graphql/GeneratorConfiguration.java
pepijno/graphql-spqr
aba927ebe28586d34e09b8a69998732e4fd94742
[ "Apache-2.0" ]
null
null
null
47.714286
196
0.831337
13,403
package io.leangen.graphql; import io.leangen.graphql.generator.mapping.strategy.InterfaceMappingStrategy; import io.leangen.graphql.metadata.strategy.type.TypeTransformer; import io.leangen.graphql.metadata.strategy.value.ScalarDeserializationStrategy; @SuppressWarnings("WeakerAccess") public class GeneratorConfiguration { public final InterfaceMappingStrategy interfaceMappingStrategy; public final ScalarDeserializationStrategy scalarDeserializationStrategy; public final TypeTransformer typeTransformer; public final String[] basePackages; GeneratorConfiguration(InterfaceMappingStrategy interfaceMappingStrategy, ScalarDeserializationStrategy scalarDeserializationStrategy, TypeTransformer typeTransformer, String[] basePackages) { this.interfaceMappingStrategy = interfaceMappingStrategy; this.scalarDeserializationStrategy = scalarDeserializationStrategy; this.typeTransformer = typeTransformer; this.basePackages = basePackages; } }
3e1fb73f68f8a4c1651abe829244d905db8ab099
1,362
java
Java
src/ca/pfv/spmf/test/MainTestFSGP_saveToFile.java
MammadDavari/CARER-
163cf555653aaf6adb4099ac74f5590b635c44c6
[ "MIT" ]
8
2018-03-28T02:46:57.000Z
2020-06-07T09:01:25.000Z
src/ca/pfv/spmf/test/MainTestFSGP_saveToFile.java
MammadDavari/CARER-
163cf555653aaf6adb4099ac74f5590b635c44c6
[ "MIT" ]
null
null
null
src/ca/pfv/spmf/test/MainTestFSGP_saveToFile.java
MammadDavari/CARER-
163cf555653aaf6adb4099ac74f5590b635c44c6
[ "MIT" ]
1
2021-01-02T12:12:56.000Z
2021-01-02T12:12:56.000Z
34.05
86
0.762849
13,404
package ca.pfv.spmf.test; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import ca.pfv.spmf.algorithms.sequentialpatterns.BIDE_and_prefixspan.AlgoFSGP; import ca.pfv.spmf.input.sequence_database_list_integers.SequenceDatabase; /** * Example of how to use the FSGP algorithm in source code. * @author Philippe Fournier-Viger */ public class MainTestFSGP_saveToFile { public static void main(String [] arg) throws IOException{ String outputPath = ".//output.txt"; // Load a Sequence database SequenceDatabase sequenceDatabase = new SequenceDatabase(); sequenceDatabase.loadFile(fileToPath("contextPrefixSpan.txt")); // print the database to console // sequenceDatabase.print(); // Create an instance of the algorithm with minsup = 50 % AlgoFSGP algo = new AlgoFSGP(); int minsup = 2; // we use a minimum support of 2 sequences. // execute the algorithm boolean performPruning = true;// to activate pruning of search space algo.runAlgorithm(sequenceDatabase, outputPath, minsup, performPruning); algo.printStatistics(sequenceDatabase.size()); } public static String fileToPath(String filename) throws UnsupportedEncodingException{ URL url = MainTestFSGP_saveToFile.class.getResource(filename); return java.net.URLDecoder.decode(url.getPath(),"UTF-8"); } }
3e1fb86f1461f3cc77b3880d14e11c1de8c891fd
3,220
java
Java
rdb/rdb-sink/src/main/java/com/dtstack/flink/sql/sink/rdb/table/RdbSinkParser.java
Mu-L/flinkStreamSQL
0c66b19bc2f5cdd845981b524646b3259df3d1a4
[ "Apache-2.0" ]
1,858
2018-09-12T09:55:04.000Z
2022-03-31T02:13:44.000Z
rdb/rdb-sink/src/main/java/com/dtstack/flink/sql/sink/rdb/table/RdbSinkParser.java
xueqianging/flinkStreamSQL
0c66b19bc2f5cdd845981b524646b3259df3d1a4
[ "Apache-2.0" ]
370
2018-10-04T10:06:30.000Z
2022-03-22T03:00:53.000Z
rdb/rdb-sink/src/main/java/com/dtstack/flink/sql/sink/rdb/table/RdbSinkParser.java
xueqianging/flinkStreamSQL
0c66b19bc2f5cdd845981b524646b3259df3d1a4
[ "Apache-2.0" ]
911
2018-09-12T09:55:07.000Z
2022-03-29T05:28:18.000Z
52.786885
126
0.765528
13,405
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flink.sql.sink.rdb.table; import com.dtstack.flink.sql.table.AbstractTableParser; import com.dtstack.flink.sql.table.AbstractTableInfo; import com.dtstack.flink.sql.util.MathUtil; import java.util.Map; /** * Reason: * Date: 2018/11/27 * Company: www.dtstack.com * * @author maqi */ public class RdbSinkParser extends AbstractTableParser { @Override public AbstractTableInfo getTableInfo(String tableName, String fieldsInfo, Map<String, Object> props) { RdbTableInfo rdbTableInfo = new RdbTableInfo(); rdbTableInfo.setName(tableName); parseFieldsInfo(fieldsInfo, rdbTableInfo); rdbTableInfo.setParallelism(MathUtil.getIntegerVal(props.get(RdbTableInfo.PARALLELISM_KEY.toLowerCase()))); rdbTableInfo.setUrl(MathUtil.getString(props.get(RdbTableInfo.URL_KEY.toLowerCase()))); rdbTableInfo.setTableName(MathUtil.getString(props.get(RdbTableInfo.TABLE_NAME_KEY.toLowerCase()))); rdbTableInfo.setUserName(MathUtil.getString(props.get(RdbTableInfo.USER_NAME_KEY.toLowerCase()))); rdbTableInfo.setPassword(MathUtil.getString(props.get(RdbTableInfo.PASSWORD_KEY.toLowerCase()))); rdbTableInfo.setBatchSize(MathUtil.getIntegerVal(props.get(RdbTableInfo.BATCH_SIZE_KEY.toLowerCase()))); rdbTableInfo.setBatchWaitInterval(MathUtil.getLongVal(props.get(RdbTableInfo.BATCH_WAIT_INTERVAL_KEY.toLowerCase()))); rdbTableInfo.setBufferSize(MathUtil.getString(props.get(RdbTableInfo.BUFFER_SIZE_KEY.toLowerCase()))); rdbTableInfo.setFlushIntervalMs(MathUtil.getString(props.get(RdbTableInfo.FLUSH_INTERVALMS_KEY.toLowerCase()))); rdbTableInfo.setSchema(MathUtil.getString(props.get(RdbTableInfo.SCHEMA_KEY.toLowerCase()))); rdbTableInfo.setUpdateMode(MathUtil.getString(props.get(RdbTableInfo.UPDATE_KEY.toLowerCase()))); rdbTableInfo.setAllReplace(MathUtil.getBoolean(props.get(RdbTableInfo.ALLREPLACE_KEY.toLowerCase()), false)); rdbTableInfo.setDriverName(MathUtil.getString(props.get(RdbTableInfo.DRIVER_NAME))); rdbTableInfo.setFastCheck(MathUtil.getBoolean(props.getOrDefault(RdbTableInfo.FAST_CHECK.toLowerCase(), false))); rdbTableInfo.setErrorLimit(MathUtil.getLongVal(props.get(RdbTableInfo.ERROR_LIMIT.toLowerCase()), 0L)); rdbTableInfo.setCheckProperties(); rdbTableInfo.check(); return rdbTableInfo; } }
3e1fb913a58f8e3246cae3ade762a00de3747b00
1,576
java
Java
src/main/java/fwlib32/idbpdfadir.java
civilizeddev/fanuc-focas
c9878c70f48830f92e43c77f04f1ebb2a0b2d567
[ "MIT" ]
6
2021-07-26T04:07:50.000Z
2022-03-24T22:09:22.000Z
src/main/java/fwlib32/idbpdfadir.java
civilizeddev/fanuc-focas
c9878c70f48830f92e43c77f04f1ebb2a0b2d567
[ "MIT" ]
null
null
null
src/main/java/fwlib32/idbpdfadir.java
civilizeddev/fanuc-focas
c9878c70f48830f92e43c77f04f1ebb2a0b2d567
[ "MIT" ]
2
2022-01-24T08:32:52.000Z
2022-03-02T14:33:05.000Z
33.531915
195
0.701777
13,406
package fwlib32; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; /** * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class idbpdfadir extends Structure { /** path name */ public byte[] path = new byte[212]; /** entry number */ public short req_num; /** kind of size */ public short size_kind; /** kind of format */ public short type; public short dummy; public idbpdfadir() { super(); } protected List<String> getFieldOrder() { return Arrays.asList("path", "req_num", "size_kind", "type", "dummy"); } public idbpdfadir(byte path[], short req_num, short size_kind, short type, short dummy) { super(); if ((path.length != this.path.length)) throw new IllegalArgumentException("Wrong array size !"); this.path = path; this.req_num = req_num; this.size_kind = size_kind; this.type = type; this.dummy = dummy; } public idbpdfadir(Pointer peer) { super(peer); } public static class ByReference extends idbpdfadir implements Structure.ByReference { }; public static class ByValue extends idbpdfadir implements Structure.ByValue { }; }
3e1fba122f703eac4f498dd4b32fb5634915d939
2,477
java
Java
core/src/main/java/de/d3adspace/scipio/core/executor/FailureReporterTask.java
d3adspace/scipio
02cb8d80b844ea55e23ae9d2d0b7fa4bf982a3df
[ "MIT" ]
null
null
null
core/src/main/java/de/d3adspace/scipio/core/executor/FailureReporterTask.java
d3adspace/scipio
02cb8d80b844ea55e23ae9d2d0b7fa4bf982a3df
[ "MIT" ]
74
2019-10-15T09:39:16.000Z
2021-06-25T15:28:38.000Z
core/src/main/java/de/d3adspace/scipio/core/executor/FailureReporterTask.java
d3adspace/scipio
02cb8d80b844ea55e23ae9d2d0b7fa4bf982a3df
[ "MIT" ]
null
null
null
34.887324
125
0.662495
13,407
/* * Copyright (c) 2017 D3adspace * * 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 de.d3adspace.scipio.core.executor; import de.d3adspace.scipio.core.SimpleScipio; import de.d3adspace.scipio.core.description.FailureDescription; /** * The Agent who will report all incoming failures. * * @author Felix 'SasukeKawaii' Klauke */ public class FailureReporterTask implements Runnable { /** * The Scipio instance the reporter is working for. */ private final SimpleScipio scipio; /** * Create a new reporter task. * * @param scipio The scipio instance to work for. */ public FailureReporterTask(SimpleScipio scipio) { this.scipio = scipio; } @Override public void run() { while (true) { if (this.scipio.getPendingFailures().isEmpty()) { synchronized (this) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } FailureDescription failureDescription = this.scipio.getPendingFailures().peek(); if (failureDescription != null) { this.scipio.getFailureHandlers().forEach(failureHandler -> failureHandler.handleFailure(failureDescription)); this.scipio.getPendingFailures().remove(); } } } }
3e1fba650b18db96d281d364090a53f681cfc426
824
java
Java
src/main/java/co/aurasphere/facebot/actionframe/ActionFrame.java
wiki05/messengerbot
c5a27c0c55d07f841213bd1700a9d04f533ac5e9
[ "MIT" ]
null
null
null
src/main/java/co/aurasphere/facebot/actionframe/ActionFrame.java
wiki05/messengerbot
c5a27c0c55d07f841213bd1700a9d04f533ac5e9
[ "MIT" ]
null
null
null
src/main/java/co/aurasphere/facebot/actionframe/ActionFrame.java
wiki05/messengerbot
c5a27c0c55d07f841213bd1700a9d04f533ac5e9
[ "MIT" ]
null
null
null
20.6
60
0.741505
13,408
package co.aurasphere.facebot.actionframe; import co.aurasphere.facebot.autoreply.AutoReply; import co.aurasphere.facebot.event.FaceBotEvent; import co.aurasphere.facebot.model.incoming.MessageEnvelope; public class ActionFrame { private FaceBotEvent event; private AutoReply reply; public ActionFrame(FaceBotEvent event, AutoReply reply) { this.event = event; this.reply = reply; } public boolean process(MessageEnvelope envelope) { if (event == null) { return false; } boolean triggered = event.verifyEventCondition(envelope); if (triggered) { beforeReply(envelope); if (reply != null) { reply.reply(envelope); } afterReply(envelope); } return triggered; } public void beforeReply(MessageEnvelope envelope) { }; public void afterReply(MessageEnvelope envelope) { }; }
3e1fbb8da0e4be3f01fff9ed86b5fb16f8561168
6,566
java
Java
pinot-tools/src/main/java/org/apache/pinot/tools/admin/command/OperateClusterConfigCommand.java
wuwenw/incubator-pinot
3e20979a3b359c5c56ef815ce771e749710e5be2
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
2
2020-04-15T22:53:30.000Z
2020-04-15T22:53:35.000Z
pinot-tools/src/main/java/org/apache/pinot/tools/admin/command/OperateClusterConfigCommand.java
rpatid10/incubator-pinot
bd4239fc6908096f60ead9f1ee2c3576f256618b
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
60
2021-08-25T03:06:34.000Z
2022-03-28T22:52:06.000Z
pinot-tools/src/main/java/org/apache/pinot/tools/admin/command/OperateClusterConfigCommand.java
rpatid10/incubator-pinot
bd4239fc6908096f60ead9f1ee2c3576f256618b
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
2
2021-07-15T04:09:36.000Z
2021-07-27T21:12:12.000Z
35.491892
162
0.700731
13,409
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.tools.admin.command; import com.fasterxml.jackson.databind.JsonNode; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.http.Header; import org.apache.pinot.spi.utils.CommonConstants; import org.apache.pinot.spi.utils.JsonUtils; import org.apache.pinot.spi.utils.NetUtils; import org.apache.pinot.tools.Command; import org.kohsuke.args4j.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OperateClusterConfigCommand extends AbstractBaseAdminCommand implements Command { private static final Logger LOGGER = LoggerFactory.getLogger(OperateClusterConfigCommand.class.getName()); @Option(name = "-controllerHost", required = false, metaVar = "<String>", usage = "host name for controller.") private String _controllerHost; @Option(name = "-controllerPort", required = false, metaVar = "<int>", usage = "http port for controller.") private String _controllerPort = DEFAULT_CONTROLLER_PORT; @Option(name = "-controllerProtocol", required = false, metaVar = "<String>", usage = "protocol for controller.") private String _controllerProtocol = CommonConstants.HTTP_PROTOCOL; @Option(name = "-user", required = false, metaVar = "<String>", usage = "Username for basic auth.") private String _user; @Option(name = "-password", required = false, metaVar = "<String>", usage = "Password for basic auth.") private String _password; @Option(name = "-authToken", required = false, metaVar = "<String>", usage = "Http auth token.") private String _authToken; @Option(name = "-config", metaVar = "<string>", usage = "Cluster config to operate.") private String _config; @Option(name = "-operation", required = true, metaVar = "<string>", usage = "Operation to take for Cluster config, currently support GET/ADD/UPDATE/DELETE.") private String _operation; @Option(name = "-help", required = false, help = true, aliases = {"-h", "--h", "--help"}, usage = "Print this message.") private boolean _help = false; @Override public boolean getHelp() { return _help; } @Override public String getName() { return "DeleteClusterConfig"; } @Override public String toString() { String toString = "Operate ClusterConfig -controllerProtocol " + _controllerProtocol + " -controllerHost " + _controllerHost + " -controllerPort " + _controllerPort + " -operation " + _operation; if (_config != null) { toString += " -config " + _config; } return toString; } @Override public void cleanup() { } @Override public String description() { return "Operate Pinot Cluster Config. Sample usage: `pinot-admin.sh OperateClusterConfig -operation DELETE -config pinot.broker.enable.query.limit.override`"; } public OperateClusterConfigCommand setControllerHost(String host) { _controllerHost = host; return this; } public OperateClusterConfigCommand setControllerPort(String port) { _controllerPort = port; return this; } public OperateClusterConfigCommand setControllerProtocol(String controllerProtocol) { _controllerProtocol = controllerProtocol; return this; } public OperateClusterConfigCommand setUser(String user) { _user = user; return this; } public OperateClusterConfigCommand setPassword(String password) { _password = password; return this; } public OperateClusterConfigCommand setAuthToken(String authToken) { _authToken = authToken; return this; } public OperateClusterConfigCommand setConfig(String config) { _config = config; return this; } public OperateClusterConfigCommand setOperation(String operation) { _operation = operation; return this; } public String run() throws Exception { if (_controllerHost == null) { _controllerHost = NetUtils.getHostAddress(); } LOGGER.info("Executing command: " + toString()); if (StringUtils.isEmpty(_config) && !_operation.equalsIgnoreCase("GET")) { throw new UnsupportedOperationException("Empty config: " + _config); } String clusterConfigUrl = _controllerProtocol + "://" + _controllerHost + ":" + _controllerPort + "/cluster/configs"; List<Header> headers = makeAuthHeader(makeAuthToken(_authToken, _user, _password)); switch (_operation.toUpperCase()) { case "ADD": case "UPDATE": String[] splits = _config.split("="); if (splits.length != 2) { throw new UnsupportedOperationException( "Bad config: " + _config + ". Please follow the pattern of [Config Key]=[Config Value]"); } String request = JsonUtils.objectToString(Collections.singletonMap(splits[0], splits[1])); return sendRequest("POST", clusterConfigUrl, request, headers); case "GET": String response = sendRequest("GET", clusterConfigUrl, null, headers); JsonNode jsonNode = JsonUtils.stringToJsonNode(response); Iterator<String> fieldNamesIterator = jsonNode.fieldNames(); String results = ""; while (fieldNamesIterator.hasNext()) { String key = fieldNamesIterator.next(); String value = jsonNode.get(key).textValue(); results += String.format("%s=%s\n", key, value); } return results; case "DELETE": return sendRequest("DELETE", String.format("%s/%s", clusterConfigUrl, _config), null, headers); default: throw new UnsupportedOperationException("Unsupported operation: " + _operation); } } @Override public boolean execute() throws Exception { String result = run(); LOGGER.info(result); return true; } }
3e1fbe0c94661c05ea33008db93158c15c37f120
2,339
java
Java
modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/delegate/HadoopFileSystemFactoryDelegate.java
DirectXceriD/gridgain
093e512a9147e266f83f6fe1cf088c0b037b501c
[ "Apache-2.0", "CC0-1.0" ]
1
2019-03-11T08:52:37.000Z
2019-03-11T08:52:37.000Z
modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/delegate/HadoopFileSystemFactoryDelegate.java
DirectXceriD/gridgain
093e512a9147e266f83f6fe1cf088c0b037b501c
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/delegate/HadoopFileSystemFactoryDelegate.java
DirectXceriD/gridgain
093e512a9147e266f83f6fe1cf088c0b037b501c
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
43.314815
101
0.745618
13,411
/* * GridGain Community Edition Licensing * Copyright 2019 GridGain Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause * Restriction; 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. * * Commons Clause Restriction * * The Software is provided to you by the Licensor under the License, as defined below, subject to * the following condition. * * Without limiting other conditions in the License, the grant of rights under the License will not * include, and the License does not grant to you, the right to Sell the Software. * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you * under the License to provide to third parties, for a fee or other consideration (including without * limitation fees for hosting or consulting/ support services related to the Software), a product or * service whose value derives, entirely or substantially, from the functionality of the Software. * Any license notice or attribution required by the License must also include this Commons Clause * License Condition notice. * * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc., * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community * Edition software provided with this notice. */ package org.apache.ignite.internal.processors.hadoop.delegate; import org.apache.ignite.lifecycle.LifecycleAware; import java.io.IOException; /** * Hadoop file system factory delegate. */ public interface HadoopFileSystemFactoryDelegate extends LifecycleAware { /** * Gets file system for the given user name. * * @param usrName User name * @return File system. * @throws IOException In case of error. */ public Object get(String usrName) throws IOException; }
3e1fbfa6668cc22287ae9ede3c3ec2842709fdc9
145
java
Java
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation2/Class_605.java
lesaint/experimenting-annotation-processing
1e9692ceb0d3d2cda709e06ccc13290262f51b39
[ "Apache-2.0" ]
1
2016-01-18T17:57:21.000Z
2016-01-18T17:57:21.000Z
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation2/Class_605.java
lesaint/experimenting-annotation-processing
1e9692ceb0d3d2cda709e06ccc13290262f51b39
[ "Apache-2.0" ]
null
null
null
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation2/Class_605.java
lesaint/experimenting-annotation-processing
1e9692ceb0d3d2cda709e06ccc13290262f51b39
[ "Apache-2.0" ]
null
null
null
18.125
51
0.827586
13,412
package fr.javatronic.blog.massive.annotation2; import fr.javatronic.blog.processor.Annotation_002; @Annotation_002 public class Class_605 { }
3e1fc0bbe0f94d399473eead2209b6ec3af6057e
66
java
Java
common/src/main/java/eu/daiad/common/model/profile/WaterIq.java
DAIAD/home-web
4d5220cecc4483cd3f29db5b2274cf67261d765f
[ "Apache-2.0" ]
3
2016-06-07T15:07:02.000Z
2018-10-02T18:54:47.000Z
common/src/main/java/eu/daiad/common/model/profile/WaterIq.java
DAIAD/home-web
4d5220cecc4483cd3f29db5b2274cf67261d765f
[ "Apache-2.0" ]
7
2016-10-07T13:04:45.000Z
2021-09-28T10:55:23.000Z
common/src/main/java/eu/daiad/common/model/profile/WaterIq.java
DAIAD/home-web
4d5220cecc4483cd3f29db5b2274cf67261d765f
[ "Apache-2.0" ]
11
2015-07-30T10:21:20.000Z
2019-03-27T17:40:37.000Z
11
38
0.757576
13,413
package eu.daiad.common.model.profile; public class WaterIq { }
3e1fc0d09a703a91c2e83079a7f03edb8d0d68ec
4,524
java
Java
litemall-core/src/main/java/org/linlinjava/litemall/core/system/SystemConfig.java
npmmirror/litemall
be72af2f3a600b24cbc9a71845f9cf81f22deeab
[ "MIT" ]
18,168
2018-03-23T07:25:16.000Z
2022-03-31T08:50:39.000Z
litemall-core/src/main/java/org/linlinjava/litemall/core/system/SystemConfig.java
npmmirror/litemall
be72af2f3a600b24cbc9a71845f9cf81f22deeab
[ "MIT" ]
387
2018-03-28T03:37:57.000Z
2022-03-30T13:07:20.000Z
litemall-core/src/main/java/org/linlinjava/litemall/core/system/SystemConfig.java
npmmirror/litemall
be72af2f3a600b24cbc9a71845f9cf81f22deeab
[ "MIT" ]
7,240
2018-03-23T07:25:17.000Z
2022-03-31T07:06:43.000Z
33.761194
97
0.730769
13,414
package org.linlinjava.litemall.core.system; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; /** * 系统设置 */ public class SystemConfig { // 小程序相关配置 public final static String LITEMALL_WX_INDEX_NEW = "litemall_wx_index_new"; public final static String LITEMALL_WX_INDEX_HOT = "litemall_wx_index_hot"; public final static String LITEMALL_WX_INDEX_BRAND = "litemall_wx_index_brand"; public final static String LITEMALL_WX_INDEX_TOPIC = "litemall_wx_index_topic"; public final static String LITEMALL_WX_INDEX_CATLOG_LIST = "litemall_wx_catlog_list"; public final static String LITEMALL_WX_INDEX_CATLOG_GOODS = "litemall_wx_catlog_goods"; public final static String LITEMALL_WX_SHARE = "litemall_wx_share"; // 运费相关配置 public final static String LITEMALL_EXPRESS_FREIGHT_VALUE = "litemall_express_freight_value"; public final static String LITEMALL_EXPRESS_FREIGHT_MIN = "litemall_express_freight_min"; // 订单相关配置 public final static String LITEMALL_ORDER_UNPAID = "litemall_order_unpaid"; public final static String LITEMALL_ORDER_UNCONFIRM = "litemall_order_unconfirm"; public final static String LITEMALL_ORDER_COMMENT = "litemall_order_comment"; // 商场相关配置 public final static String LITEMALL_MALL_NAME = "litemall_mall_name"; public final static String LITEMALL_MALL_ADDRESS = "litemall_mall_address"; public final static String LITEMALL_MALL_PHONE = "litemall_mall_phone"; public final static String LITEMALL_MALL_QQ = "litemall_mall_qq"; public final static String LITEMALL_MALL_LONGITUDE = "litemall_mall_longitude"; public final static String LITEMALL_MALL_Latitude = "litemall_mall_latitude"; //所有的配置均保存在该 HashMap 中 private static Map<String, String> SYSTEM_CONFIGS = new HashMap<>(); private static String getConfig(String keyName) { return SYSTEM_CONFIGS.get(keyName); } private static Integer getConfigInt(String keyName) { return Integer.parseInt(SYSTEM_CONFIGS.get(keyName)); } private static Boolean getConfigBoolean(String keyName) { return Boolean.valueOf(SYSTEM_CONFIGS.get(keyName)); } private static BigDecimal getConfigBigDec(String keyName) { return new BigDecimal(SYSTEM_CONFIGS.get(keyName)); } public static Integer getNewLimit() { return getConfigInt(LITEMALL_WX_INDEX_NEW); } public static Integer getHotLimit() { return getConfigInt(LITEMALL_WX_INDEX_HOT); } public static Integer getBrandLimit() { return getConfigInt(LITEMALL_WX_INDEX_BRAND); } public static Integer getTopicLimit() { return getConfigInt(LITEMALL_WX_INDEX_TOPIC); } public static Integer getCatlogListLimit() { return getConfigInt(LITEMALL_WX_INDEX_CATLOG_LIST); } public static Integer getCatlogMoreLimit() { return getConfigInt(LITEMALL_WX_INDEX_CATLOG_GOODS); } public static boolean isAutoCreateShareImage() { return getConfigBoolean(LITEMALL_WX_SHARE); } public static BigDecimal getFreight() { return getConfigBigDec(LITEMALL_EXPRESS_FREIGHT_VALUE); } public static BigDecimal getFreightLimit() { return getConfigBigDec(LITEMALL_EXPRESS_FREIGHT_MIN); } public static Integer getOrderUnpaid() { return getConfigInt(LITEMALL_ORDER_UNPAID); } public static Integer getOrderUnconfirm() { return getConfigInt(LITEMALL_ORDER_UNCONFIRM); } public static Integer getOrderComment() { return getConfigInt(LITEMALL_ORDER_COMMENT); } public static String getMallName() { return getConfig(LITEMALL_MALL_NAME); } public static String getMallAddress() { return getConfig(LITEMALL_MALL_ADDRESS); } public static String getMallPhone() { return getConfig(LITEMALL_MALL_PHONE); } public static String getMallQQ() { return getConfig(LITEMALL_MALL_QQ); } public static String getMallLongitude() { return getConfig(LITEMALL_MALL_LONGITUDE); } public static String getMallLatitude() { return getConfig(LITEMALL_MALL_Latitude); } public static void setConfigs(Map<String, String> configs) { SYSTEM_CONFIGS = configs; } public static void updateConfigs(Map<String, String> data) { for (Map.Entry<String, String> entry : data.entrySet()) { SYSTEM_CONFIGS.put(entry.getKey(), entry.getValue()); } } }
3e1fc165d063e7c4266e4bd9b4d80bfbe1376bee
3,469
java
Java
dss-access-api/src/main/java/org/streamconnect/dss/access/service/IAccessService.java
Infosys/RealtimeStreams
2a7a8f75a86a84befff35c2a80756b2f3427f72a
[ "Apache-2.0" ]
9
2019-09-04T14:50:33.000Z
2020-12-24T06:49:10.000Z
dss-access-api/src/main/java/org/streamconnect/dss/access/service/IAccessService.java
boycode/RealtimeStreams
528c5f9d4d8a93d64c4838a46e303d97be672c95
[ "Apache-2.0" ]
1
2019-09-12T07:20:11.000Z
2019-09-28T17:41:09.000Z
dss-access-api/src/main/java/org/streamconnect/dss/access/service/IAccessService.java
Infosys/RealtimeStreams
2a7a8f75a86a84befff35c2a80756b2f3427f72a
[ "Apache-2.0" ]
8
2019-09-19T16:45:38.000Z
2021-09-13T06:35:31.000Z
25.137681
76
0.64889
13,415
/* * Copyright 2019 Infosys Ltd. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.streamconnect.dss.access.service; import org.streamconnect.dss.dto.FeatureDto; import org.streamconnect.dss.dto.IdNameDto; import org.streamconnect.dss.dto.PortalDto; import org.streamconnect.dss.dto.RoleDto; import org.streamconnect.dss.dto.UserDto; import java.util.List; /** * Service for listing managing user, role, access level adding, editing and * mapping. * @version 1.0 */ public interface IAccessService { /** * Method for getting the users. * * @return String */ List<IdNameDto> getUserList(); /** * Method for saving Role against users. * * @param roleDto the role dto * @return String */ boolean saveRole(RoleDto roleDto); /** * Method for deleting a role. * * @param inRoleId the in role id * @return String */ boolean deleteRole(int inRoleId); /** * Method for mapping a user to role. * * @param userDto the user dto * @return String */ boolean mapUserRole(UserDto userDto); /** * Method for getting the roles. * * @return List */ List<RoleDto> getRoleList(); /** * Method for getting roles corresponding to the user. * * @param username the username * @return Response */ UserDto getUserRoleDetails(String username); /** * Method for getting all roles corresponding to the user. * * @return Response */ List<UserDto> listUserRoleDetails(); /** * Method for removing the user role mapping. * * @param inUserId the in user id * @return Response */ boolean removeMappedUserRole(int inUserId); /** * Method for getting the features. * * @return List */ List<FeatureDto> getFeatureList(); /** * Method for mapping role and access levels. * * @param roleDto the role dto * @return String */ boolean mapRoleAccess(RoleDto roleDto); /** * Method for getting the access levels. * * @param inRoleId the in role id * @return String */ RoleDto getRoleAccessDetails(int inRoleId); /** * Method for getting portal dashboard visualize tree. * * @return portalDtoList */ List<PortalDto> getPortalDashboardCategoryKpiVisualizeTree(); /** * Check role exist or not. * * @param inRoleId the role id * @param roleName the role name * @param userName the user name * @return true, if successful */ boolean checkRoleExistOrNot(int inRoleId, String roleName, String userName); }
3e1fc1f8f4213700abc165613ef9313e148941d7
1,270
java
Java
core/src/main/java/io/zero88/qwe/HasConfig.java
zero88/blueprint
ee30dc3bbda7f8cfd91b00d7e9003ee16bee044b
[ "Apache-2.0" ]
3
2021-07-27T15:38:40.000Z
2022-02-16T04:09:13.000Z
core/src/main/java/io/zero88/qwe/HasConfig.java
zero88/blueprint
ee30dc3bbda7f8cfd91b00d7e9003ee16bee044b
[ "Apache-2.0" ]
34
2021-05-12T06:12:58.000Z
2022-03-31T04:10:39.000Z
core/src/main/java/io/zero88/qwe/HasConfig.java
zero88/qwe
ee30dc3bbda7f8cfd91b00d7e9003ee16bee044b
[ "Apache-2.0" ]
null
null
null
25.918367
117
0.607087
13,416
package io.zero88.qwe; import io.vertx.core.json.JsonObject; import io.zero88.qwe.utils.JsonUtils; import lombok.NonNull; /** * Mark a verticle has Config * * @param <C> type of {@code IConfig} * @see IConfig */ interface HasConfig<C extends IConfig> extends HasLogger { /** * Config class * * @return IConfig class */ @NonNull Class<C> configClass(); /** * Define a config file in classpath * * @return config file path */ @NonNull String configFile(); /** * Compute configure based on user input configuration and default unit configuration that defined in {@link * #configFile()} * * @param config given user configuration * @return config instance * @see IConfig */ default C computeConfig(JsonObject config) { logger().debug("Computing configuration [{}][{}]...", configClass().getName(), configFile()); C cfg = IConfig.merge(IConfig.from(JsonUtils.silentLoadJsonInClasspath(configFile()), configClass()), config, configClass()); if (logger().isDebugEnabled()) { logger().debug("Configuration [{}][{}]", getClass().getName(), cfg.toJson().encode()); } return cfg; } }
3e1fc235bc5e8d5ff809261245664b3892e27427
1,531
java
Java
spring-data-mybatis/src/main/java/org/springframework/data/mybatis/repository/query/MybatisStatementQuery.java
overcat/spring-data-mybatis
7a171e3f809865c5834936df0d12245704be29ac
[ "Apache-2.0" ]
41
2020-03-31T10:21:57.000Z
2022-02-14T11:55:06.000Z
spring-data-mybatis/src/main/java/org/springframework/data/mybatis/repository/query/MybatisStatementQuery.java
overcat/spring-data-mybatis
7a171e3f809865c5834936df0d12245704be29ac
[ "Apache-2.0" ]
61
2020-04-10T11:35:51.000Z
2022-01-21T23:10:08.000Z
spring-data-mybatis/src/main/java/org/springframework/data/mybatis/repository/query/MybatisStatementQuery.java
overcat/spring-data-mybatis
7a171e3f809865c5834936df0d12245704be29ac
[ "Apache-2.0" ]
10
2020-09-28T03:38:10.000Z
2021-12-12T14:18:11.000Z
29.442308
97
0.770085
13,417
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.mybatis.repository.query; import org.apache.ibatis.mapping.SqlCommandType; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.data.mybatis.repository.support.ResidentStatementName; /** * MyBatis statement query. * * @author JARVIS SONG * @since 2.0.0 */ public class MybatisStatementQuery extends AbstractMybatisQuery { public MybatisStatementQuery(SqlSessionTemplate sqlSessionTemplate, MybatisQueryMethod method) { super(sqlSessionTemplate, method); } @Override public SqlCommandType getSqlCommandType() { return null; } @Override public String getStatementName() { return this.method.getAnnotationValue("statement", this.method.getName()); } @Override public String getCountStatementName() { return this.method.getAnnotationValue("countStatement", ResidentStatementName.COUNT_PREFIX + this.getStatementName()); } }
3e1fc31ef6a424bb38679c795496648405fb4b5b
577
java
Java
library/src/main/java/com/echsylon/kraken/dto/DepositMethod.java
echsylon/kraken
36545294d18e1327d2fca5f19e47b30fe59d4500
[ "Apache-2.0" ]
3
2017-09-20T18:44:31.000Z
2018-04-08T18:05:58.000Z
library/src/main/java/com/echsylon/kraken/dto/DepositMethod.java
laszlourszuly/kraken
36545294d18e1327d2fca5f19e47b30fe59d4500
[ "Apache-2.0" ]
5
2017-08-15T09:17:52.000Z
2018-02-05T08:14:05.000Z
library/src/main/java/com/echsylon/kraken/dto/DepositMethod.java
laszlourszuly/kraken
36545294d18e1327d2fca5f19e47b30fe59d4500
[ "Apache-2.0" ]
1
2017-12-11T15:30:21.000Z
2017-12-11T15:30:21.000Z
20.607143
65
0.722704
13,418
package com.echsylon.kraken.dto; import com.google.gson.annotations.SerializedName; /** * For technical details on the API see the online documentation: * https://www.kraken.com/help/api */ @SuppressWarnings("WeakerAccess") public class DepositMethod { @SerializedName("method") public String method; @SerializedName("limit") public String limit; @SerializedName("fee") public String fee; @SerializedName("gen-address") public Boolean hasGeneratedAddress; @SerializedName("address-setup-fee") public String addressSetupFee; }
3e1fc37fa0ebd60cf3b447c594ee734fa72dd5e2
321
java
Java
walkthroughs/week-5-tdd/project/src/main/java/com/google/sps/TimeRangeComparator.java
angelinechen9/STEP
3099ef0eb59d0f337663ad9d8f230863959706c4
[ "Apache-2.0" ]
null
null
null
walkthroughs/week-5-tdd/project/src/main/java/com/google/sps/TimeRangeComparator.java
angelinechen9/STEP
3099ef0eb59d0f337663ad9d8f230863959706c4
[ "Apache-2.0" ]
null
null
null
walkthroughs/week-5-tdd/project/src/main/java/com/google/sps/TimeRangeComparator.java
angelinechen9/STEP
3099ef0eb59d0f337663ad9d8f230863959706c4
[ "Apache-2.0" ]
null
null
null
26.75
74
0.719626
13,419
package com.google.sps; import java.util.Comparator; /** * A comparator for sorting ranges by their start time in ascending order. */ public final class TimeRangeComparator implements Comparator<TimeRange> { public int compare(TimeRange a, TimeRange b) { return Long.compare(a.start(), b.start()); } }
3e1fc6fc9518110170c94634aa1047a02f148420
762
java
Java
Esercitazione 2/src/esercizio4/TestGarage.java
DaimCod/Stage
14f230909a5c7c8fe0bca40edbf007a585badde0
[ "MIT" ]
null
null
null
Esercitazione 2/src/esercizio4/TestGarage.java
DaimCod/Stage
14f230909a5c7c8fe0bca40edbf007a585badde0
[ "MIT" ]
null
null
null
Esercitazione 2/src/esercizio4/TestGarage.java
DaimCod/Stage
14f230909a5c7c8fe0bca40edbf007a585badde0
[ "MIT" ]
null
null
null
31.75
89
0.648294
13,420
package esercizio4; import esercizio3.*; public class TestGarage { public static void main(String[] args) { Vehicle[] veicolo = new Vehicle[5]; veicolo[0] = new Car("AA000AA", "Audi", "RS4", false, "Station wagon"); veicolo[1] = new Car("BB111BB", "Mercedes", "C-Class", true, "Sport"); veicolo[2] = new Car("CC222CC", "Opel", "Corsa", false, "Utilitaria"); veicolo[3] = new Motorcycle("DD444DD", "Harley-Davidson", "Street-glide", false, 1800); veicolo[4] = new Motorcycle("EE555EEE", "Husqvarna", "Norden 901", true, 50); Garage garage = new Garage(); for(int i=0; i < veicolo.length; i++) { System.out.println("Veicolo "+veicolo[i].getTarga()); System.out.println("Prezzo riparazione" + garage.repair(veicolo[i])); } } }
3e1fc75ffcb1de9b2b37cdd5d28a317d0f4001d2
1,166
java
Java
voms-admin-server/src/main/java/org/glite/security/voms/admin/event/user/aup/UserAUPSignatureRequestedEvent.java
italiangrid/voms-admin-server
26fdc5f9da0a4ace7a33e419ae852b5a9bff71fe
[ "Apache-2.0" ]
null
null
null
voms-admin-server/src/main/java/org/glite/security/voms/admin/event/user/aup/UserAUPSignatureRequestedEvent.java
italiangrid/voms-admin-server
26fdc5f9da0a4ace7a33e419ae852b5a9bff71fe
[ "Apache-2.0" ]
14
2015-03-10T09:35:20.000Z
2021-04-19T19:16:31.000Z
voms-admin-server/src/main/java/org/glite/security/voms/admin/event/user/aup/UserAUPSignatureRequestedEvent.java
italiangrid/voms-admin-server
26fdc5f9da0a4ace7a33e419ae852b5a9bff71fe
[ "Apache-2.0" ]
6
2015-01-19T17:34:06.000Z
2019-03-20T22:02:37.000Z
36.4375
78
0.755575
13,421
/** * Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2006-2016 * * 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.glite.security.voms.admin.event.user.aup; import org.glite.security.voms.admin.event.EventDescription; import org.glite.security.voms.admin.persistence.model.AUP; import org.glite.security.voms.admin.persistence.model.VOMSUser; @EventDescription(message = "requested a new AUP signature from user '%s %s'", params = { "userName", "userSurname" }) public class UserAUPSignatureRequestedEvent extends UserAUPEvent { public UserAUPSignatureRequestedEvent(VOMSUser user, AUP aup) { super(user, aup); } }
3e1fc7609e943856b7487c5524d3d4744978497e
480
java
Java
src/r/b3/interfaces/criptografia/Facade.java
HigorSnt/p2
d96ab96a73e59dae98230fff3759c8f13a3cb6c5
[ "MIT" ]
5
2019-06-03T23:02:53.000Z
2020-03-16T22:27:33.000Z
src/r/b3/interfaces/criptografia/Facade.java
HigorSnt/p2
d96ab96a73e59dae98230fff3759c8f13a3cb6c5
[ "MIT" ]
4
2019-05-29T16:08:06.000Z
2019-06-12T17:53:09.000Z
src/r/b3/interfaces/criptografia/Facade.java
HigorSnt/p2
d96ab96a73e59dae98230fff3759c8f13a3cb6c5
[ "MIT" ]
24
2017-11-10T00:08:50.000Z
2019-11-18T10:03:06.000Z
17.777778
51
0.720833
13,422
package r.b3.interfaces.criptografia; import java.util.List; // INUTILLLLLLLLLLLLLLLLLLLLLLLLL public class Facade { private UsuarioController uc; public Facade() { this.uc = new UsuarioController(); } public String criptografar(int id, String texto) { return this.uc.criptografar(id, texto); } public void configurar(int id, String alg) { this.uc.configurar(id, alg); } public List<String> listarTextos(int id) { return this.uc.listarTextos(id); } }
3e1fc7a033aea66b792375a51085fb53b5d441e5
2,153
java
Java
server/apps/cassandra-app/src/test/java/org/apache/james/DockerElasticSearchRule.java
sergeByishimo/james-project
e7e2c912d9ca59c6f4cc6c8b75ce4994038c08f7
[ "Apache-2.0" ]
634
2015-12-21T20:24:06.000Z
2022-03-24T09:57:48.000Z
server/apps/cassandra-app/src/test/java/org/apache/james/DockerElasticSearchRule.java
sergeByishimo/james-project
e7e2c912d9ca59c6f4cc6c8b75ce4994038c08f7
[ "Apache-2.0" ]
4,148
2015-09-14T15:59:06.000Z
2022-03-31T10:29:10.000Z
server/apps/cassandra-app/src/test/java/org/apache/james/DockerElasticSearchRule.java
sergeByishimo/james-project
e7e2c912d9ca59c6f4cc6c8b75ce4994038c08f7
[ "Apache-2.0" ]
392
2015-07-16T07:04:59.000Z
2022-03-28T09:37:53.000Z
37.12069
92
0.613098
13,423
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james; import org.apache.james.backends.es.v7.DockerElasticSearch; import org.apache.james.backends.es.v7.DockerElasticSearchSingleton; import org.apache.james.modules.TestDockerElasticSearchModule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import com.google.inject.Module; public class DockerElasticSearchRule implements GuiceModuleTestRule { private final DockerElasticSearch elasticSearch = DockerElasticSearchSingleton.INSTANCE; @Override public Statement apply(Statement base, Description description) { return base; } @Override public void await() { elasticSearch.flushIndices(); } @Override public Module getModule() { return new TestDockerElasticSearchModule(elasticSearch); } public DockerElasticSearch getDockerEs() { return elasticSearch; } public void start() { elasticSearch.start(); } }
3e1fc7fc8713a668bba187f6a7d948e30c0eb183
17,300
java
Java
buildSrc/src/main/java/com/debughelper/tools/r8/ir/optimize/PeepholeOptimizer.java
howardpang/androiddebughelper
becf780a81ea0f7f0c00510075700c6b04eb9fef
[ "Apache-2.0", "BSD-3-Clause" ]
11
2019-05-07T11:11:34.000Z
2021-01-21T10:28:40.000Z
buildSrc/src/main/java/com/debughelper/tools/r8/ir/optimize/PeepholeOptimizer.java
howardpang/androiddebughelper
becf780a81ea0f7f0c00510075700c6b04eb9fef
[ "Apache-2.0", "BSD-3-Clause" ]
3
2019-05-09T03:44:00.000Z
2019-08-20T02:58:54.000Z
buildSrc/src/main/java/com/debughelper/tools/r8/ir/optimize/PeepholeOptimizer.java
howardpang/androiddebughelper
becf780a81ea0f7f0c00510075700c6b04eb9fef
[ "Apache-2.0", "BSD-3-Clause" ]
3
2019-05-13T09:32:08.000Z
2020-04-16T00:16:02.000Z
51.488095
181
0.682023
13,424
// Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.debughelper.tools.r8.ir.optimize; import com.debughelper.tools.r8.graph.DebugLocalInfo; import com.debughelper.tools.r8.ir.code.BasicBlock; import com.debughelper.tools.r8.ir.code.ConstNumber; import com.debughelper.tools.r8.ir.code.DebugLocalsChange; import com.debughelper.tools.r8.ir.code.Goto; import com.debughelper.tools.r8.ir.code.IRCode; import com.debughelper.tools.r8.ir.code.Instruction; import com.debughelper.tools.r8.ir.code.InstructionListIterator; import com.debughelper.tools.r8.ir.code.Value; import com.debughelper.tools.r8.ir.regalloc.LinearScanRegisterAllocator; import com.debughelper.tools.r8.ir.regalloc.LiveIntervals; import com.debughelper.tools.r8.ir.regalloc.RegisterAllocator; import com.google.common.base.Equivalence.Wrapper; import com.google.common.collect.ImmutableList; import it.unimi.dsi.fastutil.ints.Int2ReferenceMap; import it.unimi.dsi.fastutil.ints.Int2ReferenceMap.Entry; import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; public class PeepholeOptimizer { /** * Perform optimizations of the code with register assignments provided by the register allocator. */ public static void optimize(com.debughelper.tools.r8.ir.code.IRCode code, com.debughelper.tools.r8.ir.regalloc.LinearScanRegisterAllocator allocator) { removeIdenticalPredecessorBlocks(code, allocator); removeRedundantInstructions(code, allocator); shareIdenticalBlockSuffix(code, allocator); assert code.isConsistentGraph(); } /** * Identify common suffixes in predecessor blocks and share them. */ private static void shareIdenticalBlockSuffix(com.debughelper.tools.r8.ir.code.IRCode code, com.debughelper.tools.r8.ir.regalloc.RegisterAllocator allocator) { Collection<com.debughelper.tools.r8.ir.code.BasicBlock> blocks = code.blocks; com.debughelper.tools.r8.ir.code.BasicBlock normalExit = null; ImmutableList<com.debughelper.tools.r8.ir.code.BasicBlock> normalExits = code.computeNormalExitBlocks(); if (normalExits.size() > 1) { normalExit = new com.debughelper.tools.r8.ir.code.BasicBlock(); normalExit.getPredecessors().addAll(normalExits); blocks = new ArrayList<>(code.blocks); blocks.add(normalExit); } do { int startNumberOfNewBlock = code.getHighestBlockNumber() + 1; Map<com.debughelper.tools.r8.ir.code.BasicBlock, com.debughelper.tools.r8.ir.code.BasicBlock> newBlocks = new IdentityHashMap<>(); for (com.debughelper.tools.r8.ir.code.BasicBlock block : blocks) { InstructionEquivalence equivalence = new InstructionEquivalence(allocator); // Group interesting predecessor blocks by their last instruction. Map<Wrapper<com.debughelper.tools.r8.ir.code.Instruction>, List<com.debughelper.tools.r8.ir.code.BasicBlock>> lastInstructionToBlocks = new HashMap<>(); for (com.debughelper.tools.r8.ir.code.BasicBlock pred : block.getPredecessors()) { // Only deal with predecessors with one successor. This way we can move throwing // instructions as well since there are no handlers (or the handler is the same as the // normal control-flow block). Alternatively, we could move only non-throwing instructions // and allow both a goto edge and exception edges when the target does not start with a // MoveException instruction. However, that would require us to require rewriting of // catch handlers as well. if (pred.exit().isGoto() && pred.getSuccessors().size() == 1 && pred.getInstructions().size() > 1) { List<com.debughelper.tools.r8.ir.code.Instruction> instructions = pred.getInstructions(); com.debughelper.tools.r8.ir.code.Instruction lastInstruction = instructions.get(instructions.size() - 2); List<com.debughelper.tools.r8.ir.code.BasicBlock> value = lastInstructionToBlocks.computeIfAbsent( equivalence.wrap(lastInstruction), (k) -> new ArrayList<>()); value.add(pred); } else if (pred.exit().isReturn() && pred.getSuccessors().isEmpty() && pred.getInstructions().size() > 2) { com.debughelper.tools.r8.ir.code.Instruction lastInstruction = pred.exit(); List<com.debughelper.tools.r8.ir.code.BasicBlock> value = lastInstructionToBlocks.computeIfAbsent( equivalence.wrap(lastInstruction), (k) -> new ArrayList<>()); value.add(pred); } } // For each group of predecessors of size 2 or more, find the largest common suffix and // move that to a separate block. for (List<com.debughelper.tools.r8.ir.code.BasicBlock> predsWithSameLastInstruction : lastInstructionToBlocks.values()) { if (predsWithSameLastInstruction.size() < 2) { continue; } com.debughelper.tools.r8.ir.code.BasicBlock firstPred = predsWithSameLastInstruction.get(0); int commonSuffixSize = firstPred.getInstructions().size(); for (int i = 1; i < predsWithSameLastInstruction.size(); i++) { com.debughelper.tools.r8.ir.code.BasicBlock pred = predsWithSameLastInstruction.get(i); assert pred.exit().isGoto() || pred.exit().isReturn(); commonSuffixSize = Math.min(commonSuffixSize, sharedSuffixSize(firstPred, pred, allocator)); } // Don't share a suffix that is just a single goto or return instruction. if (commonSuffixSize <= 1) { continue; } int blockNumber = startNumberOfNewBlock + newBlocks.size(); com.debughelper.tools.r8.ir.code.BasicBlock newBlock = createAndInsertBlockForSuffix( blockNumber, commonSuffixSize, predsWithSameLastInstruction, block == normalExit ? null : block); newBlocks.put(predsWithSameLastInstruction.get(0), newBlock); } } ListIterator<com.debughelper.tools.r8.ir.code.BasicBlock> blockIterator = code.listIterator(); while (blockIterator.hasNext()) { com.debughelper.tools.r8.ir.code.BasicBlock block = blockIterator.next(); if (newBlocks.containsKey(block)) { blockIterator.add(newBlocks.get(block)); } } // Go through all the newly introduced blocks to find more common suffixes to share. blocks = newBlocks.values(); } while (!blocks.isEmpty()); } private static com.debughelper.tools.r8.ir.code.BasicBlock createAndInsertBlockForSuffix( int blockNumber, int suffixSize, List<com.debughelper.tools.r8.ir.code.BasicBlock> preds, com.debughelper.tools.r8.ir.code.BasicBlock successorBlock) { com.debughelper.tools.r8.ir.code.BasicBlock newBlock = com.debughelper.tools.r8.ir.code.BasicBlock.createGotoBlock(blockNumber); com.debughelper.tools.r8.ir.code.BasicBlock first = preds.get(0); assert (successorBlock != null && first.exit().isGoto()) || (successorBlock == null && first.exit().isReturn()); int offsetFromEnd = successorBlock == null ? 0 : 1; if (successorBlock == null) { newBlock.getInstructions().removeLast(); } com.debughelper.tools.r8.ir.code.InstructionListIterator from = first.listIterator(first.getInstructions().size() - offsetFromEnd); Int2ReferenceMap<com.debughelper.tools.r8.graph.DebugLocalInfo> newBlockEntryLocals = (successorBlock == null || successorBlock.getLocalsAtEntry() == null) ? new Int2ReferenceOpenHashMap<>() : new Int2ReferenceOpenHashMap<>(successorBlock.getLocalsAtEntry()); boolean movedThrowingInstruction = false; for (int i = offsetFromEnd; i < suffixSize; i++) { com.debughelper.tools.r8.ir.code.Instruction instruction = from.previous(); movedThrowingInstruction = movedThrowingInstruction || instruction.instructionTypeCanThrow(); newBlock.getInstructions().addFirst(instruction); instruction.setBlock(newBlock); if (instruction.isDebugLocalsChange()) { // Replay the debug local changes backwards to compute the entry state. DebugLocalsChange change = instruction.asDebugLocalsChange(); for (int starting : change.getStarting().keySet()) { newBlockEntryLocals.remove(starting); } for (Entry<DebugLocalInfo> ending : change.getEnding().int2ReferenceEntrySet()) { newBlockEntryLocals.put(ending.getIntKey(), ending.getValue()); } } } if (movedThrowingInstruction && first.hasCatchHandlers()) { newBlock.transferCatchHandlers(first); } for (com.debughelper.tools.r8.ir.code.BasicBlock pred : preds) { LinkedList<com.debughelper.tools.r8.ir.code.Instruction> instructions = pred.getInstructions(); for (int i = 0; i < suffixSize; i++) { instructions.removeLast(); } com.debughelper.tools.r8.ir.code.Goto jump = new com.debughelper.tools.r8.ir.code.Goto(); jump.setBlock(pred); instructions.add(jump); newBlock.getPredecessors().add(pred); if (successorBlock != null) { pred.replaceSuccessor(successorBlock, newBlock); successorBlock.getPredecessors().remove(pred); } else { pred.getSuccessors().add(newBlock); } if (movedThrowingInstruction) { pred.clearCatchHandlers(); } } newBlock.setLocalsAtEntry(newBlockEntryLocals); if (successorBlock != null) { newBlock.link(successorBlock); } return newBlock; } private static int sharedSuffixSize( com.debughelper.tools.r8.ir.code.BasicBlock block0, com.debughelper.tools.r8.ir.code.BasicBlock block1, com.debughelper.tools.r8.ir.regalloc.RegisterAllocator allocator) { assert block0.exit().isGoto() || block0.exit().isReturn(); com.debughelper.tools.r8.ir.code.InstructionListIterator it0 = block0.listIterator(block0.getInstructions().size()); InstructionListIterator it1 = block1.listIterator(block1.getInstructions().size()); int suffixSize = 0; while (it0.hasPrevious() && it1.hasPrevious()) { com.debughelper.tools.r8.ir.code.Instruction i0 = it0.previous(); com.debughelper.tools.r8.ir.code.Instruction i1 = it1.previous(); if (!i0.identicalAfterRegisterAllocation(i1, allocator)) { return suffixSize; } suffixSize++; } return suffixSize; } /** * If two predecessors have the same code and successors. Replace one of them with an * empty block with a goto to the other. */ private static void removeIdenticalPredecessorBlocks(com.debughelper.tools.r8.ir.code.IRCode code, RegisterAllocator allocator) { BasicBlockInstructionsEquivalence equivalence = new BasicBlockInstructionsEquivalence(code, allocator); // Locate one block at a time that has identical predecessors. Rewrite those predecessors and // then start over. Restarting when one blocks predecessors have been rewritten simplifies // the rewriting and reduces the size of the data structures. boolean changed; do { changed = false; for (com.debughelper.tools.r8.ir.code.BasicBlock block : code.blocks) { Map<Wrapper<com.debughelper.tools.r8.ir.code.BasicBlock>, Integer> blockToIndex = new HashMap<>(); for (int predIndex = 0; predIndex < block.getPredecessors().size(); predIndex++) { com.debughelper.tools.r8.ir.code.BasicBlock pred = block.getPredecessors().get(predIndex); if (pred.getInstructions().size() == 1) { continue; } Wrapper<com.debughelper.tools.r8.ir.code.BasicBlock> wrapper = equivalence.wrap(pred); if (blockToIndex.containsKey(wrapper)) { changed = true; int otherPredIndex = blockToIndex.get(wrapper); com.debughelper.tools.r8.ir.code.BasicBlock otherPred = block.getPredecessors().get(otherPredIndex); pred.clearCatchHandlers(); pred.getInstructions().clear(); equivalence.clearComputedHash(pred); for (com.debughelper.tools.r8.ir.code.BasicBlock succ : pred.getSuccessors()) { succ.removePredecessor(pred); } pred.getSuccessors().clear(); pred.getSuccessors().add(otherPred); assert !otherPred.getPredecessors().contains(pred); otherPred.getPredecessors().add(pred); com.debughelper.tools.r8.ir.code.Goto exit = new Goto(); exit.setBlock(pred); pred.getInstructions().add(exit); } else { blockToIndex.put(wrapper, predIndex); } } } } while (changed); } /** * Remove redundant instructions from the code. * * <p>Currently removes move instructions with the same src and target register and const * instructions where the constant is known to be in the register already. * * @param code the code from which to remove redundant instruction * @param allocator the register allocator providing registers for values */ private static void removeRedundantInstructions( IRCode code, LinearScanRegisterAllocator allocator) { for (BasicBlock block : code.blocks) { // Mapping from register number to const number instructions for this basic block. // Used to remove redundant const instructions that reloads the same constant into // the same register. Map<Integer, com.debughelper.tools.r8.ir.code.ConstNumber> registerToNumber = new HashMap<>(); MoveEliminator moveEliminator = new MoveEliminator(allocator); ListIterator<com.debughelper.tools.r8.ir.code.Instruction> iterator = block.getInstructions().listIterator(); while (iterator.hasNext()) { Instruction current = iterator.next(); if (moveEliminator.shouldBeEliminated(current)) { iterator.remove(); } else if (current.outValue() != null && current.outValue().needsRegister()) { Value outValue = current.outValue(); int instructionNumber = current.getNumber(); if (outValue.isConstant() && current.isConstNumber()) { if (constantSpilledAtDefinition(current.asConstNumber())) { // Remove constant instructions that are spilled at their definition and are // therefore unused. iterator.remove(); continue; } int outRegister = allocator.getRegisterForValue(outValue, instructionNumber); com.debughelper.tools.r8.ir.code.ConstNumber numberInRegister = registerToNumber.get(outRegister); if (numberInRegister != null && numberInRegister.identicalNonValueNonPositionParts(current)) { // This instruction is not needed, the same constant is already in this register. // We don't consider the positions of the two (non-throwing) instructions. iterator.remove(); } else { // Insert the current constant in the mapping. Make sure to clobber the second // register if wide and register-1 if that defines a wide value. registerToNumber.put(outRegister, current.asConstNumber()); if (current.outType().isWide()) { registerToNumber.remove(outRegister + 1); } else { removeWideConstantCovering(registerToNumber, outRegister); } } } else { // This instruction writes registers with a non-constant value. Remove the registers // from the mapping. int outRegister = allocator.getRegisterForValue(outValue, instructionNumber); for (int i = 0; i < outValue.requiredRegisters(); i++) { registerToNumber.remove(outRegister + i); } // Check if the first register written is the second part of a wide value. If so // the wide value is no longer active. removeWideConstantCovering(registerToNumber, outRegister); } } } } } private static void removeWideConstantCovering( Map<Integer, com.debughelper.tools.r8.ir.code.ConstNumber> registerToNumber, int register) { com.debughelper.tools.r8.ir.code.ConstNumber number = registerToNumber.get(register - 1); if (number != null && number.outType().isWide()) { registerToNumber.remove(register - 1); } } private static boolean constantSpilledAtDefinition(ConstNumber constNumber) { if (constNumber.outValue().isFixedRegisterValue()) { return false; } LiveIntervals definitionIntervals = constNumber.outValue().getLiveIntervals().getSplitCovering(constNumber.getNumber()); return definitionIntervals.isSpilledAndRematerializable(); } }
3e1fc86b754b6f8e9c6255ffa5bf2611717d6366
2,844
java
Java
src/main/java/com/thinkgem/jeesite/modules/sys/web/gbj/GbjTagController.java
GSSBuse/GSSB
68220191e87dc103df37faeaa02c140c716e6528
[ "Apache-2.0" ]
5
2017-10-25T00:10:12.000Z
2017-12-23T15:24:31.000Z
src/main/java/com/thinkgem/jeesite/modules/sys/web/gbj/GbjTagController.java
GSSBuse/GSSB
68220191e87dc103df37faeaa02c140c716e6528
[ "Apache-2.0" ]
null
null
null
src/main/java/com/thinkgem/jeesite/modules/sys/web/gbj/GbjTagController.java
GSSBuse/GSSB
68220191e87dc103df37faeaa02c140c716e6528
[ "Apache-2.0" ]
2
2017-10-26T02:12:07.000Z
2017-11-20T06:19:33.000Z
34.26506
108
0.772152
13,425
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.sys.web.gbj; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.thinkgem.jeesite.common.config.Global; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.web.BaseController; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.modules.sys.entity.gbj.GbjTag; import com.thinkgem.jeesite.modules.sys.service.gbj.GbjTagService; /** * 标签类型Controller * @author snnu * @version 2018-01-08 */ @Controller @RequestMapping(value = "${adminPath}/sys/gbj/gbjTag") public class GbjTagController extends BaseController { @Autowired private GbjTagService gbjTagService; @ModelAttribute public GbjTag get(@RequestParam(required=false) String id) { GbjTag entity = null; if (StringUtils.isNotBlank(id)){ entity = gbjTagService.get(id); } if (entity == null){ entity = new GbjTag(); } return entity; } @RequiresPermissions("sys:gbj:gbjTag:view") @RequestMapping(value = {"list", ""}) public String list(GbjTag gbjTag, HttpServletRequest request, HttpServletResponse response, Model model) { Page<GbjTag> page = gbjTagService.findPage(new Page<GbjTag>(request, response), gbjTag); model.addAttribute("page", page); return "modules/sys/gbj/gbjTagList"; } @RequiresPermissions("sys:gbj:gbjTag:view") @RequestMapping(value = "form") public String form(GbjTag gbjTag, Model model) { model.addAttribute("gbjTag", gbjTag); return "modules/sys/gbj/gbjTagForm"; } @RequiresPermissions("sys:gbj:gbjTag:edit") @RequestMapping(value = "save") public String save(GbjTag gbjTag, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, gbjTag)){ return form(gbjTag, model); } gbjTagService.save(gbjTag); addMessage(redirectAttributes, "保存标签类型列表成功"); return "redirect:"+Global.getAdminPath()+"/sys/gbj/gbjTag/?repage"; } @RequiresPermissions("sys:gbj:gbjTag:edit") @RequestMapping(value = "delete") public String delete(GbjTag gbjTag, RedirectAttributes redirectAttributes) { gbjTagService.delete(gbjTag); addMessage(redirectAttributes, "删除标签类型列表成功"); return "redirect:"+Global.getAdminPath()+"/sys/gbj/gbjTag/?repage"; } }
3e1fc9841062fe2b33b816eb138216c35e50bc9b
1,074
java
Java
src/main/java/com/codeosseum/miles/faultseeding/task/Task.java
codeosseum/miles
35db98e11afa6968b0438bd4eba7df45bb693ce1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/codeosseum/miles/faultseeding/task/Task.java
codeosseum/miles
35db98e11afa6968b0438bd4eba7df45bb693ce1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/codeosseum/miles/faultseeding/task/Task.java
codeosseum/miles
35db98e11afa6968b0438bd4eba7df45bb693ce1
[ "Apache-2.0" ]
null
null
null
27.538462
95
0.773743
13,426
package com.codeosseum.miles.faultseeding.task; import com.codeosseum.miles.faultseeding.challenge.stored.Solution; import lombok.Builder; import lombok.Value; import static com.codeosseum.miles.faultseeding.challenge.stored.Solution.CHALLENGE_NAME_INDEX; import static com.codeosseum.miles.faultseeding.challenge.stored.Solution.HASH_INDEX; import static com.codeosseum.miles.faultseeding.challenge.stored.Solution.ID_SEPARATOR; import static com.codeosseum.miles.faultseeding.challenge.stored.Solution.MODE_INDEX; @Value @Builder public class Task { private final String id; private final int difficulty; private final String title; private final String description; private final String evaluatorEntrypoint; private final String solutionEntrypoint; public String getModeId() { return id.split(ID_SEPARATOR)[MODE_INDEX]; } public String getTaskName() { return id.split(ID_SEPARATOR)[CHALLENGE_NAME_INDEX]; } public String getSolutionHash() { return id.split(ID_SEPARATOR)[HASH_INDEX]; } }
3e1fc9d7c5a5cf536d2f0a86a204d8a2a8dc3d1b
17,958
java
Java
server/aem/bundle/src/main/java/com/alexanderberndt/appintegration/aem/engine/AemExternalResourceCache.java
alberndt/aem-app-integration
23ef63835ca3616bff1419f9b39c18f9fbf929fa
[ "Apache-2.0" ]
4
2018-09-12T08:50:17.000Z
2022-01-03T09:08:48.000Z
server/aem/bundle/src/main/java/com/alexanderberndt/appintegration/aem/engine/AemExternalResourceCache.java
alberndt/aem-app-integration
23ef63835ca3616bff1419f9b39c18f9fbf929fa
[ "Apache-2.0" ]
29
2020-10-13T09:28:01.000Z
2022-03-29T03:54:00.000Z
server/aem/bundle/src/main/java/com/alexanderberndt/appintegration/aem/engine/AemExternalResourceCache.java
alberndt/aem-app-integration
23ef63835ca3616bff1419f9b39c18f9fbf929fa
[ "Apache-2.0" ]
2
2018-10-01T12:42:27.000Z
2020-09-30T14:38:54.000Z
40.355056
141
0.641608
13,427
package com.alexanderberndt.appintegration.aem.engine; import com.alexanderberndt.appintegration.engine.cache.AbstractExternalResourceCache; import com.alexanderberndt.appintegration.engine.resources.ExternalResource; import com.alexanderberndt.appintegration.engine.resources.ExternalResourceFactory; import com.alexanderberndt.appintegration.engine.resources.ExternalResourceType; import com.alexanderberndt.appintegration.exceptions.AppIntegrationException; import com.alexanderberndt.appintegration.utils.DataMap; import com.day.cq.commons.jcr.JcrUtil; import org.apache.commons.lang3.StringUtils; import org.apache.sling.api.resource.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.InputStream; import java.lang.invoke.MethodHandles; import java.net.URI; import java.util.*; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.apache.jackrabbit.JcrConstants.*; public class AemExternalResourceCache extends AbstractExternalResourceCache<AemExternalResourceCache.CacheEntry> { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); public static final String CACHE_ROOT = "/var/aem-app-integration/%s/files"; public static final int MILLIS_UNTIL_LOCKS_EXPIRE = 5 * 60 * 1000; // 5 minutes to expire public static final String LOCK_ATTR = "lock"; public static final String LOCKED_SINCE_ATTR = "lockedSince"; public static final String VERSION_ATTR = "version"; public static final String URI_ATTR = "uri"; public static final String TYPE_ATTR = "TYPE"; public static final String JCR_PATH_SEPARATOR = "/"; @Nonnull private final ResourceResolver resolver; // root-path, e.g. /var/app-integration/<my-app>/files @Nonnull private final String rootPath; private final Random random = new Random(); @Nullable private String versionId; public AemExternalResourceCache(@Nonnull ResourceResolver resolver, @Nonnull String applicationId) { this.resolver = resolver; this.rootPath = String.format(CACHE_ROOT, applicationId); } @Override public boolean isLongRunningWrite() { return (this.versionId != null); } @Override public void startLongRunningWrite(@Nullable String nameHint) { this.versionId = null; final String tempVersionId = StringUtils.defaultIfBlank(nameHint, Long.toHexString((long) Math.floor(Math.random() * 0x100000000L))); runAsTransactionOnRootResValueMap("start long running write", valueMap -> { if (canBeLocked(valueMap)) { valueMap.put(LOCK_ATTR, tempVersionId); valueMap.put(LOCKED_SINCE_ATTR, Calendar.getInstance()); } else { throw new AppIntegrationException("Cannot lock cache at " + rootPath); } }); this.versionId = tempVersionId; } @Override public void commitLongRunningWrite() { if (this.versionId == null) throw new AppIntegrationException("Cannot commit, as no transaction is currently running!"); runAsTransactionOnRootResValueMap("commit", valueMap -> { if (this.versionId.equals(valueMap.get(LOCK_ATTR, String.class))) { valueMap.put(VERSION_ATTR, versionId); valueMap.remove(LOCK_ATTR); valueMap.remove(LOCKED_SINCE_ATTR); } else { throw new AppIntegrationException("Cannot commit, as currently a different transaction is running!"); } }); } @Override public void rollbackLongRunningWrite() { if (this.versionId == null) throw new AppIntegrationException("Cannot rollback, as no transaction is currently running!"); runAsTransactionOnRootResValueMap("rollback", valueMap -> { final String curLock = valueMap.get(LOCK_ATTR, String.class); if (this.versionId.equals(curLock)) { valueMap.remove(LOCK_ATTR); valueMap.remove(LOCKED_SINCE_ATTR); } else { throw new AppIntegrationException("Cannot rollback, as currently a different transaction is running!"); } }); } private boolean canBeLocked(ValueMap valueMap) { final String currentLockId = valueMap.get(LOCK_ATTR, String.class); // is resource not locked yet? if (StringUtils.isBlank(currentLockId)) { return true; } // is resource locked by ourselves if (StringUtils.equals(this.versionId, currentLockId)) { return true; } // is lock expired? final Calendar now = Calendar.getInstance(); final Calendar lockedSince = valueMap.get(LOCKED_SINCE_ATTR, Calendar.class); if (lockedSince != null) { final long diff = now.getTimeInMillis() - lockedSince.getTimeInMillis(); return diff >= MILLIS_UNTIL_LOCKS_EXPIRE; } else { return true; } } @Override protected CacheEntry createNewCacheEntry(ExternalResource resource) { final CachePath cachePath = new CachePath(resource.getUri()); try { this.resolver.refresh(); final Resource cachePathRes = getOrCreateResource(cachePath.getPath()); final String hashCode = Integer.toHexString(resource.getUri().toString().hashCode()); // find new cache-entry name String entryName; int i = 0; do { if (i++ > 20) { throw new AppIntegrationException("Could NOT create a unique file entry for " + cachePathRes.getPath()); } entryName = hashCode + "_" + Integer.toHexString(random.nextInt(0x1000)); } while (cachePathRes.getChild(entryName) != null); final Resource cacheEntryRes = Objects.requireNonNull(resolver.create(cachePathRes, entryName, null)); final ModifiableValueMap modifiableValueMap = Objects.requireNonNull(cacheEntryRes.adaptTo(ModifiableValueMap.class)); modifiableValueMap.put(URI_ATTR, resource.getUri().toString()); return new CacheEntry(cachePath, cacheEntryRes); } catch (PersistenceException e) { throw new AppIntegrationException("Cannot create new cache-entry " + cachePath + "!", e); } } @Override protected CacheEntry getCacheEntry(URI uri) { final Resource rootRes = resolver.getResource(rootPath); if (rootRes == null) { return null; } final String curVersion = StringUtils.trimToNull(rootRes.getValueMap().get(VERSION_ATTR, String.class)); // find existing entry final CachePath cachePath = new CachePath(uri); final Resource cachePathRes = resolver.getResource(cachePath.getPath()); if (cachePathRes == null) { return null; } // iterate over all entry CacheEntry readThroughEntry = null; final Iterator<Resource> cacheResIter = cachePathRes.listChildren(); while (cacheResIter.hasNext()) { final Resource curCacheEntryRes = cacheResIter.next(); final ValueMap valueMap = curCacheEntryRes.getValueMap(); if (StringUtils.equals(uri.toString(), valueMap.get(URI_ATTR, String.class))) { final String curCacheEntryVersion = valueMap.get(VERSION_ATTR, String.class); if (StringUtils.equals(curVersion, curCacheEntryVersion)) { return new CacheEntry(cachePath, curCacheEntryRes); } if (curCacheEntryVersion == null) { readThroughEntry = new CacheEntry(cachePath, curCacheEntryRes); } } } // if nothing with the correct version was found, then return any found read-through entry (without version) return readThroughEntry; } @Override protected void addToCurrentLongRunningWrite(CacheEntry cacheEntry) { if (StringUtils.isNotBlank(versionId)) { final ModifiableValueMap modifiableValueMap = cacheEntry.getCacheEntryValueMap(); final List<String> versions = Optional.ofNullable(modifiableValueMap.get(VERSION_ATTR, String[].class)) .map(Arrays::asList) .map(ArrayList::new) .map(list -> { list.add(versionId); return (List<String>) list; }) .orElseGet(() -> Collections.singletonList(versionId)); modifiableValueMap.put(VERSION_ATTR, versions.toArray(new String[0])); } } @Override protected Supplier<InputStream> writeContent(CacheEntry cacheEntry, InputStream contentAsInputStream, String mimeType) { try { final Resource contentRes = resolver.create( cacheEntry.getCacheEntryRes(), cacheEntry.getCachePath().getFilename(), Collections.singletonMap(JCR_PRIMARYTYPE, NT_FILE)); Map<String, Object> propertiesMap = new HashMap<>(); propertiesMap.put(JCR_PRIMARYTYPE, NT_RESOURCE); propertiesMap.put(JCR_MIMETYPE, mimeType); propertiesMap.put(JCR_DATA, contentAsInputStream); resolver.create(contentRes, JCR_CONTENT, propertiesMap); // ToDo: Re-check the panic commits. This should follow a real plan (check, that input stream is already processed) //resolver.commit(); return () -> contentRes.adaptTo(InputStream.class); } catch (PersistenceException e) { throw new AppIntegrationException("Cannot write content to " + cacheEntry.getCachePath().getPath(), e); } } @Override protected void writeMetadata(CacheEntry cacheEntry, DataMap metadataMap) { try { final String nodeName = cacheEntry.getCachePath().getMetadataName(); Resource metadataRes = cacheEntry.getCacheEntryRes().getChild(nodeName); if (metadataRes == null) metadataRes = resolver.create(cacheEntry.getCacheEntryRes(), nodeName, null); final ModifiableValueMap valueMap = Objects.requireNonNull(metadataRes.adaptTo(ModifiableValueMap.class)); Set<String> keySet = valueMap.keySet().stream() .filter(key -> !StringUtils.startsWithAny(key, "jcr:", "cq:")) .collect(Collectors.toSet()); keySet.forEach(valueMap::remove); metadataMap.entrySet().stream() .filter(entry -> !entry.getKey().startsWith("jcr:")) .filter(entry -> !entry.getKey().startsWith("cq:")) .filter(entry -> (entry.getValue() instanceof String) || (entry.getValue() instanceof Number)) .forEach(entry -> valueMap.put(entry.getKey(), entry.getValue())); } catch (PersistenceException e) { throw new AppIntegrationException("Cannot write content to " + cacheEntry.getCachePath().getPath(), e); } } @Override protected void commitCacheEntry(CacheEntry cacheEntry) { if (StringUtils.isNotBlank(versionId)) { final Resource rootRes = resolver.getResource(rootPath); if (rootRes != null) { final ModifiableValueMap valueMap = Objects.requireNonNull(rootRes.adaptTo(ModifiableValueMap.class)); final String repositoryLock = valueMap.get(LOCK_ATTR, String.class); if (versionId.equals(repositoryLock)) { valueMap.put(LOCKED_SINCE_ATTR, Calendar.getInstance()); } else { throw new AppIntegrationException("Cannot write cache, as it is locked by different long-running processes!" + " (was: " + repositoryLock + ", expected: " + versionId + ")"); } } else { LOG.warn("Cannot refresh lock on {}, because path not found!", rootPath); } } try { resolver.commit(); } catch (PersistenceException e) { throw new AppIntegrationException("Cannot commit cache entry " + cacheEntry.getCachePath().getPath(), e); } } @Override @Nullable public ExternalResource getCachedResource(@Nonnull URI uri, @Nonnull ExternalResourceFactory resourceFactory) { final CacheEntry cacheEntry = getCacheEntry(uri); if (cacheEntry != null) { final Resource cacheEntryRes = cacheEntry.getCacheEntryRes(); final ValueMap cacheEntryValueMap = cacheEntryRes.getValueMap(); final ExternalResourceType type = ExternalResourceType.parse(cacheEntryValueMap.get(TYPE_ATTR, String.class)); final Resource contentRes = Objects.requireNonNull(cacheEntryRes.getChild(cacheEntry.getCachePath().getFilename())); final InputStream content = Objects.requireNonNull(contentRes.adaptTo(InputStream.class)); final Resource metadataRes = Objects.requireNonNull(cacheEntryRes.getChild(cacheEntry.getCachePath().getMetadataName())); final ValueMap metadataValueMap = metadataRes.getValueMap(); final DataMap metadataMap = new DataMap(); metadataValueMap.entrySet().stream() .filter(entry -> !StringUtils.startsWith(entry.getKey(), "jcr:")) .filter(entry -> !StringUtils.startsWith(entry.getKey(), "cq:")) .forEach(entry -> metadataMap.setData(entry.getKey(), entry.getValue())); return resourceFactory.createExternalResource(uri, type, content, metadataMap); } else { return null; } } private void runAsTransactionOnRootResValueMap(@Nonnull String methodName, Consumer<ModifiableValueMap> consumer) { try { resolver.refresh(); final Resource rootRes = getOrCreateResource(rootPath); final ModifiableValueMap modifiableValueMap = Objects.requireNonNull(rootRes.adaptTo(ModifiableValueMap.class)); consumer.accept(modifiableValueMap); resolver.commit(); } catch (PersistenceException e) { throw new AppIntegrationException("Failed to " + methodName + " on " + rootPath); } } @Nonnull protected Resource getOrCreateResource(String path) throws PersistenceException { final String[] splitPath = path.split(JCR_PATH_SEPARATOR); if ((splitPath.length < 3) || (!splitPath[0].equals(""))) { throw new AppIntegrationException("Cannot create path " + path + "! Must be an absolute path with at least two levels"); } // handle top-level path-elem final String topLevelPath = JCR_PATH_SEPARATOR + splitPath[1] + JCR_PATH_SEPARATOR + splitPath[2]; Resource curResource = resolver.getResource(topLevelPath); if (curResource == null) { throw new AppIntegrationException("Cannot create path " + path + ", as top-level paths should already exists: " + topLevelPath); } // handle 2nd-level path-elements and deeper for (int i = 3; i < splitPath.length; i++) { curResource = getOrCreateChild(curResource, splitPath[i]); } return curResource; } @Nonnull private Resource getOrCreateChild(@Nonnull Resource parentRes, @Nonnull String childName) throws PersistenceException { Resource childRes = parentRes.getChild(childName); if (childRes == null) { childRes = resolver.create(parentRes, childName, Collections.singletonMap(JCR_PRIMARYTYPE, NT_UNSTRUCTURED)); } return childRes; } private class CachePath { private static final String METADATA_NAME = "metadata"; private final String path; private final String filename; public CachePath(URI uri) { List<String> splitPath = Arrays.stream(StringUtils.split(uri.getPath(), "/")) .map(StringUtils::trimToNull) .filter(Objects::nonNull) .map(JcrUtil::escapeIllegalJcrChars) .collect(Collectors.toCollection(ArrayList::new)); if (splitPath.isEmpty()) splitPath.add("index"); this.filename = splitPath.get(splitPath.size() - 1); if (StringUtils.isNotBlank(uri.getQuery())) splitPath.add(Integer.toHexString(uri.getQuery().hashCode())); this.path = rootPath + JCR_PATH_SEPARATOR + String.join(JCR_PATH_SEPARATOR, splitPath); } public String getPath() { return path; } public String getFilename() { return filename; } public String getMetadataName() { return METADATA_NAME + (METADATA_NAME.equals(filename) ? "0" : ""); } } protected static class CacheEntry { private final CachePath cachePath; private final Resource cacheEntryRes; private ModifiableValueMap cacheEntryValueMap; public CacheEntry(CachePath cachePath, Resource cacheEntryRes) { this.cachePath = cachePath; this.cacheEntryRes = cacheEntryRes; } public Resource getCacheEntryRes() { return cacheEntryRes; } public CachePath getCachePath() { return cachePath; } public ModifiableValueMap getCacheEntryValueMap() { if (cacheEntryValueMap == null) { cacheEntryValueMap = Objects.requireNonNull(cacheEntryRes.adaptTo(ModifiableValueMap.class)); } return cacheEntryValueMap; } } }
3e1fca9aefcc22c8d532412dab87e0f780c5f8bf
15,110
java
Java
continuum-grind/src/main/java/com/kinotic/continuum/grind/internal/api/TaskStep.java
Kinotic-Foundation/continuum-framework
c8a29b0e07f3ff1b5c5d1c0bf7e5f5bc578e797e
[ "Apache-2.0" ]
null
null
null
continuum-grind/src/main/java/com/kinotic/continuum/grind/internal/api/TaskStep.java
Kinotic-Foundation/continuum-framework
c8a29b0e07f3ff1b5c5d1c0bf7e5f5bc578e797e
[ "Apache-2.0" ]
null
null
null
continuum-grind/src/main/java/com/kinotic/continuum/grind/internal/api/TaskStep.java
Kinotic-Foundation/continuum-framework
c8a29b0e07f3ff1b5c5d1c0bf7e5f5bc578e797e
[ "Apache-2.0" ]
null
null
null
45.927052
178
0.542422
13,428
/* * * Copyright 2008-2021 Kinotic and the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kinotic.continuum.grind.internal.api; import com.kinotic.continuum.grind.api.*; import org.apache.commons.lang3.ClassUtils; import org.reactivestreams.Publisher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.ReactiveAdapter; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.core.env.MapPropertySource; import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.UUID; /** * Provides functionality for a {@link Step} that will execute a {@link Task} that will emit a single value * * * Created by Navid Mitchell on 3/19/20 */ public class TaskStep extends AbstractStep { private static final Logger log = LoggerFactory.getLogger(TaskStep.class); private final ReactiveAdapterRegistry reactiveAdapterRegistry; private final Task<?> task; private final boolean storeResult; private final String resultName; private final String taskDisplayString; public TaskStep(int sequence, Task<?> task) { this(sequence, task, false, null); } public TaskStep(int sequence, Task<?> task, boolean storeResult) { this(sequence, task, storeResult, null); } /** * Create a {@link Step} that will execute a {@link Task} that will emit a single value * @param task for this step * @param storeResult determines if the result of the {@link Task} should be stored in the execution context * @param resultName the name of the result to use when storing the result in the execution context */ public TaskStep(int sequence, Task<?> task, boolean storeResult, String resultName) { super(sequence); this.task = task; this.storeResult = storeResult; this.resultName = resultName; this.taskDisplayString = "\"" + task.getDescription() + "\""; reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance(); } @Override public String getDescription() { return task.getDescription(); } @Override public Publisher<Result<?>> assemble(GenericApplicationContext applicationContext, ResultOptions options) { return Flux.create(sink -> { try { notifyProgress(() -> new Progress(0, "Task: " + taskDisplayString + " Executing"), sink, options, log); if(!(task instanceof NoopTask)) { Object result = task.execute(applicationContext); // check if this task returned a job definition, task, or something else if(result instanceof JobDefinition){ completeWithJobDefinition(applicationContext, options, sink, (JobDefinition) result); }else if(result instanceof Task){ completeWithTask(applicationContext, options, sink, (Task<?>) result); }else{ completeWithResult(applicationContext, options, sink, result); } }else{ if(log.isDebugEnabled()){ log.debug("Task was noop "+taskDisplayString); } sink.next(new DefaultResult<>(new StepInfo(sequence), ResultType.NOOP, null)); notifyProgress(() -> new Progress(100, "Task: " + taskDisplayString + " Finished Executing"), sink, options, log); sink.complete(); } } catch (Exception throwable) { notifyException(() -> "Task: " + taskDisplayString + " Exception during execution ", throwable, sink, options, log); sink.error(throwable); } }); } private void completeWithJobDefinition(GenericApplicationContext applicationContext, ResultOptions options, FluxSink<Result<?>> sink, JobDefinition jobDefinition){ notifyDiagnostic(DiagnosticLevel.TRACE, () -> "Task: " + taskDisplayString + " returned a JobDefinition: \"" + jobDefinition.getDescription() + "\"", sink, options, log); JobDefinitionStep jobDefinitionStep = new JobDefinitionStep(1, jobDefinition); sink.next(new DefaultResult<>(new StepInfo(sequence), ResultType.DYNAMIC_STEPS, jobDefinitionStep)); completeWithStep(options, sink, jobDefinitionStep.assemble(applicationContext, options)); } private void completeWithTask(GenericApplicationContext applicationContext, ResultOptions options, FluxSink<Result<?>> sink, Task<?> result) { notifyDiagnostic(DiagnosticLevel.TRACE, () -> "Task: " + taskDisplayString + " returned a Task: \"" + result.getDescription() + "\"", sink, options, log); TaskStep taskStep = new TaskStep(1, result, storeResult, resultName); sink.next(new DefaultResult<>(new StepInfo(sequence), ResultType.DYNAMIC_STEPS, taskStep)); completeWithStep(options, sink, taskStep.assemble(applicationContext, options)); } private void completeWithStep(ResultOptions options, FluxSink<Result<?>> sink, Publisher<Result<?>> assemble) { // Results are produced by Tasks that return a JobDefinition or a Task Disposable disposable = Flux.from(assemble) .doOnNext(result -> { result.getStepInfo().addAncestor(new StepInfo(sequence)); sink.next(result); }) .doOnError(throwable -> { notifyException(() -> "Task: " + taskDisplayString + " Exception during execution ", throwable, sink, options, log); sink.error(throwable); }) .doOnComplete(() -> { notifyProgress(() -> new Progress(100, "Task: " + taskDisplayString + " Finished Executing"), sink, options, log); sink.complete(); }) .subscribe(); sink.onCancel(disposable); } private void completeWithResult(GenericApplicationContext applicationContext, ResultOptions options, FluxSink<Result<?>> sink, Object result){ if (result != null) { // Check if result is reactive if so we only complete once result is complete ReactiveAdapter reactiveAdapter = reactiveAdapterRegistry.getAdapter(null, result); if(reactiveAdapter != null){ notifyDiagnostic(DiagnosticLevel.TRACE, () -> "Task: " + taskDisplayString+ " returned value of type:\"" + result.getClass().getName(), sink, options, log); Disposable disposable = Flux.from(reactiveAdapter.toPublisher(result)) .doOnNext(value -> { // If the value returned is a Result type we will store it but the forward through // we just overwrite the parentIdentifier to match this task if(value instanceof Result){ Result<?> resultInternal = (Result<?>) value; if(resultInternal.getResultType() == ResultType.VALUE){ addIfDesiredToApplicationContext(applicationContext, options, sink, resultInternal.getValue()); } resultInternal.getStepInfo().addAncestor(new StepInfo(sequence)); sink.next(resultInternal); }else{ addIfDesiredToApplicationContext(applicationContext, options, sink, value); sink.next(new DefaultResult<>(new StepInfo(sequence), ResultType.VALUE, value)); } }).doOnError(throwable -> { notifyException(() -> "Task: " + taskDisplayString + " Exception during execution ", throwable, sink, options, log); sink.error(throwable); }).doOnComplete(() -> { notifyProgress(() -> new Progress(100, "Task: " + taskDisplayString + " Finished Executing"), sink, options, log); sink.complete(); }).subscribe(); sink.onCancel(disposable); } else { addIfDesiredToApplicationContext(applicationContext, options, sink, result); sink.next(new DefaultResult<>(new StepInfo(sequence), ResultType.VALUE, result)); notifyProgress(() -> new Progress(100, "Task: " + taskDisplayString + " Finished Executing"), sink, options, log); sink.complete(); } }else{ notifyDiagnostic(DiagnosticLevel.WARN, () -> "Task: " + taskDisplayString +" Result was requested to be stored, but result is NULL", sink, options, log); sink.next(new DefaultResult<>(new StepInfo(sequence), ResultType.VALUE, null)); notifyProgress(() -> new Progress(100, "Task: " + taskDisplayString + " Finished Executing"), sink, options, log); sink.complete(); } } private void addIfDesiredToApplicationContext(GenericApplicationContext applicationContext, ResultOptions options, FluxSink<Result<?>> sink, Object result){ if(storeResult) { if (result != null) { Class<?> clazz = result.getClass(); ConfigurableBeanFactory beanFactory = applicationContext.getBeanFactory(); MapPropertySource propertySource = (MapPropertySource) applicationContext.getEnvironment() .getPropertySources() .get(GrindConstants.GRIND_MAP_PROPERTY_SOURCE); // sanity check if (propertySource == null) { throw new IllegalStateException("Expected MapPropertySource was not set for " + GrindConstants.GRIND_MAP_PROPERTY_SOURCE); } if (isBeanCandidate(result)) { if (result instanceof Collection) { if(this.resultName != null && this.resultName.length() > 0){ notifyDiagnostic(DiagnosticLevel.TRACE, () -> "Task: " + taskDisplayString + " Storing result as Collection Property \"" + resultName + "\" Value: " + result, sink, options, log); propertySource.getSource().put(resultName, result); }else{ for (Object val : ((Collection<?>) result)) { String beanName = val.getClass().getSimpleName() + "_" + UUID.randomUUID().toString(); notifyDiagnostic(DiagnosticLevel.TRACE, () -> "Task: " + taskDisplayString + " Storing result as Singleton: \"" + beanName + "\" Value: " + result, sink, options, log); beanFactory.registerSingleton(beanName, val); } } } else { String beanName = this.resultName != null && this.resultName.length() > 0 ? this.resultName : clazz.getSimpleName(); notifyDiagnostic(DiagnosticLevel.TRACE, () -> "Task: " + taskDisplayString + " Storing result as Singleton: \"" + beanName + "\" Value: " + result, sink, options, log); beanFactory.registerSingleton(beanName, result); } } else { if (resultName != null && resultName.length() > 0) { notifyDiagnostic(DiagnosticLevel.TRACE, () -> "Task: " + taskDisplayString + " Storing result as Property: \"" + resultName + "\" Value: " + result, sink, options, log); propertySource.getSource().put(resultName, result); } else { notifyDiagnostic(DiagnosticLevel.WARN, () -> "Task: " + taskDisplayString +" Cannot store Application Context Property. All primitive types must have a name defined.", sink, options, log); } } }else{ notifyDiagnostic(DiagnosticLevel.WARN, () -> "Task: " + taskDisplayString +" Result was requested to be stored, but result is NULL", sink, options, log); } } } private boolean isBeanCandidate(Object result){ boolean ret = false; Class<?> clazz = result.getClass(); if(!clazz.isArray() && !clazz.isEnum() && !ClassUtils.isPrimitiveOrWrapper(clazz) && !clazz.isAnnotation() && !(result instanceof CharSequence) && !(result instanceof Date) && !(result instanceof Calendar)){ ret = true; } return ret; } }
3e1fcb088aebeebf657dda9ff40e09244e950072
678
java
Java
src/main/java/com/company/project/configurer/CorsConfig.java
ruiyeclub/spring-boot-api-project-seed
3de1248fd9e138c2409eb9bfd02bc2cecde066b8
[ "Apache-2.0" ]
13
2020-06-29T02:23:38.000Z
2021-12-03T09:44:55.000Z
src/main/java/com/company/project/configurer/CorsConfig.java
ColorfulGhost/spring-boot-api-project-seed
ebbda0b62ed1a45076857756f3b610d4a7da9b52
[ "Apache-2.0" ]
1
2022-02-09T22:26:51.000Z
2022-02-09T22:26:51.000Z
src/main/java/com/company/project/configurer/CorsConfig.java
ColorfulGhost/spring-boot-api-project-seed
ebbda0b62ed1a45076857756f3b610d4a7da9b52
[ "Apache-2.0" ]
6
2020-09-04T01:52:18.000Z
2022-01-08T12:51:43.000Z
30.818182
82
0.666667
13,429
package com.company.project.configurer; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 解决跨域问题 */ @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true) .maxAge(3600) .allowedHeaders("*"); } }
3e1fcbabb19d51783fbc0346018f8cd89fa0d99e
1,675
java
Java
paygeneralsdk/src/main/java/com/sdk/paygeneral/PayGeneral.java
banketree/PayGeneralSdk
9f3e15aeb9457d527b150da75eff8223c780de78
[ "Apache-2.0" ]
null
null
null
paygeneralsdk/src/main/java/com/sdk/paygeneral/PayGeneral.java
banketree/PayGeneralSdk
9f3e15aeb9457d527b150da75eff8223c780de78
[ "Apache-2.0" ]
null
null
null
paygeneralsdk/src/main/java/com/sdk/paygeneral/PayGeneral.java
banketree/PayGeneralSdk
9f3e15aeb9457d527b150da75eff8223c780de78
[ "Apache-2.0" ]
null
null
null
19.034091
61
0.727761
13,430
package com.sdk.paygeneral; import com.sdk.paygeneral.alipay.AliPay; import com.sdk.paygeneral.alipay.IAliPayInfo; import com.sdk.paygeneral.weixin.IWeiXinInfo; import com.sdk.paygeneral.weixin.WeiXinPay; import com.thinkcore.utils.TStringUtils; public class PayGeneral implements IAliPayInfo, IWeiXinInfo { public boolean hasPay(String name) { if (TStringUtils.isEmpty(name)) return false; if (name.contains("微信支付") || name.contains("支付宝")) { return true; } return false; } public AliPay getAliPay() { AliPay aliPay = new AliPay(); aliPay.setAliPayPartner(getAliPayPartner()); aliPay.setAliPayRsaPrivate(getAliPayRsaPrivate()); aliPay.setAliPaySeller(getAliPaySeller()); aliPay.setAliPayNotifyUrl(getAliPayNotifyUrl()); return aliPay; } public WeiXinPay getWeiXinPay() { WeiXinPay weiXinPay = new WeiXinPay(); weiXinPay.setWeiXinAppId(getWeiXinAppId()); weiXinPay.setWeiXinMchId(getWeiXinMchId()); weiXinPay.setWeiXinApiKey(getWeiXinApiKey()); weiXinPay.setWeiXinNotifyUrl(getWeiXinNotifyUrl()); return weiXinPay; } // alipay @Override public String getAliPayPartner() { return ""; } @Override public String getAliPaySeller() { return ""; } @Override public String getAliPayRsaPrivate() { return ""; } @Override public String getAliPayRsaPublic() { return ""; } @Override public String getAliPayNotifyUrl() { return ""; } // weixinpay @Override public String getWeiXinAppId() { return ""; } @Override public String getWeiXinMchId() { return ""; } @Override public String getWeiXinApiKey() { return ""; } @Override public String getWeiXinNotifyUrl() { return ""; } }
3e1fcc4df2bea1d7c66d227b2f01c2e1d70e7f48
2,173
java
Java
src/main/java/pers/li/thread/schedule/schedule/ScheduledExecutorTest.java
a982338665/multithreading
792ed796e744c97a45906e0604069224771712eb
[ "MIT" ]
2
2020-10-19T14:13:02.000Z
2021-01-22T09:47:01.000Z
src/main/java/pers/li/thread/schedule/schedule/ScheduledExecutorTest.java
a982338665/multithreading
792ed796e744c97a45906e0604069224771712eb
[ "MIT" ]
null
null
null
src/main/java/pers/li/thread/schedule/schedule/ScheduledExecutorTest.java
a982338665/multithreading
792ed796e744c97a45906e0604069224771712eb
[ "MIT" ]
null
null
null
26.5
80
0.599172
13,431
package pers.li.thread.schedule.schedule; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledExecutorTest { public static void main(String[] a) throws Exception { // executeAtFixTime(); //严格按照定时执行,不管上次的执行是否完成 executeFixedRate(); //3s //等待上次执行完成后,以结束时间为定时开始时间,总保证上次任务执行完毕 // executeFixedDelay(); //4s } /** * 1秒后执行任务task * * @throws Exception */ public static void executeAtFixTime() throws Exception { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.schedule( new MyTask(), 1, TimeUnit.SECONDS); Thread.sleep(20000); executor.shutdown(); } /** * 延迟1毫秒执行,每3000毫秒执行一次 * 周期任务 固定速率 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕, * 如果上一个任务执行完毕,则当前任务立即执行,如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行。 * * @throws Exception */ public static void executeFixedRate() throws Exception { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleAtFixedRate( new MyTask(), 1, 3000, TimeUnit.MILLISECONDS); Thread.sleep(20000); executor.shutdown(); } /** * 周期任务 固定延时 是以上一个任务结束时开始计时,period时间过去后,立即执行。 * * @throws Exception */ public static void executeFixedDelay() throws Exception { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleWithFixedDelay( new MyTask(), 1, 3000, TimeUnit.MILLISECONDS); Thread.sleep(20000); executor.shutdown(); } } class MyTask implements Runnable { public void run() { System.out.println("时间为:" + new Date()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } //System.out.println("时间为:" + new Date()); } }
3e1fcc9609aace009edf9f84d174eeaa01111ba5
3,760
java
Java
src/test/java/ch/hslu/ad/sw08_N3/Aufgabe1/ConcurrentTest.java
yannickbaettig/ad
93dd41d9a04ca4b8ae40762503dd2aa926b72b91
[ "Apache-2.0" ]
null
null
null
src/test/java/ch/hslu/ad/sw08_N3/Aufgabe1/ConcurrentTest.java
yannickbaettig/ad
93dd41d9a04ca4b8ae40762503dd2aa926b72b91
[ "Apache-2.0" ]
null
null
null
src/test/java/ch/hslu/ad/sw08_N3/Aufgabe1/ConcurrentTest.java
yannickbaettig/ad
93dd41d9a04ca4b8ae40762503dd2aa926b72b91
[ "Apache-2.0" ]
null
null
null
32.136752
106
0.570745
13,432
package ch.hslu.ad.sw08_N3.Aufgabe1; import ch.hslu.ad.sw06_N2.Aufgabe3.*; import org.apache.logging.log4j.LogManager; import org.junit.Before; import org.junit.Test; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; public class ConcurrentTest { private final static org.apache.logging.log4j.Logger LOG = LogManager.getLogger(ConcurrentTest.class); private LinkedBlockingDeque<Integer> buffer; private ExecutorService executor; @Before public void before(){ buffer = new LinkedBlockingDeque(); executor = Executors.newCachedThreadPool(); } @Test public void testPut() throws InterruptedException { buffer.put(1); LOG.info(buffer.size()); } @Test public void testGet() throws InterruptedException { buffer.put(4); Integer integer = buffer.poll(); LOG.info(integer); LOG.info(buffer.size()); } @Test public void testPushAndPop() throws InterruptedException { final Random random = new Random(); final int nPros = 3; final Producer2[] producers = new Producer2[nPros]; final int mCons = 2; final Consumer2[] consumers = new Consumer2[mCons]; for (int i = 0; i < nPros; i++) { producers[i] = new Producer2(buffer, random.nextInt(10000)); executor.execute(producers[i]); } for (int i = 0; i < mCons; i++) { consumers[i] = new Consumer2(buffer); executor.execute(consumers[i]); } /*executor.awaitTermination(3000, TimeUnit.MILLISECONDS); while (!executor.isShutdown()) { Thread.yield(); }*/ TimeUnit.MILLISECONDS.sleep(100); executor.shutdown(); int sumPros = 0; for (int i = 0; i < nPros; i++) { LOG.info("Prod " + (char) (i + 65) + " = " + producers[i].getSum()); sumPros += producers[i].getSum(); } int sumCons = 0; for (int i = 0; i < mCons; i++) { LOG.info("Cons " + (char) (i + 65) + " = " + consumers[i].getSum()); sumCons += consumers[i].getSum(); } LOG.info(sumPros + " = " + sumCons); assertEquals(sumPros, sumCons); } @Test public void testPutAndGet() throws InterruptedException { final Random random = new Random(); final int nPros = 3; final Producer[] producers = new Producer[nPros]; final int mCons = 2; final Consumer[] consumers = new Consumer[mCons]; for (int i = 0; i < nPros; i++) { producers[i] = new Producer(buffer, random.nextInt(10000)); executor.execute(producers[i]); } for (int i = 0; i < mCons; i++) { consumers[i] = new Consumer(buffer); executor.execute(consumers[i]); } /*executor.awaitTermination(3000, TimeUnit.MILLISECONDS); while (!executor.isShutdown()) { Thread.yield(); }*/ TimeUnit.MILLISECONDS.sleep(100); executor.shutdown(); int sumPros = 0; for (int i = 0; i < nPros; i++) { LOG.info("Prod " + (char) (i + 65) + " = " + producers[i].getSum()); sumPros += producers[i].getSum(); } int sumCons = 0; for (int i = 0; i < mCons; i++) { LOG.info("Cons " + (char) (i + 65) + " = " + consumers[i].getSum()); sumCons += consumers[i].getSum(); } LOG.info(sumPros + " = " + sumCons); assertEquals(sumPros, sumCons); } }
3e1fcd0396650ab7f7a15a662ad08a4a0083a45c
535
java
Java
SummerNoteApi&S3/src/main/java/com/kh/spring/summernote/model/converter/BooleanToStringConverter.java
nob0dj/springWebAPI
f43546dcd102cdecd326ea8bf34b407a4d134004
[ "BSD-3-Clause" ]
null
null
null
SummerNoteApi&S3/src/main/java/com/kh/spring/summernote/model/converter/BooleanToStringConverter.java
nob0dj/springWebAPI
f43546dcd102cdecd326ea8bf34b407a4d134004
[ "BSD-3-Clause" ]
14
2020-03-04T21:44:27.000Z
2021-12-09T20:50:57.000Z
SummerNoteApi&S3/src/main/java/com/kh/spring/summernote/model/converter/BooleanToStringConverter.java
nob0dj/springWebAPI
f43546dcd102cdecd326ea8bf34b407a4d134004
[ "BSD-3-Clause" ]
1
2019-08-05T01:06:58.000Z
2019-08-05T01:06:58.000Z
28.157895
87
0.652336
13,433
package com.kh.spring.summernote.model.converter; import javax.persistence.AttributeConverter; import javax.persistence.Converter; @Converter public class BooleanToStringConverter implements AttributeConverter<Boolean, String> { @Override public String convertToDatabaseColumn(Boolean value) { return (value != null && value) ? "Y" : "N"; } @Override public Boolean convertToEntityAttribute(String value) { return "Y".equals(value); } }
3e1fce9c84c5a45565bcf32243380210b6c7140a
4,359
java
Java
jbb-web-app-e2e-tests/src/test/java/org/jbb/e2e/serenity/rest/board/GetBoardRestStories.java
jbb-project/jbb
cefa12cda40804395b2d6e8bea0fb8352610b761
[ "Apache-2.0" ]
4
2017-02-23T15:35:33.000Z
2020-08-03T22:00:17.000Z
jbb-web-app-e2e-tests/src/test/java/org/jbb/e2e/serenity/rest/board/GetBoardRestStories.java
jbb-project/jbb
cefa12cda40804395b2d6e8bea0fb8352610b761
[ "Apache-2.0" ]
1
2019-05-14T18:54:24.000Z
2019-05-14T18:54:24.000Z
jbb-web-app-e2e-tests/src/test/java/org/jbb/e2e/serenity/rest/board/GetBoardRestStories.java
jbb-project/jbb
cefa12cda40804395b2d6e8bea0fb8352610b761
[ "Apache-2.0" ]
3
2018-03-29T15:51:09.000Z
2019-11-25T02:46:41.000Z
34.595238
116
0.745125
13,434
/* * Copyright (C) 2019 the original author or authors. * * This file is part of jBB Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jbb.e2e.serenity.rest.board; import net.thucydides.core.annotations.Steps; import net.thucydides.core.annotations.WithTagValuesOf; import org.jbb.e2e.serenity.Tags.Feature; import org.jbb.e2e.serenity.Tags.Interface; import org.jbb.e2e.serenity.Tags.Release; import org.jbb.e2e.serenity.Tags.Type; import org.jbb.e2e.serenity.rest.EndToEndRestStories; import org.jbb.e2e.serenity.rest.commons.TestMember; import org.jbb.e2e.serenity.rest.commons.TestOAuthClient; import org.jbb.e2e.serenity.rest.members.SetupMemberSteps; import org.jbb.e2e.serenity.rest.oauthclient.SetupOAuthSteps; import org.jbb.lib.restful.domain.ErrorInfo; import org.junit.Test; import static org.jbb.lib.commons.security.OAuthScope.BOARD_READ; import static org.jbb.lib.commons.security.OAuthScope.BOARD_READ_WRITE; public class GetBoardRestStories extends EndToEndRestStories { @Steps BoardResourceSteps boardResourceSteps; @Steps SetupMemberSteps setupMemberSteps; @Steps SetupOAuthSteps setupOAuthSteps; @Test @WithTagValuesOf({Interface.REST, Type.SMOKE, Feature.FORUM_MANAGEMENT, Release.VER_0_11_0}) public void guest_can_get_board_structure_via_api() { // when boardResourceSteps.get_board(); // then boardResourceSteps.should_contains_not_empty_board(); } @Test @WithTagValuesOf({Interface.REST, Type.SMOKE, Feature.FORUM_MANAGEMENT, Release.VER_0_11_0}) public void member_can_get_board_structure_via_api() { // given TestMember member = setupMemberSteps.create_member(); make_rollback_after_test_case(setupMemberSteps.delete_member(member)); authRestSteps.sign_in_for_every_request(member); // when boardResourceSteps.get_board(); // then boardResourceSteps.should_contains_not_empty_board(); } @Test @WithTagValuesOf({Interface.REST, Type.SMOKE, Feature.FORUM_MANAGEMENT, Release.VER_0_11_0}) public void administrator_can_get_board_structure_via_api() { // given authRestSteps.sign_in_as_admin_for_every_request(); // when boardResourceSteps.get_board(); // then boardResourceSteps.should_contains_not_empty_board(); } @Test @WithTagValuesOf({Interface.REST, Type.SMOKE, Feature.FORUM_MANAGEMENT, Release.VER_0_12_0}) public void client_with_board_read_scope_can_get_board_structure_via_api() { // given TestOAuthClient client = setupOAuthSteps.create_client_with_scope(BOARD_READ); make_rollback_after_test_case(setupOAuthSteps.delete_oauth_client(client)); authRestSteps.authorize_every_request_with_oauth_client(client); // when boardResourceSteps.get_board(); // then boardResourceSteps.should_contains_not_empty_board(); } @Test @WithTagValuesOf({Interface.REST, Type.SMOKE, Feature.FORUM_MANAGEMENT, Release.VER_0_12_0}) public void client_with_board_write_scope_can_get_board_structure_via_api() { // given TestOAuthClient client = setupOAuthSteps.create_client_with_scope(BOARD_READ_WRITE); make_rollback_after_test_case(setupOAuthSteps.delete_oauth_client(client)); authRestSteps.authorize_every_request_with_oauth_client(client); // when boardResourceSteps.get_board(); // then boardResourceSteps.should_contains_not_empty_board(); } @Test @WithTagValuesOf({Interface.REST, Type.SMOKE, Feature.FORUM_MANAGEMENT, Release.VER_0_12_0}) public void client_without_board_scopes_cannot_get_board_structure_via_api() { // given TestOAuthClient client = setupOAuthSteps.create_client_with_all_scopes_except(BOARD_READ, BOARD_READ_WRITE); make_rollback_after_test_case(setupOAuthSteps.delete_oauth_client(client)); authRestSteps.authorize_every_request_with_oauth_client(client); // when boardResourceSteps.get_board(); // then assertRestSteps.assert_response_error_info(ErrorInfo.FORBIDDEN); } }
3e1fceeaa65bf8b70f528d9f8873a9c2ae2b955a
2,043
java
Java
mongodb-redis-integration/src/main/java/com/poc/mongodbredisintegration/service/MongoDBReactiveService.java
SamyBacha/POC
c42345d28ffd949b145724fd7e7583ce48e812b3
[ "Apache-2.0" ]
null
null
null
mongodb-redis-integration/src/main/java/com/poc/mongodbredisintegration/service/MongoDBReactiveService.java
SamyBacha/POC
c42345d28ffd949b145724fd7e7583ce48e812b3
[ "Apache-2.0" ]
null
null
null
mongodb-redis-integration/src/main/java/com/poc/mongodbredisintegration/service/MongoDBReactiveService.java
SamyBacha/POC
c42345d28ffd949b145724fd7e7583ce48e812b3
[ "Apache-2.0" ]
null
null
null
25.860759
79
0.694077
13,435
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.poc.mongodbredisintegration.service; import com.poc.mongodbredisintegration.document.Book; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.http.ResponseEntity; /** * Interface for MongoDBReactiveService. * * @author Raja Kolli * @since 0.1.1 */ public interface MongoDBReactiveService { /** * <p> * findAllBooks. * </p> * @return a {@link reactor.core.publisher.Flux} object. */ Flux<Book> findAllBooks(); /** * <p> * save. * </p> * @param book a {@link com.poc.mongodbredisintegration.document.Book} object. * @return a {@link reactor.core.publisher.Mono} object. */ Mono<Book> save(Book book); /** * <p> * getBookById. * </p> * @param bookId a {@link java.lang.String} object. * @return a {@link reactor.core.publisher.Mono} object. */ Mono<ResponseEntity<Book>> getBookById(String bookId); /** * <p> * updateBook. * </p> * @param bookId a {@link java.lang.String} object. * @param book a {@link com.poc.mongodbredisintegration.document.Book} object. * @return a {@link reactor.core.publisher.Mono} object. */ Mono<ResponseEntity<Book>> updateBook(String bookId, Book book); /** * <p> * deleteBook. * </p> * @param bookId a {@link java.lang.String} object. * @return a {@link reactor.core.publisher.Mono} object. */ Mono<ResponseEntity<Void>> deleteBook(String bookId); }
3e1fd04a674b2b12e8ff34732775317ad4ddd2f2
434
java
Java
languages/baseLanguage/baseLanguage/source_gen/jetbrains/mps/baseLanguage/textGen/BooleanType_TextGen.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
languages/baseLanguage/baseLanguage/source_gen/jetbrains/mps/baseLanguage/textGen/BooleanType_TextGen.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
languages/baseLanguage/baseLanguage/source_gen/jetbrains/mps/baseLanguage/textGen/BooleanType_TextGen.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
27.125
64
0.790323
13,436
package jetbrains.mps.baseLanguage.textGen; /*Generated by MPS */ import jetbrains.mps.text.rt.TextGenDescriptorBase; import jetbrains.mps.text.rt.TextGenContext; import jetbrains.mps.text.impl.TextGenSupport; public class BooleanType_TextGen extends TextGenDescriptorBase { @Override public void generateText(final TextGenContext ctx) { final TextGenSupport tgs = new TextGenSupport(ctx); tgs.append("boolean"); } }
3e1fd1066cf50a72b36652e99e60f77a1991083f
1,339
java
Java
core/IncrementOperators.java
hershyz/bscript
61078bb8eed69dabf0f8a0cd8e28a96b7a451c99
[ "MIT" ]
null
null
null
core/IncrementOperators.java
hershyz/bscript
61078bb8eed69dabf0f8a0cd8e28a96b7a451c99
[ "MIT" ]
1
2019-07-26T13:31:06.000Z
2019-07-27T13:33:02.000Z
core/IncrementOperators.java
hershyz/bscript
61078bb8eed69dabf0f8a0cd8e28a96b7a451c99
[ "MIT" ]
1
2021-04-11T01:23:42.000Z
2021-04-11T01:23:42.000Z
36.189189
86
0.559373
13,437
public class IncrementOperators { private static Parser parser = new Parser(""); private double incrementFactor = 1.00; //Increments an existing double variable by the increment factor: public void increment(String variableName, String incrementType) { variableName = variableName.trim(); incrementType = incrementType.trim(); double existingValue = parser.findDoubleValue(variableName); //Adds: if (incrementType.equals("++")) { int i; for (i = 0; i < parser.variableStorage.doubleNames.size(); i++) { if (parser.variableStorage.doubleNames.get(i).equals(variableName)) { double newValue = existingValue + incrementFactor; parser.variableStorage.doubleValues.set(i, newValue); } } } //Subtracts: if (incrementType.equals("--")) { int i; for (i = 0; i < parser.variableStorage.doubleNames.size(); i++) { if (parser.variableStorage.doubleNames.get(i).equals(variableName)) { double newValue = existingValue - incrementFactor; parser.variableStorage.doubleValues.set(i, newValue); } } } } }
3e1fd1228964f4baf57b921f48cabd9068b94e79
3,132
java
Java
wk-app/wk-nb-web-vue/src/main/java/cn/wizzer/app/web/commons/base/Globals.java
dingmike/nutwxProject
0a8004054ac3e992c5130a44a654293e41bc1e74
[ "Apache-2.0" ]
1
2017-12-19T06:58:26.000Z
2017-12-19T06:58:26.000Z
wk-app/wk-nb-web-vue/src/main/java/cn/wizzer/app/web/commons/base/Globals.java
dingmike/nutwxProject
0a8004054ac3e992c5130a44a654293e41bc1e74
[ "Apache-2.0" ]
1
2018-06-29T12:16:09.000Z
2018-06-29T12:16:09.000Z
wk-app/wk-nb-web-vue/src/main/java/cn/wizzer/app/web/commons/base/Globals.java
dingmike/nutwxProject
0a8004054ac3e992c5130a44a654293e41bc1e74
[ "Apache-2.0" ]
1
2017-12-27T10:57:39.000Z
2017-12-27T10:57:39.000Z
32.968421
95
0.623883
13,438
package cn.wizzer.app.web.commons.base; import cn.wizzer.app.sys.modules.models.Sys_config; import cn.wizzer.app.sys.modules.models.Sys_route; import cn.wizzer.app.sys.modules.services.SysConfigService; import cn.wizzer.app.sys.modules.services.SysRouteService; import com.alibaba.dubbo.config.annotation.Reference; import org.nutz.dao.Cnd; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.weixin.impl.WxApi2Impl; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by wizzer on 2016/12/19. */ @IocBean(create = "init") public class Globals { //项目路径 public static String AppRoot = ""; //项目目录 public static String AppBase = ""; //项目名称 public static String AppName = "NutzWk 开发框架"; //项目短名称 public static String AppShrotName = "NutzWk"; //项目域名 public static String AppDomain = "http://127.0.0.1"; //文件上传路径 public static String AppUploadPath = "D://files/upload"; //文件上传路径 public static String AppUploadBase = "/upload"; // 是否启用了队列 public static boolean RabbitMQEnabled = false; //系统自定义参数 public static Map<String, String> MyConfig = new HashMap<>(); //自定义路由 public static Map<String, Sys_route> RouteMap = new HashMap<>(); //微信map public static Map<String, WxApi2Impl> WxMap = new HashMap<>(); @Inject @Reference private SysConfigService sysConfigService; @Inject @Reference private SysRouteService sysRouteService; public void init() { initSysConfig(sysConfigService); initRoute(sysRouteService); } public static void initSysConfig(SysConfigService sysConfigService) { Globals.MyConfig.clear(); List<Sys_config> configList = sysConfigService.query(); for (Sys_config sysConfig : configList) { switch (sysConfig.getConfigKey()) { case "AppName": Globals.AppName = sysConfig.getConfigValue(); break; case "AppShrotName": Globals.AppShrotName = sysConfig.getConfigValue(); break; case "AppDomain": Globals.AppDomain = sysConfig.getConfigValue(); break; case "AppUploadPath": Globals.AppUploadPath = sysConfig.getConfigValue(); break; case "AppUploadBase": Globals.AppUploadBase = sysConfig.getConfigValue(); break; default: Globals.MyConfig.put(sysConfig.getConfigKey(), sysConfig.getConfigValue()); break; } } } public static void initRoute(SysRouteService sysRouteService) { Globals.RouteMap.clear(); List<Sys_route> routeList = sysRouteService.query(Cnd.where("disabled", "=", false)); for (Sys_route route : routeList) { Globals.RouteMap.put(route.getUrl(), route); } } public static void initWx() { Globals.WxMap.clear(); } }
3e1fd14724dd424b1ccb3e060098d181ad08774d
1,951
java
Java
cheetah-web-backstage/src/main/java/top/zylsite/cheetah/web/backstage/common/shiro/credentials/UserCredentialsMatcher.java
githubzyl/cheetah
fad101a6a750f658c9d89117fffbb4e913d2f301
[ "MIT" ]
2
2020-02-21T09:16:40.000Z
2021-05-14T02:09:38.000Z
cheetah-web-backstage/src/main/java/top/zylsite/cheetah/web/backstage/common/shiro/credentials/UserCredentialsMatcher.java
githubzyl/cheetah
fad101a6a750f658c9d89117fffbb4e913d2f301
[ "MIT" ]
null
null
null
cheetah-web-backstage/src/main/java/top/zylsite/cheetah/web/backstage/common/shiro/credentials/UserCredentialsMatcher.java
githubzyl/cheetah
fad101a6a750f658c9d89117fffbb4e913d2f301
[ "MIT" ]
null
null
null
34.22807
88
0.789851
13,439
package top.zylsite.cheetah.web.backstage.common.shiro.credentials; import java.util.concurrent.atomic.AtomicInteger; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.ExcessiveAttemptsException; import org.apache.shiro.authc.credential.SimpleCredentialsMatcher; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheManager; import top.zylsite.cheetah.base.utils.EncdDecd; import top.zylsite.cheetah.web.backstage.common.shiro.ShiroConstants; import top.zylsite.cheetah.web.backstage.common.shiro.LoginTypeToken; public class UserCredentialsMatcher extends SimpleCredentialsMatcher { private Cache<String, AtomicInteger> passwordRetryCache; public UserCredentialsMatcher(CacheManager cacheManager) { passwordRetryCache = cacheManager.getCache("passwordRetryCache"); } @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { char[] password = null; if(token instanceof LoginTypeToken) { LoginTypeToken loginTypeToken = (LoginTypeToken) token; password = loginTypeToken.getPassword(); } // 获取用户名 String username = (String) token.getPrincipal(); // 获取登录记录次数 AtomicInteger atomicInteger = passwordRetryCache.get(username); if (null == atomicInteger) { atomicInteger = new AtomicInteger(0); passwordRetryCache.put(username, atomicInteger); } int currentCount = atomicInteger.incrementAndGet(); if (currentCount > ShiroConstants.LOGIN_ERROR_RETRYCOUNT) {// 登陆出错次数已达到上限 throw new ExcessiveAttemptsException(); } // 获得用户输入的密码:(可以采用加盐(salt)的方式去检验) String inPassword = new String(password); inPassword = EncdDecd.MD5String(inPassword); // 获得数据库中的密码 String dbPassword = (String) info.getCredentials(); // 进行密码的比对 boolean matches = this.equals(inPassword, dbPassword); if (matches) { passwordRetryCache.remove(username); } return matches; } }
3e1fd1b30977fd38b3eba0f659324655de48b566
952
java
Java
src/Visualization/VisualizationModel.java
askrier/cell_society
32de05598e8e4f995328783c75cc6eef10184734
[ "MIT" ]
null
null
null
src/Visualization/VisualizationModel.java
askrier/cell_society
32de05598e8e4f995328783c75cc6eef10184734
[ "MIT" ]
null
null
null
src/Visualization/VisualizationModel.java
askrier/cell_society
32de05598e8e4f995328783c75cc6eef10184734
[ "MIT" ]
null
null
null
19.04
90
0.67437
13,440
package Visualization; import XML.SimData; import cellsociety.Grid; import javafx.animation.Timeline; public class VisualizationModel { private Grid myGrid; private SimData mySimData; private Timeline animation; public VisualizationModel() { myGrid = null; } public void setSimData(SimData sim) { mySimData = sim; } public Grid getGrid() { myGrid = new Grid(mySimData.getRows(), mySimData.getColumns(), mySimData.getSimType(), mySimData.getValList(), mySimData.getSpreadProb()); return myGrid; } /** * Returns the state of grid, if there is a grid */ public Grid start(Timeline Animation) { animation = Animation; animation.play(); myGrid.updateGrid(); return myGrid; } public void end() { animation.stop(); } public void speed(double speed) { animation.setRate(speed); } public void stepThrough() { animation.pause(); myGrid.updateGrid(); } }
3e1fd236ab230260b351a0c56cdbcd1204247faf
838
java
Java
src/main/java/thut/api/entity/ai/VectorPosWrapper.java
NelkGames/Pokecube-Issues-and-Wiki
3486e6a8ef415e84bdb4361c8f19cea2a60fa58a
[ "MIT" ]
24
2019-02-02T20:37:53.000Z
2022-02-09T13:51:41.000Z
src/main/java/thut/api/entity/ai/VectorPosWrapper.java
NelkGames/Pokecube-Issues-and-Wiki
3486e6a8ef415e84bdb4361c8f19cea2a60fa58a
[ "MIT" ]
671
2018-08-20T08:46:35.000Z
2022-03-26T00:11:43.000Z
src/main/java/thut/api/entity/ai/VectorPosWrapper.java
NelkGames/Pokecube-Issues-and-Wiki
3486e6a8ef415e84bdb4361c8f19cea2a60fa58a
[ "MIT" ]
68
2018-09-25T21:03:40.000Z
2022-02-25T19:59:51.000Z
20.439024
62
0.671838
13,441
package thut.api.entity.ai; import net.minecraft.entity.LivingEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.IPosWrapper; import net.minecraft.util.math.vector.Vector3d; import thut.api.maths.Vector3; public class VectorPosWrapper implements IPosWrapper { final BlockPos bpos; final Vector3d vpos; final Vector3 pos; public VectorPosWrapper(final Vector3 pos) { this.bpos = pos.getPos().immutable(); this.vpos = pos.toVec3d(); this.pos = pos.copy(); } @Override public BlockPos currentBlockPosition() { return this.bpos; } @Override public Vector3d currentPosition() { return this.vpos; } @Override public boolean isVisibleBy(final LivingEntity p_220610_1_) { return true; } }
3e1fd23a8c12ac189572bc9a7ff92c09c08d8d1a
1,489
java
Java
src/test/java/com/thoughtworks/gocd/elasticagent/ecs/requests/ValidateClusterProfileRequestTest.java
luiseterc/gocd-ecs-elastic-agent
7a7b456f4aec3bb56a7636251f087a8818264619
[ "Apache-2.0" ]
6
2020-06-17T01:49:52.000Z
2022-03-25T13:37:14.000Z
src/test/java/com/thoughtworks/gocd/elasticagent/ecs/requests/ValidateClusterProfileRequestTest.java
luiseterc/gocd-ecs-elastic-agent
7a7b456f4aec3bb56a7636251f087a8818264619
[ "Apache-2.0" ]
15
2020-06-02T09:24:42.000Z
2022-02-28T15:24:16.000Z
src/test/java/com/thoughtworks/gocd/elasticagent/ecs/requests/ValidateClusterProfileRequestTest.java
luiseterc/gocd-ecs-elastic-agent
7a7b456f4aec3bb56a7636251f087a8818264619
[ "Apache-2.0" ]
7
2020-06-01T05:21:02.000Z
2021-10-31T01:42:01.000Z
35.452381
93
0.670248
13,442
/* * Copyright 2020 ThoughtWorks, 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.thoughtworks.gocd.elasticagent.ecs.requests; import org.junit.jupiter.api.Test; import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; public class ValidateClusterProfileRequestTest { @Test void shouldDeserializeFromJSON() { String json = "{\n" + " \"server_url\": \"http://localhost\", \n" + " \"username\": \"bob\", \n" + " \"password\": \"secret\"" + "}"; ValidateClusterProfileRequest request = ValidateClusterProfileRequest.fromJSON(json); HashMap<String, String> expectedSettings = new HashMap<>(); expectedSettings.put("server_url", "http://localhost"); expectedSettings.put("username", "bob"); expectedSettings.put("password", "secret"); assertThat(request).isEqualTo(expectedSettings); } }
3e1fd2c9a9e5bbfb6b877ba72f47e6e189a62aaf
883
java
Java
apps/QT-GUI-Client/src/main/view/PieChartView.java
Didotto/QT-GUI-Miner
9fa4aabfe62e99688b202e8ad8882ee74c6f571a
[ "Apache-2.0" ]
null
null
null
apps/QT-GUI-Client/src/main/view/PieChartView.java
Didotto/QT-GUI-Miner
9fa4aabfe62e99688b202e8ad8882ee74c6f571a
[ "Apache-2.0" ]
null
null
null
apps/QT-GUI-Client/src/main/view/PieChartView.java
Didotto/QT-GUI-Miner
9fa4aabfe62e99688b202e8ad8882ee74c6f571a
[ "Apache-2.0" ]
null
null
null
27.59375
74
0.738392
13,443
package view; import java.io.IOException; import java.util.LinkedList; import model.DataModel; import controller.PieChartController; /** * This class models the view of the stage used * to visualize the results obtained through * the clustering process using a pie-chart. * (Useful to determine the clusters distribution) */ public class PieChartView extends View { /** * Display the stage used to visualize the results * using a pie-chart obtained by the user's input * * @param model contains the information needed and stored for the client * @throws IOException if an I/O error occurs when using the stage */ public PieChartView(DataModel model) throws IOException { super(model, "pieChart.fxml", "mining.png", "CHART VIEW"); getController().init(model, getStage()); ((PieChartController)getController()).updateChart(); getStage().show(); } }
3e1fd316cd44b5aea1aae0e5d7087d5c44a260e9
2,727
java
Java
src/main/java/cn/mirrorming/blog/domain/po/Permission.java
pursue-wind/awesome-blog
b47fb68e7dc9dbe75a97141a4b43b3f9836d1903
[ "MIT" ]
5
2019-11-09T17:19:38.000Z
2020-07-26T20:21:58.000Z
src/main/java/cn/mirrorming/blog/domain/po/Permission.java
pursue-wind/awesome-blog
b47fb68e7dc9dbe75a97141a4b43b3f9836d1903
[ "MIT" ]
3
2020-02-19T13:53:43.000Z
2020-07-26T20:28:08.000Z
src/main/java/cn/mirrorming/blog/domain/po/Permission.java
pursue-wind/awesome-blog
b47fb68e7dc9dbe75a97141a4b43b3f9836d1903
[ "MIT" ]
3
2020-03-25T09:14:24.000Z
2020-11-09T08:33:26.000Z
24.132743
68
0.6707
13,444
package cn.mirrorming.blog.domain.po; import cn.mirrorming.blog.domain.base.BaseEntity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * 后台用户权限表 */ @ApiModel(value = "cn-mirrorming-blog-domain-po-Permission") @Data @EqualsAndHashCode(callSuper = true) @Builder @AllArgsConstructor @NoArgsConstructor @TableName(value = "permission") public class Permission extends BaseEntity implements Serializable { public static final String COL_MODULE = "module"; @TableId(value = "id", type = IdType.AUTO) @ApiModelProperty(value = "") private Integer id; /** * 父级权限id */ @TableField(value = "pid") @ApiModelProperty(value = "父级权限id") private Integer pid; /** * 名称 */ @TableField(value = "name") @ApiModelProperty(value = "名称") private String name; /** * 权限值 */ @TableField(value = "value") @ApiModelProperty(value = "权限值") private String value; /** * 图标 */ @TableField(value = "icon") @ApiModelProperty(value = "图标") private String icon; /** * 权限类型:0->目录;1->菜单;2->按钮(接口绑定权限) */ @TableField(value = "type") @ApiModelProperty(value = "权限类型:0->目录;1->菜单;2->按钮(接口绑定权限)") private Integer type; /** * 前端资源路径 */ @TableField(value = "uri") @ApiModelProperty(value = "前端资源路径") private String uri; /** * 启用状态;0->禁用;1->启用 */ @TableField(value = "status") @ApiModelProperty(value = "启用状态;0->禁用;1->启用") private Integer status; /** * 排序 */ @TableField(value = "sort") @ApiModelProperty(value = "排序") private Integer sort; private static final long serialVersionUID = 1L; public static final String COL_ID = "id"; public static final String COL_PID = "pid"; public static final String COL_NAME = "name"; public static final String COL_VALUE = "value"; public static final String COL_ICON = "icon"; public static final String COL_TYPE = "type"; public static final String COL_URI = "uri"; public static final String COL_STATUS = "status"; public static final String COL_SORT = "sort"; public static final String COL_CREATE_TIME = "create_time"; public static final String COL_UPDATE_TIME = "update_time"; }
3e1fd3287e8fd32e688c2745b2d4ad880e6f9cd3
2,662
java
Java
DSM-sensor/src/main/java/pl/edu/agh/dsm/sensor/Sensor.java
wysekm/DistributedSystemMonitoring
6a643b614c5cc308d414fa35646ef8a02305a1fc
[ "BSD-3-Clause" ]
2
2015-04-23T03:17:04.000Z
2017-01-29T13:44:23.000Z
DSM-sensor/src/main/java/pl/edu/agh/dsm/sensor/Sensor.java
wysekm/DistributedSystemMonitoring
6a643b614c5cc308d414fa35646ef8a02305a1fc
[ "BSD-3-Clause" ]
null
null
null
DSM-sensor/src/main/java/pl/edu/agh/dsm/sensor/Sensor.java
wysekm/DistributedSystemMonitoring
6a643b614c5cc308d414fa35646ef8a02305a1fc
[ "BSD-3-Clause" ]
null
null
null
33.275
108
0.695342
13,445
package pl.edu.agh.dsm.sensor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.edu.agh.dsm.sensor.monitored.MonitoredFactory; import pl.edu.agh.dsm.sensor.monitored.MonitoringException; import pl.edu.agh.dsm.sensor.udp.SensorSocket; import java.io.IOException; import java.util.concurrent.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Sensor { private static final Logger log = LoggerFactory.getLogger(Sensor.class); private static final ScheduledExecutorService es = Executors .newScheduledThreadPool(4); // TODO public static void main(String[] args) { if (args.length < 3) { System.out .println("Usage: sensor <monitor address> <resource> <metric> <time ms> [<metric> <time ms> [ ... ]]"); log.error("Not enough arguments supplied."); System.exit(1); } String ipPort = args[0]; String resourceName = args[1]; Pattern pattern = Pattern.compile("(\\d+\\.\\d+\\.\\d+\\.\\d+):(\\d+)"); Matcher matcher = pattern.matcher(ipPort); if (!matcher.matches()) { System.out.println("Malformed monitor address."); log.error("Monitor address did not match basic ip:port regex."); System.exit(1); } String ip = matcher.group(1); String port = matcher.group(2); SensorConfiguration sensorConfiguration = new SensorConfiguration(); sensorConfiguration.setResource(resourceName); try { startSensors(args, sensorConfiguration, new SensorSocket(ip, Integer.parseInt(port))); } catch (IOException ex) { log.error("IOException caught while creating SensorSocket: ", ex); } log.info("Startup completed."); } private static void startSensors(String[] args, SensorConfiguration sensorConfiguration, SensorSocket sensorSocket) { log.trace("Starting sensors."); MonitoredFactory factory = new MonitoredFactory(); for (int i = 2; i < args.length; i += 2) { log.info("Starting sensor for metric " + args[i]); try { SensorThread thread = new SensorThread( factory.createMonitoredResource(args[i]), sensorConfiguration, sensorSocket); es.scheduleAtFixedRate(thread, 0, Integer.parseInt(args[i + 1]), TimeUnit.MILLISECONDS); } catch (MonitoringException ex) { log.error( "MonitoringException caught while starting sensor for metric " + args[i] + ": ", ex); } catch (IndexOutOfBoundsException ex) { log.error( "IndexOutOfBoundsException caught while starting sensor for metric " + args[i] + ": ", ex); } catch (NumberFormatException ex) { log.error( "NumberFormatException caught while starting sensor for metric " + args[i] + ": ", ex); } } } }
3e1fd37c99e395fb3ab543b0fa307c3c27571093
382
java
Java
Creational Design Patterns/Singleton Pattern/LazyInstantiation/Normal Approach/Singleton.java
AbhilashG97/WatermelonPudding
41dd91ccfb1c8b09ab1ff919024b6fb8efb28030
[ "MIT" ]
1
2019-12-10T16:32:43.000Z
2019-12-10T16:32:43.000Z
Creational Design Patterns/Singleton Pattern/LazyInstantiation/Normal Approach/Singleton.java
AbhilashG97/WatermelonPudding
41dd91ccfb1c8b09ab1ff919024b6fb8efb28030
[ "MIT" ]
null
null
null
Creational Design Patterns/Singleton Pattern/LazyInstantiation/Normal Approach/Singleton.java
AbhilashG97/WatermelonPudding
41dd91ccfb1c8b09ab1ff919024b6fb8efb28030
[ "MIT" ]
null
null
null
19.1
49
0.570681
13,446
public class Singleton { private static Singleton instance; private Singleton() { // default private method } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } public void doSomething() { System.out.println("Do something here."); } }
3e1fd4a7a4fde250aa2c8eaf86242e5709e9c1dc
632
java
Java
src/main/java/x/nullpointer/simplegraphtag/utils/SystemUtils.java
p00temkin/simplegraphtag
ed02a52a2dff4759ba44ab4f4455bad431745891
[ "Apache-2.0" ]
null
null
null
src/main/java/x/nullpointer/simplegraphtag/utils/SystemUtils.java
p00temkin/simplegraphtag
ed02a52a2dff4759ba44ab4f4455bad431745891
[ "Apache-2.0" ]
null
null
null
src/main/java/x/nullpointer/simplegraphtag/utils/SystemUtils.java
p00temkin/simplegraphtag
ed02a52a2dff4759ba44ab4f4455bad431745891
[ "Apache-2.0" ]
null
null
null
25.28
187
0.598101
13,447
package x.nullpointer.simplegraphtag.utils; public class SystemUtils { public static void halt() { System.exit(1); } public static String getSystemInformation() { String systemInfo = System.getProperty("java.vendor") + " " + System.getProperty("java.version") + " on " + System.getProperty("os.name") + " " + System.getProperty("os.version"); return systemInfo; } public static String getQuote() { return ""; } public static void sleepInSeconds(int i) { try { Thread.sleep(i*1000); } catch (InterruptedException e) { } } }
3e1fd5465f616620c2647761134e54616b1a6ac5
9,974
java
Java
src/main/java/org/hijizhou/utilities/WalkBar.java
MicroscPSF/MicroscPSF-ImageJ
4383a3edb6513aea749aab8166721a726f1d763e
[ "MIT" ]
3
2019-02-19T06:17:20.000Z
2020-01-09T09:55:29.000Z
src/main/java/org/hijizhou/utilities/WalkBar.java
MicroscPSF/MicroscPSF-ImageJ
4383a3edb6513aea749aab8166721a726f1d763e
[ "MIT" ]
1
2019-05-28T06:09:27.000Z
2019-05-29T22:26:55.000Z
src/main/java/org/hijizhou/utilities/WalkBar.java
MicroscPSF/MicroscPSF-ImageJ
4383a3edb6513aea749aab8166721a726f1d763e
[ "MIT" ]
null
null
null
31.865815
699
0.635853
13,448
package org.hijizhou.utilities; import javax.swing.*; import javax.swing.text.DefaultCaret; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class WalkBar extends JToolBar implements ActionListener { private JProgressBar progress = new JProgressBar(); private JButton bnHelp = new JButton("Help"); private JButton bnAbout = new JButton("About"); private JButton bnClose = new JButton("Close"); private String[] about = { "About", "Version", "Description", "Author", "Biomedical Image Group", "2008", "http://bigwww.epfl.ch" }; private String help; private double chrono; private int xSizeAbout = 400; private int ySizeAbout = 400; private int xSizeHelp = 400; private int ySizeHelp = 400; private static class SetValue implements Runnable { private int value; private JProgressBar progress; public SetValue(JProgressBar progress, int value) { this.progress = progress; this.value = value; } public void run() { this.progress.setValue(this.value); } } private static class IncValue implements Runnable { private double inc; private JProgressBar progress; public IncValue(JProgressBar progress, double inc) { this.progress = progress; this.inc = inc; } public void run() { this.progress.setValue((int)Math.round(this.progress.getValue() + this.inc)); } } private static class SetMessage implements Runnable { private String msg; private JProgressBar progress; public SetMessage(JProgressBar progress, String msg) { this.progress = progress; this.msg = msg; } public void run() { this.progress.setString(this.msg); } } public WalkBar() { super("Walk Bar"); build("", false, false, false, 100); } public WalkBar(String initialMessage, boolean isAbout, boolean isHelp, boolean isClose) { super("Walk Bar"); build(initialMessage, isAbout, isHelp, isClose, 100); } public WalkBar(String initialMessage, boolean isAbout, boolean isHelp, boolean isClose, int size) { super("Walk Bar"); build(initialMessage, isAbout, isHelp, isClose, size); } private void build(String initialMessage, boolean isAbout, boolean isHelp, boolean isClose, int size) { if (isAbout) { add(this.bnAbout); } if (isHelp) { add(this.bnHelp); } addSeparator(); add(this.progress); addSeparator(); if (isClose) { add(this.bnClose); } this.progress.setStringPainted(true); this.progress.setString(initialMessage); this.progress.setMinimum(0); this.progress.setMaximum(100); this.progress.setPreferredSize(new Dimension(size, 20)); this.bnAbout.addActionListener(this); this.bnHelp.addActionListener(this); setFloatable(false); setRollover(true); setBorderPainted(false); this.chrono = System.currentTimeMillis(); } public synchronized void actionPerformed(ActionEvent e) { if (e.getSource() == this.bnHelp) { showHelp(); } else if (e.getSource() == this.bnAbout) { showAbout(); } else { e.getSource(); } } public JButton getButtonClose() { return this.bnClose; } public void progress(String msg, int value) { double elapsedTime = System.currentTimeMillis() - this.chrono; String t = " [" + (elapsedTime > 3000.0D ? Math.round(elapsedTime / 10.0D) / 100.0D + "s." : new StringBuilder(String.valueOf(elapsedTime)).append("ms").toString()) + "]"; SwingUtilities.invokeLater(new SetValue(this.progress, value)); SwingUtilities.invokeLater(new SetMessage(this.progress, msg + t)); } public void increment(double inc) { SwingUtilities.invokeLater(new IncValue(this.progress, inc)); } public void setValue(int value) { SwingUtilities.invokeLater(new SetValue(this.progress, value)); } public void setMessage(String msg) { SwingUtilities.invokeLater(new SetMessage(this.progress, msg)); } public void progress(String msg, double value) { progress(msg, (int)Math.round(value)); } public void reset() { this.chrono = System.currentTimeMillis(); progress("Start", 0); } public void finish() { progress("End", 100); } public void finish(String msg) { progress(msg, 100); } public void fillAbout(String name, String version, String description, String author, String organisation, String date, String info) { this.about[0] = name; this.about[1] = version; this.about[2] = description; this.about[3] = author; this.about[4] = organisation; this.about[5] = date; this.about[6] = info; } public void fillHelp(String help) { this.help = help; } public void showAbout() { final JFrame frame = new JFrame("About " + this.about[0]); JEditorPane pane = new JEditorPane(); pane.setEditable(false); pane.setContentType("text/html; charset=ISO-8859-1"); pane.setText("<html><head><title>" + this.about[0] + "</title>" + getStyle() + "</head><body>" + ( this.about[0] == "" ? "" : new StringBuilder("<p class=\"name\">").append(this.about[0]).append("</p>").toString()) + ( this.about[1] == "" ? "" : new StringBuilder("<p class=\"vers\">").append(this.about[1]).append("</p>").toString()) + ( this.about[2] == "" ? "" : new StringBuilder("<p class=\"desc\">").append(this.about[2]).append("</p><hr>").toString()) + ( this.about[3] == "" ? "" : new StringBuilder("<p class=\"auth\">").append(this.about[3]).append("</p>").toString()) + ( this.about[4] == "" ? "" : new StringBuilder("<p class=\"orga\">").append(this.about[4]).append("</p>").toString()) + ( this.about[5] == "" ? "" : new StringBuilder("<p class=\"date\">").append(this.about[5]).append("</p>").toString()) + ( this.about[6] == "" ? "" : new StringBuilder("<p class=\"more\">").append(this.about[6]).append("</p>").toString()) + "</html>"); JButton bnClose = new JButton("Close"); bnClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); } }); pane.setCaret(new DefaultCaret()); JScrollPane scrollPane = new JScrollPane(pane); scrollPane.setPreferredSize(new Dimension(this.xSizeAbout, this.ySizeAbout)); frame.getContentPane().add(scrollPane, "North"); frame.getContentPane().add(bnClose, "Center"); frame.pack(); frame.setResizable(false); frame.setVisible(true); center(frame); } public void showHelp() { final JFrame frame = new JFrame("Help " + this.about[0]); JEditorPane pane = new JEditorPane(); pane.setEditable(false); pane.setContentType("text/html; charset=ISO-8859-1"); pane.setText("<html><head><title>" + this.about[0] + "</title>" + getStyle() + "</head><body>" + ( this.about[0] == "" ? "" : new StringBuilder("<p class=\"name\">").append(this.about[0]).append("</p>").toString()) + ( this.about[1] == "" ? "" : new StringBuilder("<p class=\"vers\">").append(this.about[1]).append("</p>").toString()) + ( this.about[2] == "" ? "" : new StringBuilder("<p class=\"desc\">").append(this.about[2]).append("</p>").toString()) + "<hr><p class=\"help\">" + this.help + "</p>" + "</html>"); JButton bnClose = new JButton("Close"); bnClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); } }); pane.setCaret(new DefaultCaret()); JScrollPane scrollPane = new JScrollPane(pane); scrollPane.setVerticalScrollBarPolicy(22); scrollPane.setPreferredSize(new Dimension(this.xSizeHelp, this.ySizeHelp)); frame.setPreferredSize(new Dimension(this.xSizeHelp, this.ySizeHelp)); frame.getContentPane().add(scrollPane, "Center"); frame.getContentPane().add(bnClose, "South"); frame.setVisible(true); frame.pack(); center(frame); } private void center(Window w) { Dimension screenSize = new Dimension(0, 0); boolean isWin = System.getProperty("os.name").startsWith("Windows"); if (isWin) { screenSize = Toolkit.getDefaultToolkit().getScreenSize(); } if (GraphicsEnvironment.isHeadless()) { screenSize = new Dimension(0, 0); } else { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gd = ge.getScreenDevices(); GraphicsConfiguration[] gc = gd[0].getConfigurations(); Rectangle bounds = gc[0].getBounds(); if ((bounds.x == 0) && (bounds.y == 0)) { screenSize = new Dimension(bounds.width, bounds.height); } else { screenSize = Toolkit.getDefaultToolkit().getScreenSize(); } } Dimension window = w.getSize(); if (window.width == 0) { return; } int left = screenSize.width / 2 - window.width / 2; int top = (screenSize.height - window.height) / 4; if (top < 0) { top = 0; } w.setLocation(left, top); } private String getStyle() { return "<style type=text/css>body {backgroud-color:#222277}hr {width:80% color:#333366; padding-top:7px }p, li {margin-left:10px;margin-right:10px; color:#000000; font-size:1em; font-family:Verdana,Helvetica,Arial,Geneva,Swiss,SunSans-Regular,sans-serif}p.name {color:#ffffff; font-size:1.2em; font-weight: bold; background-color: #333366; text-align:center;}p.vers {color:#333333; text-align:center;}p.desc {color:#333333; font-weight: bold; text-align:center;}p.auth {color:#333333; font-style: italic; text-align:center;}p.orga {color:#333333; text-align:center;}p.date {color:#333333; text-align:center;}p.more {color:#333333; text-align:center;}p.help {color:#000000; text-align:left;}</style>"; } }
3e1fd603cd8c8f7eec710efebd6ef85cda352720
1,650
java
Java
components/camel-aws2-sns/src/main/java/org/apache/camel/component/aws2/sns/client/Sns2ClientFactory.java
DragoiNicolae/camel
9fbc54678680d2bf00b0004963f32a08bf4d0515
[ "Apache-2.0" ]
2
2017-10-05T19:28:46.000Z
2018-01-22T20:17:34.000Z
components/camel-aws2-sns/src/main/java/org/apache/camel/component/aws2/sns/client/Sns2ClientFactory.java
DragoiNicolae/camel
9fbc54678680d2bf00b0004963f32a08bf4d0515
[ "Apache-2.0" ]
null
null
null
components/camel-aws2-sns/src/main/java/org/apache/camel/component/aws2/sns/client/Sns2ClientFactory.java
DragoiNicolae/camel
9fbc54678680d2bf00b0004963f32a08bf4d0515
[ "Apache-2.0" ]
null
null
null
39.285714
104
0.74
13,449
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.aws2.sns.client; import org.apache.camel.component.aws2.sns.Sns2Configuration; import org.apache.camel.component.aws2.sns.client.impl.Sns2ClientIAMOptimized; import org.apache.camel.component.aws2.sns.client.impl.Sns2ClientStandardImpl; /** * Factory class to return the correct type of AWS SNS aws. */ public final class Sns2ClientFactory { private Sns2ClientFactory() { } /** * Return the correct aws SNS client (based on remote vs local). * * @param configuration configuration * @return SNSClient */ public static Sns2InternalClient getSnsClient(Sns2Configuration configuration) { return configuration.isUseIAMCredentials() ? new Sns2ClientIAMOptimized(configuration) : new Sns2ClientStandardImpl(configuration); } }
3e1fd68e305bf1ad4a55c1998ea11a9b58acdbc3
4,718
java
Java
sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/AliasExpressionParser.java
hkpxj/sharding-jdbc
9d1fe6d5ebcc089fb66c6bc58c20d24111bff150
[ "Apache-2.0" ]
1
2021-03-16T17:58:17.000Z
2021-03-16T17:58:17.000Z
sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/AliasExpressionParser.java
hkpxj/sharding-jdbc
9d1fe6d5ebcc089fb66c6bc58c20d24111bff150
[ "Apache-2.0" ]
null
null
null
sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/expression/AliasExpressionParser.java
hkpxj/sharding-jdbc
9d1fe6d5ebcc089fb66c6bc58c20d24111bff150
[ "Apache-2.0" ]
1
2021-03-16T17:58:46.000Z
2021-03-16T17:58:46.000Z
42.890909
197
0.72128
13,450
/* * Copyright 2016-2018 shardingsphere.io. * <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 * * 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. * </p> */ package io.shardingsphere.core.parsing.parser.clause.expression; import com.google.common.base.Optional; import io.shardingsphere.core.parsing.lexer.LexerEngine; import io.shardingsphere.core.parsing.lexer.token.DefaultKeyword; import io.shardingsphere.core.parsing.lexer.token.Literals; import io.shardingsphere.core.parsing.lexer.token.Symbol; import io.shardingsphere.core.parsing.lexer.token.TokenType; import io.shardingsphere.core.util.SQLUtil; import lombok.RequiredArgsConstructor; /** * Alias expression parser. * * @author zhangliang */ @RequiredArgsConstructor public class AliasExpressionParser { private final LexerEngine lexerEngine; /** * Parse alias for select item. * * @return alias for select item */ public Optional<String> parseSelectItemAlias() { if (lexerEngine.skipIfEqual(DefaultKeyword.AS)) { return parseWithAs(); } if (lexerEngine.equalAny(getDefaultAvailableKeywordsForSelectItemAlias()) || lexerEngine.equalAny(getCustomizedAvailableKeywordsForSelectItemAlias())) { return parseAlias(); } return Optional.absent(); } private Optional<String> parseWithAs() { if (lexerEngine.equalAny(Symbol.values())) { return Optional.absent(); } return parseAlias(); } private Optional<String> parseAlias() { String result = SQLUtil.getExactlyValue(lexerEngine.getCurrentToken().getLiterals()); lexerEngine.nextToken(); return Optional.of(result); } private TokenType[] getDefaultAvailableKeywordsForSelectItemAlias() { return new TokenType[] { Literals.IDENTIFIER, Literals.CHARS, DefaultKeyword.BITMAP, DefaultKeyword.NOSORT, DefaultKeyword.REVERSE, DefaultKeyword.COMPILE, DefaultKeyword.NEW, DefaultKeyword.ADVISE, DefaultKeyword.AVG, DefaultKeyword.MAX, DefaultKeyword.MIN, DefaultKeyword.SUM, DefaultKeyword.COUNT, DefaultKeyword.ROUND, DefaultKeyword.TRUNC, DefaultKeyword.LENGTH, DefaultKeyword.CHAR_LENGTH, DefaultKeyword.SUBSTR, DefaultKeyword.INSTR, DefaultKeyword.INITCAP, DefaultKeyword.UPPER, DefaultKeyword.LOWER, DefaultKeyword.LTRIM, DefaultKeyword.RTRIM, DefaultKeyword.TRANSLATE, DefaultKeyword.LPAD, DefaultKeyword.RPAD, DefaultKeyword.DECODE, DefaultKeyword.NVL, }; } protected TokenType[] getCustomizedAvailableKeywordsForSelectItemAlias() { return new TokenType[0]; } /** * Parse alias for table. * * @return alias for table */ public Optional<String> parseTableAlias() { if (lexerEngine.skipIfEqual(DefaultKeyword.AS)) { return parseWithAs(); } if (lexerEngine.equalAny(getDefaultAvailableKeywordsForTableAlias()) || lexerEngine.equalAny(getCustomizedAvailableKeywordsForTableAlias())) { return parseAlias(); } return Optional.absent(); } private TokenType[] getDefaultAvailableKeywordsForTableAlias() { return new TokenType[] { Literals.IDENTIFIER, Literals.CHARS, DefaultKeyword.SEQUENCE, DefaultKeyword.NO, DefaultKeyword.AFTER, DefaultKeyword.BITMAP, DefaultKeyword.NOSORT, DefaultKeyword.REVERSE, DefaultKeyword.COMPILE, DefaultKeyword.ENABLE, DefaultKeyword.DISABLE, DefaultKeyword.NEW, DefaultKeyword.UNTIL, DefaultKeyword.ADVISE, DefaultKeyword.PASSWORD, DefaultKeyword.LOCAL, DefaultKeyword.GLOBAL, DefaultKeyword.STORAGE, DefaultKeyword.DATA, DefaultKeyword.TIME, DefaultKeyword.BOOLEAN, DefaultKeyword.GREATEST, DefaultKeyword.LEAST, DefaultKeyword.ROUND, DefaultKeyword.TRUNC, DefaultKeyword.POSITION, DefaultKeyword.LENGTH, DefaultKeyword.CHAR_LENGTH, DefaultKeyword.SUBSTRING, DefaultKeyword.SUBSTR, DefaultKeyword.INSTR, DefaultKeyword.INITCAP, DefaultKeyword.UPPER, DefaultKeyword.LOWER, DefaultKeyword.TRIM, }; } protected TokenType[] getCustomizedAvailableKeywordsForTableAlias() { return new TokenType[0]; } }
3e1fd6eae78dba9704b4aa7165d8e0cc1b94cc7c
826
java
Java
gsl/src/gen/java/org/bytedeco/gsl/gsl_siman_copy_t.java
drieks/javacpp-presets
d18c14cee40e8c313d194d208c1a8b132ac0de51
[ "Apache-2.0" ]
null
null
null
gsl/src/gen/java/org/bytedeco/gsl/gsl_siman_copy_t.java
drieks/javacpp-presets
d18c14cee40e8c313d194d208c1a8b132ac0de51
[ "Apache-2.0" ]
null
null
null
gsl/src/gen/java/org/bytedeco/gsl/gsl_siman_copy_t.java
drieks/javacpp-presets
d18c14cee40e8c313d194d208c1a8b132ac0de51
[ "Apache-2.0" ]
1
2021-01-22T05:22:30.000Z
2021-01-22T05:22:30.000Z
34.416667
78
0.746973
13,451
// Targeted by JavaCPP version 1.5.3: DO NOT EDIT THIS FILE package org.bytedeco.gsl; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.openblas.global.openblas_nolapack.*; import static org.bytedeco.openblas.global.openblas.*; import static org.bytedeco.gsl.global.gsl.*; @Properties(inherit = org.bytedeco.gsl.presets.gsl.class) public class gsl_siman_copy_t extends FunctionPointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public gsl_siman_copy_t(Pointer p) { super(p); } protected gsl_siman_copy_t() { allocate(); } private native void allocate(); public native void call(Pointer source, Pointer dest); }
3e1fd93758923d58230bebf9d422896db37b5a3e
1,862
java
Java
EvolvedDecisions/src/main/java/evolved/genetics/GeneticDatabase.java
rosspalmer/Evolved-Decisions
8bff846db9c1a8322d4d2c1200d8abad206f684f
[ "MIT" ]
null
null
null
EvolvedDecisions/src/main/java/evolved/genetics/GeneticDatabase.java
rosspalmer/Evolved-Decisions
8bff846db9c1a8322d4d2c1200d8abad206f684f
[ "MIT" ]
null
null
null
EvolvedDecisions/src/main/java/evolved/genetics/GeneticDatabase.java
rosspalmer/Evolved-Decisions
8bff846db9c1a8322d4d2c1200d8abad206f684f
[ "MIT" ]
null
null
null
29.555556
119
0.670247
13,452
package evolved.genetics; import evolved.graph.Node; import evolved.graph.NodeDatabase; import evolved.graph.NodeRelationship; import evolved.graph.NodeSearch; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class GeneticDatabase extends NodeDatabase { public void addGeneList(List<GeneNode> geneList) { Node previousNode = geneList.get(0); if (containsNode(previousNode)) { previousNode = getNode(previousNode.getNodeId()); } else { addNode(previousNode); } for (int i=1; i < geneList.size(); i++) { Node nextNode = geneList.get(i); if (containsNode(nextNode)) { nextNode = getNode(nextNode.getNodeId()); } else { addNode(nextNode); } previousNode.addRelatedNodes(NodeRelationship.PATH_TO, nextNode); } } public void addSpecies(SpeciesNode speciesNode, Set<GeneNode> geneNodeSet, GeneNode startGeneNode) { Set<Node> speciesGeneNodes = getNodes().stream() .filter(geneNodeSet::contains) .collect(Collectors.toSet()); speciesGeneNodes.forEach(node -> speciesNode.addRelatedNodes(NodeRelationship.SPECIES_GENES, node)); speciesNode.addRelatedNodes(NodeRelationship.SPECIES_START_GENE, startGeneNode); addNode(speciesNode); } public List<GeneNode> getSpeciesGeneList(SpeciesNode speciesNode) { Node startGeneNode = speciesNode.getRelatedNodes(NodeRelationship.SPECIES_START_GENE).stream().findAny().get(); Set<Node> speciesGeneNodeSet = speciesNode.getRelatedNodes(NodeRelationship.SPECIES_GENES); List<GeneNode> orderGeneNodeList = NodeSearch.getNodePath(startGeneNode, speciesGeneNodeSet) .stream().map(); } }
3e1fd9a221259ea8a98769da31ee4d614893f71e
530
java
Java
android/src/net/big2/pushnotify/PushNotifyDroidGap.java
kctang/cordova-push-notify-demo
e221d118f839438d01b32b82f716962c2c361520
[ "MIT" ]
2
2015-06-23T07:55:14.000Z
2015-08-23T20:28:47.000Z
android/src/net/big2/pushnotify/PushNotifyDroidGap.java
kctang/cordova-push-notify-demo
e221d118f839438d01b32b82f716962c2c361520
[ "MIT" ]
null
null
null
android/src/net/big2/pushnotify/PushNotifyDroidGap.java
kctang/cordova-push-notify-demo
e221d118f839438d01b32b82f716962c2c361520
[ "MIT" ]
null
null
null
27.894737
63
0.696226
13,453
package net.big2.pushnotify; import android.os.Bundle; import org.apache.cordova.Config; import org.apache.cordova.DroidGap; // TODO: review & refactor! public class PushNotifyDroidGap extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set by <content src="index.html" /> in config.xml super.loadUrl(Config.getStartUrl()); //super.loadUrl("file:///android_asset/www/index.html") // TODO: call handlePush } }
3e1fd9a6127cc1c18a6583611e42cc834d7e2bc2
1,483
java
Java
Example/src/main/java/com/vechain/walletdemo/view/adapter/ItemViewDelegate.java
zacharyruss40/wallet-Android-sdk
67b579180ff6f834568ce680dc1a9ef680b7afa2
[ "MIT" ]
18
2019-07-29T12:14:01.000Z
2022-03-03T21:18:26.000Z
Example/src/main/java/com/vechain/walletdemo/view/adapter/ItemViewDelegate.java
NIKOLAY733/wallet-Android-sdk
9d037741eb39981812712c82ed25d4d945f9e140
[ "MIT" ]
null
null
null
Example/src/main/java/com/vechain/walletdemo/view/adapter/ItemViewDelegate.java
NIKOLAY733/wallet-Android-sdk
9d037741eb39981812712c82ed25d4d945f9e140
[ "MIT" ]
19
2019-07-29T10:37:48.000Z
2022-01-13T01:34:45.000Z
51.206897
463
0.779798
13,454
/* * Vechain Wallet SDK is licensed under the MIT LICENSE, also included in LICENSE file in the repository. * * Copyright (c) 2019 VeChain nnheo@example.com * * 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.vechain.walletdemo.view.adapter; public interface ItemViewDelegate<T> { public abstract int getItemViewLayoutId(); public abstract boolean isForViewType(T item, int position); public abstract void convert(ViewHolder holder, T t, int position); }
3e1fda0db583695203cf0e3689bdb6c136006093
342
java
Java
src/demo/java/com/demo/amplitude/Demo.java
bohan-amplitude/Amplitude-Java
06743fac112aefedc6b1668195872f75e578e73d
[ "MIT" ]
4
2021-09-14T06:30:46.000Z
2022-02-16T12:18:24.000Z
src/demo/java/com/demo/amplitude/Demo.java
bohan-amplitude/Amplitude-Java
06743fac112aefedc6b1668195872f75e578e73d
[ "MIT" ]
25
2021-04-12T18:27:28.000Z
2022-03-31T23:45:43.000Z
src/demo/java/com/demo/amplitude/Demo.java
bohan-amplitude/Amplitude-Java
06743fac112aefedc6b1668195872f75e578e73d
[ "MIT" ]
7
2021-05-14T03:29:08.000Z
2022-01-17T06:23:24.000Z
26.307692
68
0.78655
13,455
package com.demo.amplitude; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Demo { public static void main(String[] args) { System.out.println("Running Amplitude Java Demo"); SpringApplication.run(Demo.class, args); } }