instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class TextToSpeechController { private final TextToSpeechService textToSpeechService; @Autowired public TextToSpeechController(TextToSpeechService textToSpeechService) { this.textToSpeechService = textToSpeechService; } @GetMapping("/text-to-speech-customized") public ResponseEntity<byte[]> generateSpeechForTextCustomized(@RequestParam("text") String text, @RequestParam Map<String, String> params) { OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder() .model(params.get("model")) .voice(OpenAiAudioApi.SpeechRequest.Voice.valueOf(params.get("voice"))) .responseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.valueOf(params.get("responseFormat"))) .speed(Float.parseFloat(params.get("speed"))) .build(); return ResponseEntity.ok(textToSpeechService.makeSpeech(text, speechOptions)); } @GetMapping("/text-to-speech") public ResponseEntity<byte[]> generateSpeechForText(@RequestParam("text") String text) { return ResponseEntity.ok(textToSpeechService.makeSpeech(text)); } @GetMapping(value = "/text-to-speech-stream", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public ResponseEntity<StreamingResponseBody> streamSpeech(@RequestParam("text") String text) {
Flux<byte[]> audioStream = textToSpeechService.makeSpeechStream(text); StreamingResponseBody responseBody = outputStream -> { audioStream.toStream().forEach(bytes -> { try { outputStream.write(bytes); outputStream.flush(); } catch (IOException e) { throw new UncheckedIOException(e); } }); }; return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(responseBody); } }
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springai\transcribe\controllers\TextToSpeechController.java
2
请在Spring Boot框架中完成以下Java代码
public class RestTemplateFactory implements FactoryBean<RestTemplate>, InitializingBean { private RestTemplate restTemplate; public RestTemplateFactory() { super(); } // API @Override public RestTemplate getObject() { return restTemplate; } @Override public Class<RestTemplate> getObjectType() { return RestTemplate.class;
} @Override public boolean isSingleton() { return true; } @Override public void afterPropertiesSet() { HttpHost host = new HttpHost("localhost", 8082, "http"); final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host); restTemplate = new RestTemplate(requestFactory); restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass")); } }
repos\tutorials-master\apache-httpclient4\src\main\java\com\baeldung\client\RestTemplateFactory.java
2
请完成以下Java代码
protected LdapUserDetailsImpl createTarget() { return new InetOrgPerson(); } public void setMail(String email) { ((InetOrgPerson) this.instance).mail = email; } public void setUid(String uid) { ((InetOrgPerson) this.instance).uid = uid; if (this.instance.getUsername() == null) { setUsername(uid); } } public void setInitials(String initials) { ((InetOrgPerson) this.instance).initials = initials; } public void setO(String organization) { ((InetOrgPerson) this.instance).o = organization; } public void setOu(String ou) { ((InetOrgPerson) this.instance).ou = ou; } public void setRoomNumber(String no) { ((InetOrgPerson) this.instance).roomNumber = no; } public void setTitle(String title) { ((InetOrgPerson) this.instance).title = title; } public void setCarLicense(String carLicense) { ((InetOrgPerson) this.instance).carLicense = carLicense; } public void setDepartmentNumber(String departmentNumber) { ((InetOrgPerson) this.instance).departmentNumber = departmentNumber; } public void setDisplayName(String displayName) { ((InetOrgPerson) this.instance).displayName = displayName; } public void setEmployeeNumber(String no) { ((InetOrgPerson) this.instance).employeeNumber = no; } public void setDestinationIndicator(String destination) { ((InetOrgPerson) this.instance).destinationIndicator = destination; } public void setHomePhone(String homePhone) {
((InetOrgPerson) this.instance).homePhone = homePhone; } public void setStreet(String street) { ((InetOrgPerson) this.instance).street = street; } public void setPostalCode(String postalCode) { ((InetOrgPerson) this.instance).postalCode = postalCode; } public void setPostalAddress(String postalAddress) { ((InetOrgPerson) this.instance).postalAddress = postalAddress; } public void setMobile(String mobile) { ((InetOrgPerson) this.instance).mobile = mobile; } public void setHomePostalAddress(String homePostalAddress) { ((InetOrgPerson) this.instance).homePostalAddress = homePostalAddress; } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\InetOrgPerson.java
1
请完成以下Java代码
public boolean shouldPerformAuthorizatioCheck() { return shouldPerformAuthorizatioCheck; } /** is used by myBatis */ public boolean getShouldPerformAuthorizatioCheck() { return isAuthorizationCheckEnabled && !isPermissionChecksEmpty(); } public void setShouldPerformAuthorizatioCheck(boolean shouldPerformAuthorizatioCheck) { this.shouldPerformAuthorizatioCheck = shouldPerformAuthorizatioCheck; } protected boolean isPermissionChecksEmpty() { return permissionChecks.getAtomicChecks().isEmpty() && permissionChecks.getCompositeChecks().isEmpty(); } public String getAuthUserId() { return authUserId; } public void setAuthUserId(String authUserId) { this.authUserId = authUserId; } public List<String> getAuthGroupIds() { return authGroupIds; } public void setAuthGroupIds(List<String> authGroupIds) { this.authGroupIds = authGroupIds; } public int getAuthDefaultPerm() { return authDefaultPerm; } public void setAuthDefaultPerm(int authDefaultPerm) { this.authDefaultPerm = authDefaultPerm; } // authorization check parameters public CompositePermissionCheck getPermissionChecks() { return permissionChecks; } public void setAtomicPermissionChecks(List<PermissionCheck> permissionChecks) { this.permissionChecks.setAtomicChecks(permissionChecks); } public void addAtomicPermissionCheck(PermissionCheck permissionCheck) { permissionChecks.addAtomicCheck(permissionCheck); } public void setPermissionChecks(CompositePermissionCheck permissionChecks) { this.permissionChecks = permissionChecks; }
public boolean isRevokeAuthorizationCheckEnabled() { return isRevokeAuthorizationCheckEnabled; } public void setRevokeAuthorizationCheckEnabled(boolean isRevokeAuthorizationCheckEnabled) { this.isRevokeAuthorizationCheckEnabled = isRevokeAuthorizationCheckEnabled; } public void setHistoricInstancePermissionsEnabled(boolean historicInstancePermissionsEnabled) { this.historicInstancePermissionsEnabled = historicInstancePermissionsEnabled; } /** * Used in SQL mapping */ public boolean isHistoricInstancePermissionsEnabled() { return historicInstancePermissionsEnabled; } public boolean isUseLeftJoin() { return useLeftJoin; } public void setUseLeftJoin(boolean useLeftJoin) { this.useLeftJoin = useLeftJoin; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\AuthorizationCheck.java
1
请完成以下Java代码
public static String getApplicationPathByProcessDefinitionId(ProcessEngine engine, String processDefinitionId) { ProcessDefinition processDefinition = engine.getRepositoryService().getProcessDefinition(processDefinitionId); if (processDefinition == null) { return null; } return getApplicationPathForDeployment(engine, processDefinition.getDeploymentId()); } public static String getApplicationPathByCaseDefinitionId(ProcessEngine engine, String caseDefinitionId) { CaseDefinition caseDefinition = engine.getRepositoryService().getCaseDefinition(caseDefinitionId); if (caseDefinition == null) { return null; } return getApplicationPathForDeployment(engine, caseDefinition.getDeploymentId()); } public static String getApplicationPathForDeployment(ProcessEngine engine, String deploymentId) { // get the name of the process application that made the deployment String processApplicationName = null; IdentityService identityService = engine.getIdentityService(); Authentication currentAuthentication = identityService.getCurrentAuthentication(); try { identityService.clearAuthentication();
processApplicationName = engine.getManagementService().getProcessApplicationForDeployment(deploymentId); } finally { identityService.setAuthentication(currentAuthentication); } if (processApplicationName == null) { // no a process application deployment return null; } else { ProcessApplicationService processApplicationService = BpmPlatform.getProcessApplicationService(); ProcessApplicationInfo processApplicationInfo = processApplicationService.getProcessApplicationInfo(processApplicationName); return processApplicationInfo.getProperties().get(ProcessApplicationInfo.PROP_SERVLET_CONTEXT_PATH); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\util\ApplicationContextPathUtil.java
1
请在Spring Boot框架中完成以下Java代码
public MessageChannel fileChannel() { return new DirectChannel(); } @Bean @InboundChannelAdapter(value = "fileChannel", poller = @Poller(fixedDelay = "10000")) public MessageSource<File> fileReadingMessageSource() { FileReadingMessageSource sourceReader = new FileReadingMessageSource(); sourceReader.setDirectory(new File(INPUT_DIR)); sourceReader.setFilter(new SimplePatternFileListFilter(FILE_PATTERN)); return sourceReader; } @Bean @ServiceActivator(inputChannel = "fileChannel") public MessageHandler fileWritingMessageHandler() { FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR)); handler.setFileExistsMode(FileExistsMode.REPLACE); handler.setExpectReply(false); return handler; } public static void main(final String... args) { final AbstractApplicationContext context = new AnnotationConfigApplicationContext(FileCopyConfig.class); context.registerShutdownHook();
final Scanner scanner = new Scanner(System.in); System.out.print("Please enter a string and press <enter>: "); while (true) { final String input = scanner.nextLine(); if ("q".equals(input.trim())) { context.close(); scanner.close(); break; } } System.exit(0); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\samples\FileCopyConfig.java
2
请在Spring Boot框架中完成以下Java代码
public CookieRememberMeManager rememberMeManager() { //System.out.println("ShiroConfiguration.rememberMeManager()"); CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); cookieRememberMeManager.setCookie(rememberMeCookie()); return cookieRememberMeManager; } @Bean(name = "sessionManager") public DefaultWebSessionManager defaultWebSessionManager() { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setGlobalSessionTimeout(18000000); // url中是否显示session Id sessionManager.setSessionIdUrlRewritingEnabled(false); // 删除失效的session sessionManager.setDeleteInvalidSessions(true); sessionManager.setSessionValidationSchedulerEnabled(true); sessionManager.setSessionValidationInterval(18000000); sessionManager.setSessionValidationScheduler(getExecutorServiceSessionValidationScheduler()); //设置SessionIdCookie 导致认证不成功,不从新设置新的cookie,从sessionManager获取sessionIdCookie //sessionManager.setSessionIdCookie(simpleIdCookie()); sessionManager.getSessionIdCookie().setName("session-z-id"); sessionManager.getSessionIdCookie().setPath("/");
sessionManager.getSessionIdCookie().setMaxAge(60 * 60 * 24 * 7); return sessionManager; } @Bean(name = "sessionValidationScheduler") public ExecutorServiceSessionValidationScheduler getExecutorServiceSessionValidationScheduler() { ExecutorServiceSessionValidationScheduler scheduler = new ExecutorServiceSessionValidationScheduler(); scheduler.setInterval(900000); return scheduler; } @Bean(name = "shiroDialect") public ShiroDialect shiroDialect() { return new ShiroDialect(); } }
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\config\ShiroConfig.java
2
请完成以下Java代码
public void checkTenantEntity(EntityId entityId) throws TbNodeException { TenantId actualTenantId = TenantIdLoader.findTenantId(this, entityId); if (!getTenantId().equals(actualTenantId)) { throw new TbNodeException("Entity with id: '" + entityId + "' specified in the configuration doesn't belong to the current tenant.", true); } } @Override public <E extends HasId<I> & HasTenantId, I extends EntityId> void checkTenantOrSystemEntity(E entity) throws TbNodeException { TenantId actualTenantId = entity.getTenantId(); if (!getTenantId().equals(actualTenantId) && !actualTenantId.isSysTenantId()) { throw new TbNodeException("Entity with id: '" + entity.getId() + "' specified in the configuration doesn't belong to the current or system tenant.", true); } } private static String getFailureMessage(Throwable th) { String failureMessage; if (th != null) { if (!StringUtils.isEmpty(th.getMessage())) { failureMessage = th.getMessage(); } else { failureMessage = th.getClass().getSimpleName(); } } else { failureMessage = null; } return failureMessage; }
private void persistDebugOutput(TbMsg msg, String relationType) { persistDebugOutput(msg, Set.of(relationType)); } private void persistDebugOutput(TbMsg msg, Set<String> relationTypes) { persistDebugOutput(msg, relationTypes, null, null); } private void persistDebugOutput(TbMsg msg, Set<String> relationTypes, Throwable error, String failureMessage) { RuleNode ruleNode = nodeCtx.getSelf(); if (DebugModeUtil.isDebugAllAvailable(ruleNode)) { relationTypes.forEach(relationType -> mainCtx.persistDebugOutput(getTenantId(), ruleNode.getId(), msg, relationType, error, failureMessage)); } else if (DebugModeUtil.isDebugFailuresAvailable(ruleNode, relationTypes)) { mainCtx.persistDebugOutput(getTenantId(), ruleNode.getId(), msg, TbNodeConnectionType.FAILURE, error, failureMessage); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\DefaultTbContext.java
1
请完成以下Java代码
public void setValue(ELContext context, Object base, Object property, Object value) throws PropertyNotWritableException { if (resolve(context, base, property)) { if (readOnly) { throw new PropertyNotWritableException("Resolver is read only!"); } setProperty((String) property, value); } } @Override public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if (resolve(context, base, method)) { throw new NullPointerException("Cannot invoke method " + method + " on null"); } return null; } /** * Get property value * * @param property * property name * @return value associated with the given property */ public Object getProperty(String property) { return map.get(property); } /** * Set property value * * @param property * property name * @param value * property value */ public void setProperty(String property, Object value) { map.put(property, value); }
/** * Test property * * @param property * property name * @return <code>true</code> if the given property is associated with a value */ public boolean isProperty(String property) { return map.containsKey(property); } /** * Get properties * * @return all property names (in no particular order) */ public Iterable<String> properties() { return map.keySet(); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\RootPropertyResolver.java
1
请在Spring Boot框架中完成以下Java代码
public class MultipleAuthProvidersSecurityConfig { @Autowired CustomAuthenticationProvider customAuthProvider; @Bean public AuthenticationManager authManager(HttpSecurity http) throws Exception { AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); authenticationManagerBuilder.authenticationProvider(customAuthProvider); authenticationManagerBuilder.inMemoryAuthentication() .withUser("memuser") .password(passwordEncoder().encode("pass")) .roles("USER"); return authenticationManagerBuilder.build(); }
@Bean public SecurityFilterChain filterChain(HttpSecurity http, AuthenticationManager authManager, HandlerMappingIntrospector introspector) throws Exception { MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); http.httpBasic(Customizer.withDefaults()) .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry .requestMatchers(PathRequest.toH2Console()).authenticated() .requestMatchers(mvcMatcherBuilder.pattern("/api/**")).authenticated()) .authenticationManager(authManager); return http.build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\java\com\baeldung\multipleauthproviders\MultipleAuthProvidersSecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class UserDao { @Autowired private MongoTemplate mongoTemplate; public void insert(UserDO entity) { mongoTemplate.insert(entity); } public void updateById(UserDO entity) { // 生成 Update 条件 final Update update = new Update(); // 反射遍历 entity 对象,将非空字段设置到 Update 中 ReflectionUtils.doWithFields(entity.getClass(), new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { // 排除指定条件 if ("id".equals(field.getName()) // 排除 id 字段,因为作为查询主键 || field.getAnnotation(Transient.class) != null // 排除 @Transient 注解的字段,因为非存储字段 || Modifier.isStatic(field.getModifiers())) { // 排除静态字段 return; } // 设置字段可反射 if (!field.isAccessible()) { field.setAccessible(true); } // 排除字段为空的情况 if (field.get(entity) == null) { return; } // 设置更新条件 update.set(field.getName(), field.get(entity)); } }); // 防御,避免有业务传递空的 Update 对象 if (update.getUpdateObject().isEmpty()) { return; }
// 执行更新 mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(entity.getId())), update, UserDO.class); } public void deleteById(Integer id) { mongoTemplate.remove(new Query(Criteria.where("_id").is(id)), UserDO.class); } public UserDO findById(Integer id) { return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), UserDO.class); } public UserDO findByUsername(String username) { return mongoTemplate.findOne(new Query(Criteria.where("username").is(username)), UserDO.class); } public List<UserDO> findAllById(List<Integer> ids) { return mongoTemplate.find(new Query(Criteria.where("_id").in(ids)), UserDO.class); } }
repos\SpringBoot-Labs-master\lab-16-spring-data-mongo\lab-16-spring-data-mongodb\src\main\java\cn\iocoder\springboot\lab16\springdatamongodb\dao\UserDao.java
2
请在Spring Boot框架中完成以下Java代码
public class PickupStep { public static final String SERIALIZED_NAME_MERCHANT_LOCATION_KEY = "merchantLocationKey"; @SerializedName(SERIALIZED_NAME_MERCHANT_LOCATION_KEY) private String merchantLocationKey; public PickupStep merchantLocationKey(String merchantLocationKey) { this.merchantLocationKey = merchantLocationKey; return this; } /** * A merchant-defined unique identifier of the merchant&#39;s store where the buyer will pick up their In-Store Pickup order. This field is always returned with the pickupStep container. * * @return merchantLocationKey **/ @javax.annotation.Nullable @ApiModelProperty(value = "A merchant-defined unique identifier of the merchant's store where the buyer will pick up their In-Store Pickup order. This field is always returned with the pickupStep container.") public String getMerchantLocationKey() { return merchantLocationKey; } public void setMerchantLocationKey(String merchantLocationKey) { this.merchantLocationKey = merchantLocationKey; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PickupStep pickupStep = (PickupStep)o; return Objects.equals(this.merchantLocationKey, pickupStep.merchantLocationKey); } @Override public int hashCode()
{ return Objects.hash(merchantLocationKey); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PickupStep {\n"); sb.append(" merchantLocationKey: ").append(toIndentedString(merchantLocationKey)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PickupStep.java
2
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password= spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 最小空闲连接,默认值10,小于0或大于maximum-pool-size,都会重置为maximum-pool-size spring.datasource.hikari.minimum-idle=10 # 最大连接数,小于等于0会被重置为默认值10;大于零小于1会被重置为minimum-idle的值 spring.datasource.hikari.maximum-pool-size=20 # 空闲连接超时时间,默认值600000(10分钟),大于等于max-lifetime且max-lifetime>0,会被重置为0;不等于0且小于10秒,会被重置为10秒。 spring.datasource.hikari.idle-timeout=500000 # 连接最大存活时间.不等于0且小于30秒,会被重置
为默认值30分钟.设置应该比mysql设置的超时时间短 spring.datasource.hikari.max-lifetime=540000 # 连接超时时间:毫秒,小于250毫秒,否则被重置为默认值30秒 spring.datasource.hikari.connection-timeout=60000 # 用于测试连接是否可用的查询语句 spring.datasource.hikari.connection-test-query=SELECT 1
repos\SpringBoot-Learning-master\2.x\chapter3-2\src\main\resources\application.properties
2
请完成以下Java代码
public boolean isClosed() { return Completed.equals(this) || Aborted.equals(this) || Terminated.equals(this); } public boolean isNotStarted() { return NotStarted.equals(this); } // isNotStarted public boolean isRunning() { return Running.equals(this); } public boolean isSuspended() { return Suspended.equals(this); } public boolean isCompleted() { return Completed.equals(this); } public boolean isError() { return isAborted() || isTerminated(); } /** * @return true if state is Aborted (Environment/Setup issue) */ public boolean isAborted() { return Aborted.equals(this); } /** * @return true if state is Terminated (Execution issue) */ public boolean isTerminated() { return Terminated.equals(this); } /** * Get New State Options based on current State */ private WFState[] getNewStateOptions() { if (isNotStarted()) return new WFState[] { Running, Aborted, Terminated }; else if (isRunning()) return new WFState[] { Suspended, Completed, Aborted, Terminated }; else if (isSuspended()) return new WFState[] { Running, Aborted, Terminated }; else return new WFState[] {}; } /** * Is the new State valid based on current state * * @param newState new state * @return true valid new state */ public boolean isValidNewState(final WFState newState) { final WFState[] options = getNewStateOptions(); for (final WFState option : options)
{ if (option.equals(newState)) return true; } return false; } /** * @return true if the action is valid based on current state */ public boolean isValidAction(final WFAction action) { final WFAction[] options = getActionOptions(); for (final WFAction option : options) { if (option.equals(action)) { return true; } } return false; } /** * @return valid actions based on current State */ private WFAction[] getActionOptions() { if (isNotStarted()) return new WFAction[] { WFAction.Start, WFAction.Abort, WFAction.Terminate }; if (isRunning()) return new WFAction[] { WFAction.Suspend, WFAction.Complete, WFAction.Abort, WFAction.Terminate }; if (isSuspended()) return new WFAction[] { WFAction.Resume, WFAction.Abort, WFAction.Terminate }; else return new WFAction[] {}; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFState.java
1
请在Spring Boot框架中完成以下Java代码
public class VariableInstanceRestServiceImpl extends AbstractRestProcessEngineAware implements VariableInstanceRestService { public VariableInstanceRestServiceImpl(String engineName, ObjectMapper objectMapper) { super(engineName, objectMapper); } @Override public VariableInstanceResource getVariableInstance(String id) { return new VariableInstanceResourceImpl(id, getProcessEngine()); } @Override public List<VariableInstanceDto> getVariableInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults, boolean deserializeObjectValues) { VariableInstanceQueryDto queryDto = new VariableInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return queryVariableInstances(queryDto, firstResult, maxResults, deserializeObjectValues); } @Override public List<VariableInstanceDto> queryVariableInstances(VariableInstanceQueryDto queryDto, Integer firstResult, Integer maxResults, boolean deserializeObjectValues) { ProcessEngine engine = getProcessEngine(); queryDto.setObjectMapper(getObjectMapper()); VariableInstanceQuery query = queryDto.toQuery(engine); // disable binary fetching by default. query.disableBinaryFetching(); // disable custom object fetching by default. Cannot be done to not break existing API if (!deserializeObjectValues) { query.disableCustomObjectDeserialization(); } List<VariableInstance> matchingInstances = QueryUtil.list(query, firstResult, maxResults);
List<VariableInstanceDto> instanceResults = new ArrayList<>(); for (VariableInstance instance : matchingInstances) { VariableInstanceDto resultInstance = VariableInstanceDto.fromVariableInstance(instance); instanceResults.add(resultInstance); } return instanceResults; } @Override public CountResultDto getVariableInstancesCount(UriInfo uriInfo) { VariableInstanceQueryDto queryDto = new VariableInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return queryVariableInstancesCount(queryDto); } @Override public CountResultDto queryVariableInstancesCount(VariableInstanceQueryDto queryDto) { ProcessEngine engine = getProcessEngine(); queryDto.setObjectMapper(getObjectMapper()); VariableInstanceQuery query = queryDto.toQuery(engine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\VariableInstanceRestServiceImpl.java
2
请完成以下Java代码
public FunctionMapper getFunctionMapper() { return null; } @Override public VariableMapper getVariableMapper() { return null; } // delegate methods //////////////////////////// @Override @SuppressWarnings("rawtypes") public Object getContext(Class key) { return delegateContext.getContext(key); } @Override public boolean equals(Object obj) { return delegateContext.equals(obj); } @Override public Locale getLocale() { return delegateContext.getLocale();
} @Override public boolean isPropertyResolved() { return delegateContext.isPropertyResolved(); } @Override @SuppressWarnings("rawtypes") public void putContext(Class key, Object contextObject) { delegateContext.putContext(key, contextObject); } @Override public void setLocale(Locale locale) { delegateContext.setLocale(locale); } @Override public void setPropertyResolved(boolean resolved) { delegateContext.setPropertyResolved(resolved); } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\el\ElContextDelegate.java
1
请完成以下Java代码
private static int countLines(FilePath path) throws IOException, InterruptedException { byte[] buffer = new byte[1024]; int result = 1; try (InputStream in = path.read()) { while (true) { int read = in.read(buffer); if (read < 0) { return result; } for (int i = 0; i < read; i++) { if (buffer[i] == '\n') { result++; } } } } } private static String generateReport(String projectName, ProjectStats stats) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try (InputStream in = ProjectStatsBuildWrapper.class.getResourceAsStream(REPORT_TEMPLATE_PATH)) { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) >= 0) { bOut.write(buffer, 0, read); } } String content = new String(bOut.toByteArray(), StandardCharsets.UTF_8); content = content.replace(PROJECT_NAME_VAR, projectName);
content = content.replace(CLASSES_NUMBER_VAR, String.valueOf(stats.getClassesNumber())); content = content.replace(LINES_NUMBER_VAR, String.valueOf(stats.getLinesNumber())); return content; } @Extension public static final class DescriptorImpl extends BuildWrapperDescriptor { @Override public boolean isApplicable(AbstractProject<?, ?> item) { return true; } @Nonnull @Override public String getDisplayName() { return "Construct project stats during build"; } } }
repos\tutorials-master\jenkins-modules\plugins\src\main\java\com\baeldung\jenkins\plugins\ProjectStatsBuildWrapper.java
1
请完成以下Java代码
public MinimalColumnInfo getById(final @NonNull AdColumnId adColumnId) { final MinimalColumnInfo column = byId.get(adColumnId); if (column == null) { throw new AdempiereException("No column found for " + adColumnId); } return column; } @Override public ImmutableList<MinimalColumnInfo> getByIds(final Collection<AdColumnId> adColumnIds) { if (adColumnIds.isEmpty()) { return ImmutableList.of(); } return adColumnIds.stream() .distinct() .map(byId::get) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } @Override public ImmutableList<MinimalColumnInfo> getByColumnName(@NonNull final String columnName) { return byId.values() .stream() .filter(columnInfo -> columnInfo.isColumnNameMatching(columnName)) .collect(ImmutableList.toImmutableList()); }
@Nullable @Override public MinimalColumnInfo getByColumnNameOrNull(final AdTableId adTableId, final String columnName) { final AdTableIdAndColumnName key = new AdTableIdAndColumnName(adTableId, columnName); return byColumnName.get(key); } // // // @Value static class AdTableIdAndColumnName { @NonNull AdTableId adTableId; @NonNull String columnNameUC; AdTableIdAndColumnName(@NonNull final AdTableId adTableId, @NonNull final String columnName) { this.adTableId = adTableId; this.columnNameUC = columnName.toUpperCase(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\impl\ImmutableMinimalColumnInfoMap.java
1
请完成以下Java代码
public class PropertySourceOrigin implements Origin, OriginProvider { private final PropertySource<?> propertySource; private final String propertyName; private final @Nullable Origin origin; /** * Create a new {@link PropertySourceOrigin} instance. * @param propertySource the property source * @param propertyName the name from the property source */ public PropertySourceOrigin(PropertySource<?> propertySource, String propertyName) { this(propertySource, propertyName, null); } /** * Create a new {@link PropertySourceOrigin} instance. * @param propertySource the property source * @param propertyName the name from the property source * @param origin the actual origin for the source if known * @since 3.2.8 */ public PropertySourceOrigin(PropertySource<?> propertySource, String propertyName, @Nullable Origin origin) { Assert.notNull(propertySource, "'propertySource' must not be null"); Assert.hasLength(propertyName, "'propertyName' must not be empty"); this.propertySource = propertySource; this.propertyName = propertyName; this.origin = origin; } /** * Return the origin {@link PropertySource}. * @return the origin property source */ public PropertySource<?> getPropertySource() { return this.propertySource; } /** * Return the property name that was used when obtaining the original value from the
* {@link #getPropertySource() property source}. * @return the origin property name */ public String getPropertyName() { return this.propertyName; } /** * Return the actual origin for the source if known. * @return the actual source origin * @since 3.2.8 */ @Override public @Nullable Origin getOrigin() { return this.origin; } @Override public @Nullable Origin getParent() { return (this.origin != null) ? this.origin.getParent() : null; } @Override public String toString() { return (this.origin != null) ? this.origin.toString() : "\"" + this.propertyName + "\" from property source \"" + this.propertySource.getName() + "\""; } /** * Get an {@link Origin} for the given {@link PropertySource} and * {@code propertyName}. Will either return an {@link OriginLookup} result or a * {@link PropertySourceOrigin}. * @param propertySource the origin property source * @param name the property name * @return the property origin */ public static Origin get(PropertySource<?> propertySource, String name) { Origin origin = OriginLookup.getOrigin(propertySource, name); return (origin instanceof PropertySourceOrigin) ? origin : new PropertySourceOrigin(propertySource, name, origin); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\origin\PropertySourceOrigin.java
1
请完成以下Java代码
public boolean hasParameters() { return !lookupDataSourceFetcher.getSqlForFetchingLookups().getParameters().isEmpty() || (!filters.getDependsOnFieldNames().isEmpty()); } public ImmutableSet<String> getDependsOnFieldNames() { return filters.getDependsOnFieldNames(); } public ImmutableSet<String> getDependsOnTableNames() { return filters.getDependsOnTableNames(); } @NonNull public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression() { return lookupDataSourceFetcher.getSqlForFetchingLookupById(); } public SqlLookupDescriptor withScope(@Nullable LookupDescriptorProvider.LookupScope scope)
{ return withFilters(this.filters.withOnlyScope(scope)); } public SqlLookupDescriptor withOnlyForAvailableParameterNames(@Nullable Set<String> onlyForAvailableParameterNames) { return withFilters(this.filters.withOnlyForAvailableParameterNames(onlyForAvailableParameterNames)); } private SqlLookupDescriptor withFilters(@NonNull final CompositeSqlLookupFilter filters) { return !Objects.equals(this.filters, filters) ? toBuilder().filters(filters).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public Sort getSort() { return this.sort; } /** * Pageable properties. */ public static class Pageable { /** * Page index parameter name. */ private String pageParameter = "page"; /** * Page size parameter name. */ private String sizeParameter = "size"; /** * Whether to expose and assume 1-based page number indexes. Defaults to "false", * meaning a page number of 0 in the request equals the first page. */ private boolean oneIndexedParameters; /** * General prefix to be prepended to the page number and page size parameters. */ private String prefix = ""; /** * Delimiter to be used between the qualifier and the actual page number and size * properties. */ private String qualifierDelimiter = "_"; /** * Default page size. */ private int defaultPageSize = 20; /** * Maximum page size to be accepted. */ private int maxPageSize = 2000; /** * Configures how to render Spring Data Pageable instances. */ private PageSerializationMode serializationMode = PageSerializationMode.DIRECT; public String getPageParameter() { return this.pageParameter; } public void setPageParameter(String pageParameter) { this.pageParameter = pageParameter; } public String getSizeParameter() { return this.sizeParameter; } public void setSizeParameter(String sizeParameter) { this.sizeParameter = sizeParameter; } public boolean isOneIndexedParameters() { return this.oneIndexedParameters; } public void setOneIndexedParameters(boolean oneIndexedParameters) { this.oneIndexedParameters = oneIndexedParameters; }
public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getQualifierDelimiter() { return this.qualifierDelimiter; } public void setQualifierDelimiter(String qualifierDelimiter) { this.qualifierDelimiter = qualifierDelimiter; } public int getDefaultPageSize() { return this.defaultPageSize; } public void setDefaultPageSize(int defaultPageSize) { this.defaultPageSize = defaultPageSize; } public int getMaxPageSize() { return this.maxPageSize; } public void setMaxPageSize(int maxPageSize) { this.maxPageSize = maxPageSize; } public PageSerializationMode getSerializationMode() { return this.serializationMode; } public void setSerializationMode(PageSerializationMode serializationMode) { this.serializationMode = serializationMode; } } /** * Sort properties. */ public static class Sort { /** * Sort parameter name. */ private String sortParameter = "sort"; public String getSortParameter() { return this.sortParameter; } public void setSortParameter(String sortParameter) { this.sortParameter = sortParameter; } } }
repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\autoconfigure\web\DataWebProperties.java
2
请完成以下Java代码
private static String computeEffectiveColumnName(@Nullable final String columnName, @Nullable final AdElementId adElementId) { if (columnName == null) { return null; } String columnNameNormalized = StringUtils.trimBlankToNull(columnName); if (columnNameNormalized == null) { return null; } columnNameNormalized = StringUtils.ucFirst(columnNameNormalized); assertColumnNameDoesNotExist(columnNameNormalized, adElementId); return columnNameNormalized; } private static void assertColumnNameDoesNotExist(final String columnName, final AdElementId elementIdToExclude) { String sql = "select count(1) from AD_Element where UPPER(ColumnName)=UPPER(?)"; if (elementIdToExclude != null) { sql += " AND AD_Element_ID<>" + elementIdToExclude.getRepoId(); } final int no = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, columnName); if (no > 0) { throw new AdempiereException("@SaveErrorNotUnique@ @ColumnName@: " + columnName); } } @Override
protected boolean afterSave(final boolean newRecord, final boolean success) { if (!newRecord) { // update dependent entries only in case of existing element. // new elements are not used yet. updateDependentADEntries(); } return success; } private void updateDependentADEntries() { final AdElementId adElementId = AdElementId.ofRepoId(getAD_Element_ID()); if (is_ValueChanged(COLUMNNAME_ColumnName)) { final String columnName = getColumnName(); Services.get(IADTableDAO.class).updateColumnNameByAdElementId(adElementId, columnName); Services.get(IADProcessDAO.class).updateColumnNameByAdElementId(adElementId, columnName); } final IElementTranslationBL elementTranslationBL = Services.get(IElementTranslationBL.class); final ILanguageDAO languageDAO = Services.get(ILanguageDAO.class); final String baseADLanguage = languageDAO.retrieveBaseLanguage(); elementTranslationBL.propagateElementTrls(adElementId, baseADLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\M_Element.java
1
请完成以下Java代码
public static final String toOneLineStackTraceString(@NonNull final StackTraceElement[] stacktrace) { final StringBuilder stackTraceStr = new StringBuilder(); int ste_Considered = 0; boolean ste_lastSkipped = false; for (final StackTraceElement ste : stacktrace) { if (ste_Considered >= 100) { stackTraceStr.append("..."); break; } String classname = ste.getClassName(); final String methodName = ste.getMethodName(); // Skip some irrelevant stack trace elements if (classname.startsWith("java.") || classname.startsWith("javax.") || classname.startsWith("sun.") || classname.startsWith("com.google.") || classname.startsWith("org.springframework.") || classname.startsWith("org.apache.") || classname.startsWith(QueryStatisticsLogger.class.getPackage().getName()) || classname.startsWith(Trace.class.getName()) // || classname.startsWith(StatementsFactory.class.getPackage().getName()) || classname.startsWith(AbstractResultSetBlindIterator.class.getPackage().getName()) || classname.startsWith(ITrxManager.class.getPackage().getName()) || classname.startsWith(org.adempiere.ad.persistence.TableModelLoader.class.getPackage().getName()) // || classname.startsWith(JavaAssistInterceptor.class.getPackage().getName()) || classname.indexOf("_$$_jvstdca_") >= 0 // javassist proxy || methodName.startsWith("access$") // ) { ste_lastSkipped = true; continue; }
final int lastDot = classname.lastIndexOf("."); if (lastDot >= 0) { classname = classname.substring(lastDot + 1); } if (ste_lastSkipped || stackTraceStr.length() > 0) { stackTraceStr.append(ste_lastSkipped ? " <~~~ " : " <- "); } stackTraceStr.append(classname).append(".").append(methodName); final int lineNumber = ste.getLineNumber(); if (lineNumber > 0) { stackTraceStr.append(":").append(lineNumber); } ste_lastSkipped = false; ste_Considered++; } return stackTraceStr.toString(); } } // Trace
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Trace.java
1
请完成以下Java代码
public class MethodInvocationResult { private final MethodInvocation methodInvocation; private @Nullable final Object result; /** * Construct a {@link MethodInvocationResult} with the provided parameters * @param methodInvocation the already-invoked {@link MethodInvocation} * @param result the value returned from the {@link MethodInvocation} */ public MethodInvocationResult(MethodInvocation methodInvocation, @Nullable Object result) { Assert.notNull(methodInvocation, "methodInvocation cannot be null"); this.methodInvocation = methodInvocation; this.result = result; } /**
* Return the already-invoked {@link MethodInvocation} * @return the already-invoked {@link MethodInvocation} */ public MethodInvocation getMethodInvocation() { return this.methodInvocation; } /** * Return the result of the already-invoked {@link MethodInvocation} * @return the result */ public @Nullable Object getResult() { return this.result; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\MethodInvocationResult.java
1
请完成以下Java代码
public String getPackageName() { if (StringUtils.hasText(this.packageName)) { return this.packageName; } if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) { return getGroupId() + "." + getArtifactId(); } return null; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getJavaVersion() { return this.javaVersion;
} public void setJavaVersion(String javaVersion) { this.javaVersion = javaVersion; } public String getBaseDir() { return this.baseDir; } public void setBaseDir(String baseDir) { this.baseDir = baseDir; } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\ProjectRequest.java
1
请在Spring Boot框架中完成以下Java代码
public class CoronaVirusDataService { private static String VIRUS_DATA_URL = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv"; private List<LocationStats> allStats = new ArrayList<>(); public List<LocationStats> getAllStats() { return allStats; } @PostConstruct @Scheduled(cron = "* * 1 * * *") public void fetchVirusData() throws IOException, InterruptedException { List<LocationStats> newStats = new ArrayList<>(); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(VIRUS_DATA_URL)) .build();
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString()); StringReader csvBodyReader = new StringReader(httpResponse.body()); Iterable<CSVRecord> records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(csvBodyReader); for (CSVRecord record : records) { LocationStats locationStat = new LocationStats(); locationStat.setState(record.get("Province/State")); locationStat.setCountry(record.get("Country/Region")); int latestCases = Integer.parseInt(record.get(record.size() - 1)); int prevDayCases = Integer.parseInt(record.get(record.size() - 2)); locationStat.setLatestTotalCases(latestCases); locationStat.setDiffFromPrevDay(latestCases - prevDayCases); newStats.add(locationStat); } this.allStats = newStats; } }
repos\Spring-Boot-Advanced-Projects-main\spring covid-19\src\main\java\io\alanbinu\coronavirustracker\services\CoronaVirusDataService.java
2
请完成以下Java代码
public boolean equals(final IProductionMaterial pm1, final IProductionMaterial pm2) { final int cmp = compare(pm1, pm2); return cmp == 0; } @Override public int compare(final IProductionMaterial pm1, final IProductionMaterial pm2) { if (pm1 == pm2) { return 0; } if (pm1 == null) { return -1; } if (pm2 == null) { return +1; } // // Compare Types { final ProductionMaterialType type1 = pm1.getType(); final ProductionMaterialType type2 = pm2.getType(); final int cmp = type1.compareTo(type2); if (cmp != 0) { return cmp; } } // // Compare Product { final int productId1 = pm1.getM_Product().getM_Product_ID(); final int productId2 = pm2.getM_Product().getM_Product_ID(); if (productId1 != productId2) { return productId1 - productId2; } } // // Compare Qty { final BigDecimal qty1 = pm1.getQty(); final BigDecimal qty2 = pm2.getQty(); final int cmp = qty1.compareTo(qty2); if (cmp != 0) { return cmp; } } // // Compare UOM {
final int uomId1 = pm1.getC_UOM().getC_UOM_ID(); final int uomId2 = pm2.getC_UOM().getC_UOM_ID(); if (uomId1 != uomId2) { return uomId1 - uomId2; } } // // Compare QM_QtyDeliveredPercOfRaw { final BigDecimal qty1 = pm1.getQM_QtyDeliveredPercOfRaw(); final BigDecimal qty2 = pm2.getQM_QtyDeliveredPercOfRaw(); final int cmp = qty1.compareTo(qty2); if (cmp != 0) { return cmp; } } // // Compare QM_QtyDeliveredPercOfRaw { final BigDecimal qty1 = pm1.getQM_QtyDeliveredAvg(); final BigDecimal qty2 = pm2.getQM_QtyDeliveredAvg(); final int cmp = qty1.compareTo(qty2); if (cmp != 0) { return cmp; } } // // If we reach this point, they are equal return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ProductionMaterialComparator.java
1
请完成以下Java代码
public void setReclassifyOnExceptionChange(boolean reclassifyOnExceptionChange) { this.reclassifyOnExceptionChange = reclassifyOnExceptionChange; } @Override public void handleBatch(Exception thrownException, @Nullable ConsumerRecords<?, ?> records, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { if (records == null || records.count() == 0) { this.logger.error(thrownException, "Called with no records; consumer exception"); return; } this.retrying.put(Thread.currentThread(), true); try { ErrorHandlingUtils.retryBatch(thrownException, records, consumer, container, invokeListener, this.backOff, this.seeker, this.recoverer, this.logger, getLogLevel(), this.retryListeners, getExceptionMatcher(), this.reclassifyOnExceptionChange); } finally { this.retrying.remove(Thread.currentThread()); } } @Override public void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions, Runnable publishPause) { if (Boolean.TRUE.equals(this.retrying.get(Thread.currentThread()))) { consumer.pause(consumer.assignment()); publishPause.run(); } } private final class SeekAfterRecoverFailsOrInterrupted implements CommonErrorHandler {
SeekAfterRecoverFailsOrInterrupted() { } @Override public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { data.partitions() .stream() .collect( Collectors.toMap(tp -> tp, tp -> data.records(tp).get(0).offset(), (u, v) -> v, LinkedHashMap::new)) .forEach(consumer::seek); throw new KafkaException("Seek to current after exception", getLogLevel(), thrownException); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\FallbackBatchErrorHandler.java
1
请完成以下Java代码
public DocumentLayoutElementDescriptor createSpecialElement_DocStatusAndDocAction() { final Map<Characteristic, DocumentFieldDescriptor.Builder> fields = descriptorsFactory.getSpecialField_DocSatusAndDocAction(); if (fields == null || fields.isEmpty()) { return null; } final DocumentFieldDescriptor.Builder docStatusField = fields.get(Characteristic.SpecialField_DocStatus); final DocumentFieldDescriptor.Builder docActionField = fields.get(Characteristic.SpecialField_DocAction); return DocumentLayoutElementDescriptor.builder() .setCaptionNone() // not relevant .setDescription(null) // not relevant .setLayoutTypeNone() // not relevant .setWidgetType(DocumentFieldWidgetType.ActionButton) .addField(layoutElementField(docStatusField).setFieldType(FieldType.ActionButtonStatus)) .addField(layoutElementField(docActionField).setFieldType(FieldType.ActionButton))
.build(); } private boolean isSkipField(@NonNull final DocumentFieldDescriptor.Builder field) { switch (field.getFieldName()) { case FIELDNAME_AD_Org_ID: return !services.getSysConfigBooleanValue(SYS_CONFIG_AD_ORG_ID_IS_DISPLAYED, true); case FIELDNAME_AD_Client_ID: return !services.getSysConfigBooleanValue(SYS_CONFIG_AD_CLIENT_ID_IS_DISPLAYED, true); default: return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\LayoutFactory.java
1
请完成以下Java代码
private Mono<List<JWK>> get(JWKSelector jwkSelector, JWKSet jwkSet) { return Mono.defer(() -> { // Run the selector on the JWK set List<JWK> matches = jwkSelector.select(jwkSet); if (!matches.isEmpty()) { // Success return Mono.just(matches); } // Refresh the JWK set if the sought key ID is not in the cached JWK set // Looking for JWK with specific ID? String soughtKeyID = getFirstSpecifiedKeyID(jwkSelector.getMatcher()); if (soughtKeyID == null) { // No key ID specified, return no matches return Mono.just(Collections.emptyList()); } if (jwkSet.getKeyByKeyId(soughtKeyID) != null) { // The key ID exists in the cached JWK set, matching // failed for some other reason, return no matches return Mono.just(Collections.emptyList()); } return Mono.empty(); }); } /** * Updates the cached JWK set from the configured URL. * @return The updated JWK set. * @throws RemoteKeySourceException If JWK retrieval failed. */ private Mono<JWKSet> getJWKSet() { // @formatter:off return this.jwkSetUrlProvider .flatMap((jwkSetURL) -> this.webClient.get() .uri(jwkSetURL) .retrieve() .bodyToMono(String.class) ) .map(this::parse)
.doOnNext((jwkSet) -> this.cachedJWKSet .set(Mono.just(jwkSet)) ) .cache(); // @formatter:on } private JWKSet parse(String body) { try { return JWKSet.parse(body); } catch (ParseException ex) { throw new RuntimeException(ex); } } /** * Returns the first specified key ID (kid) for a JWK matcher. * @param jwkMatcher The JWK matcher. Must not be {@code null}. * @return The first key ID, {@code null} if none. */ protected static String getFirstSpecifiedKeyID(final JWKMatcher jwkMatcher) { Set<String> keyIDs = jwkMatcher.getKeyIDs(); if (keyIDs == null || keyIDs.isEmpty()) { return null; } for (String id : keyIDs) { if (id != null) { return id; } } return null; // No kid in matcher } void setWebClient(WebClient webClient) { this.webClient = webClient; } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\ReactiveRemoteJWKSource.java
1
请完成以下Java代码
public static final class Builder { private BigDecimal qtyCUsTotal; private BigDecimal qtyTUsTotal; private BigDecimal qtyCUsPerTU; private BigDecimal qtyTUsPerLU; private Builder() { super(); } public TotalQtyCUBreakdownCalculator build() { return new TotalQtyCUBreakdownCalculator(this); } public Builder setQtyCUsTotal(final BigDecimal qtyCUsTotal) { this.qtyCUsTotal = qtyCUsTotal; return this; } public BigDecimal getQtyCUsTotal() { Check.assumeNotNull(qtyCUsTotal, "qtyCUsTotal not null"); return qtyCUsTotal; } public Builder setQtyTUsTotal(final BigDecimal qtyTUsTotal) { this.qtyTUsTotal = qtyTUsTotal; return this; } public BigDecimal getQtyTUsTotal() { if (qtyTUsTotal == null) { return Quantity.QTY_INFINITE; } return qtyTUsTotal; } public Builder setStandardQtyCUsPerTU(final BigDecimal qtyCUsPerTU) { this.qtyCUsPerTU = qtyCUsPerTU; return this; } public BigDecimal getStandardQtyCUsPerTU() { return qtyCUsPerTU;
} public Builder setStandardQtyTUsPerLU(final BigDecimal qtyTUsPerLU) { this.qtyTUsPerLU = qtyTUsPerLU; return this; } public Builder setStandardQtyTUsPerLU(final int qtyTUsPerLU) { return setStandardQtyTUsPerLU(BigDecimal.valueOf(qtyTUsPerLU)); } public BigDecimal getStandardQtyTUsPerLU() { return qtyTUsPerLU; } public Builder setStandardQtysAsInfinite() { setStandardQtyCUsPerTU(BigDecimal.ZERO); setStandardQtyTUsPerLU(BigDecimal.ZERO); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TotalQtyCUBreakdownCalculator.java
1
请完成以下Java代码
public I_M_Warehouse getM_Warehouse() throws RuntimeException { return (I_M_Warehouse)MTable.get(getCtx(), I_M_Warehouse.Table_Name) .getPO(getM_Warehouse_ID(), get_TrxName()); } /** Set Warehouse. @param M_Warehouse_ID Storage Warehouse and Service Point */ public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } /** Get Warehouse. @return Storage Warehouse and Service Point */ public int getM_Warehouse_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false;
} /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Expense Report. @param S_TimeExpense_ID Time and Expense Report */ public void setS_TimeExpense_ID (int S_TimeExpense_ID) { if (S_TimeExpense_ID < 1) set_ValueNoCheck (COLUMNNAME_S_TimeExpense_ID, null); else set_ValueNoCheck (COLUMNNAME_S_TimeExpense_ID, Integer.valueOf(S_TimeExpense_ID)); } /** Get Expense Report. @return Time and Expense Report */ public int getS_TimeExpense_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeExpense_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_TimeExpense.java
1
请完成以下Java代码
public Set<Object> documents() { return tfMap.keySet(); } public Map<Object, Map<String, Double>> getTfMap() { return tfMap; } public List<Map.Entry<String, Double>> sortedAllTf() { return sort(allTf()); } public List<Map.Entry<String, Integer>> sortedAllTfInt() { return doubleToInteger(sortedAllTf()); } public Map<String, Double> allTf() { Map<String, Double> result = new HashMap<String, Double>(); for (Map<String, Double> d : tfMap.values()) { for (Map.Entry<String, Double> tf : d.entrySet()) { Double f = result.get(tf.getKey()); if (f == null) { result.put(tf.getKey(), tf.getValue()); } else { result.put(tf.getKey(), f + tf.getValue()); } } }
return result; } private static List<Map.Entry<String, Double>> sort(Map<String, Double> map) { List<Map.Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Double>>() { @Override public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) { return o2.getValue().compareTo(o1.getValue()); } }); return list; } private static List<Map.Entry<String, Integer>> doubleToInteger(List<Map.Entry<String, Double>> list) { List<Map.Entry<String, Integer>> result = new ArrayList<Map.Entry<String, Integer>>(list.size()); for (Map.Entry<String, Double> entry : list) { result.add(new AbstractMap.SimpleEntry<String, Integer>(entry.getKey(), entry.getValue().intValue())); } return result; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TfIdfCounter.java
1
请完成以下Java代码
public void setJ(byte[] value) { this.j = value; } /** * Gets the value of the seed property. * * @return * possible object is * byte[] */ public byte[] getSeed() { return seed; } /** * Sets the value of the seed property. * * @param value * allowed object is * byte[] */ public void setSeed(byte[] value) { this.seed = value; } /**
* Gets the value of the pgenCounter property. * * @return * possible object is * byte[] */ public byte[] getPgenCounter() { return pgenCounter; } /** * Sets the value of the pgenCounter property. * * @param value * allowed object is * byte[] */ public void setPgenCounter(byte[] value) { this.pgenCounter = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DSAKeyValueType.java
1
请完成以下Java代码
public static Builder builder() { return new Builder(); } /** * Used to build a new instance of {@link DelegatingAuthenticationEntryPoint}. * * @author Rob Winch * @since 7.0 */ public static final class Builder { private @Nullable AuthenticationEntryPoint defaultEntryPoint; private List<RequestMatcherEntry<AuthenticationEntryPoint>> entryPoints = new ArrayList<RequestMatcherEntry<AuthenticationEntryPoint>>(); /** * Set the default {@link AuthenticationEntryPoint} if none match. The default is * to use the first {@link AuthenticationEntryPoint} added in * {@link #addEntryPointFor(AuthenticationEntryPoint, RequestMatcher)}. * @param defaultEntryPoint the default {@link AuthenticationEntryPoint} to use. * @return the {@link Builder} for further customization. */ public Builder defaultEntryPoint(@Nullable AuthenticationEntryPoint defaultEntryPoint) { this.defaultEntryPoint = defaultEntryPoint; return this; } /** * Adds an {@link AuthenticationEntryPoint} for the provided * {@link RequestMatcher}. * @param entryPoint the {@link AuthenticationEntryPoint} to use. Cannot be null. * @param requestMatcher the {@link RequestMatcher} to use. Cannot be null. * @return the {@link Builder} for further customization. */ public Builder addEntryPointFor(AuthenticationEntryPoint entryPoint, RequestMatcher requestMatcher) { Assert.notNull(entryPoint, "entryPoint cannot be null"); Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.entryPoints.add(new RequestMatcherEntry<>(requestMatcher, entryPoint)); return this; } /** * Builds the {@link AuthenticationEntryPoint}. If the * {@link #defaultEntryPoint(AuthenticationEntryPoint)} is not set, then the first * {@link #addEntryPointFor(AuthenticationEntryPoint, RequestMatcher)} is used as * the default. If the {@link #defaultEntryPoint(AuthenticationEntryPoint)} is not * set and there is only a single * {@link #addEntryPointFor(AuthenticationEntryPoint, RequestMatcher)}, then the * {@link AuthenticationEntryPoint} is returned rather than wrapping it in * {@link DelegatingAuthenticationEntryPoint}. * @return the {@link AuthenticationEntryPoint} to use. */ public AuthenticationEntryPoint build() { AuthenticationEntryPoint defaultEntryPoint = this.defaultEntryPoint; if (defaultEntryPoint == null) { Assert.state(!this.entryPoints.isEmpty(), "entryPoints cannot be empty if defaultEntryPoint is null"); AuthenticationEntryPoint firstAuthenticationEntryPoint = this.entryPoints.get(0).getEntry(); if (this.entryPoints.size() == 1) { return firstAuthenticationEntryPoint; } defaultEntryPoint = firstAuthenticationEntryPoint; } else if (this.entryPoints.isEmpty()) { return defaultEntryPoint; } return new DelegatingAuthenticationEntryPoint(defaultEntryPoint, this.entryPoints); } private Builder() { } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\DelegatingAuthenticationEntryPoint.java
1
请完成以下Java代码
public class TemplateMsg extends BaseModel { private String touser; @JSONField(name = "template_id") private String templateId; private String url; @Deprecated private String topcolor; private Map<String, TemplateParam> data; public String getTouser() { return touser; } public void setTouser(String touser) { this.touser = touser; } public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Deprecated public String getTopcolor() {
return topcolor; } @Deprecated public void setTopcolor(String topcolor) { this.topcolor = topcolor; } public Map<String, TemplateParam> getData() { return data; } public void setData(Map<String, TemplateParam> data) { this.data = data; } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\model\TemplateMsg.java
1
请完成以下Java代码
public final class StringGridTabSummaryInfo implements IGridTabSummaryInfo { private static final long serialVersionUID = 1L; private final String message; private final boolean translated; /** * * @param message * @param translated true if the message is already translated */ public StringGridTabSummaryInfo(final String message, final boolean translated) { super(); this.message = message;
this.translated = translated; } @Override public String getSummaryMessageTranslated(final Properties ctx) { if (translated) { return message; } return Services.get(IMsgBL.class).parseTranslation(ctx, message); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\api\StringGridTabSummaryInfo.java
1
请完成以下Java代码
public class C_BPartner_ShipmentSchedule { /** * * * @param bpartner */ @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_C_BPartner.COLUMNNAME_AllowConsolidateInOut }) public void inValidateScheds(final I_C_BPartner bpartner) { // // Services final IShipmentSchedulePA shipmentSchedulesRepo = Services.get(IShipmentSchedulePA.class); final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class); final boolean isBPAllowConsolidateInOut = bpartnerBL.isAllowConsolidateInOutEffective(bpartner, SOTrx.SALES); final BPartnerId bpartnerId = BPartnerId.ofRepoId(bpartner.getC_BPartner_ID()); shipmentSchedulesRepo
.streamUnprocessedByPartnerIdAndAllowConsolidateInOut(bpartnerId, !isBPAllowConsolidateInOut) .forEach(sched -> setAllowConsolidateInOutAndSave(sched, isBPAllowConsolidateInOut)); } private void setAllowConsolidateInOutAndSave(final I_M_ShipmentSchedule sched, final boolean allowConsolidateInOut) { if (sched.isAllowConsolidateInOut() == allowConsolidateInOut) { return; } sched.setAllowConsolidateInOut(allowConsolidateInOut); InterfaceWrapperHelper.saveRecord(sched); // note that we do not need to invalidate the current sched explicitly.. // it will be updated as part of the segment, unless it has delivery rule force.. // and if it has that rule, then the partner change makes no difference to it, anyways. Services.get(IShipmentScheduleInvalidateBL.class).notifySegmentChangedForShipmentSchedule(sched); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\C_BPartner_ShipmentSchedule.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityController { private Logger logger = LoggerFactory.getLogger(getClass()); @GetMapping("/login") public String loginPage() { return "login.html"; } @ResponseBody @PostMapping("/login") public String login(HttpServletRequest request) { // 判断是否已经登陆 Subject subject = SecurityUtils.getSubject(); if (subject.getPrincipal() != null) { return "你已经登陆账号:" + subject.getPrincipal(); } // 获得登陆失败的原因 String shiroLoginFailure = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); // 翻译成人类看的懂的提示 String msg = ""; if (UnknownAccountException.class.getName().equals(shiroLoginFailure)) { msg = "账号不存在"; } else if (IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) { msg = "密码不正确";
} else if (LockedAccountException.class.getName().equals(shiroLoginFailure)) { msg = "账号被锁定"; } else if (ExpiredCredentialsException.class.getName().equals(shiroLoginFailure)) { msg = "账号已过期"; } else { msg = "未知"; logger.error("[login][未知登陆错误:{}]", shiroLoginFailure); } return "登陆失败,原因:" + msg; } @ResponseBody @GetMapping("/login_success") public String loginSuccess() { return "登陆成功"; } @ResponseBody @GetMapping("/unauthorized") public String unauthorized() { return "你没有权限"; } }
repos\SpringBoot-Labs-master\lab-33\lab-33-shiro-demo\src\main\java\cn\iocoder\springboot\lab01\shirodemo\controller\SecurityController.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_C_TaxGroup[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Tax Group. @param C_TaxGroup_ID Tax Group */ public void setC_TaxGroup_ID (int C_TaxGroup_ID) { if (C_TaxGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxGroup_ID, Integer.valueOf(C_TaxGroup_ID)); } /** Get Tax Group. @return Tax Group */ public int getC_TaxGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity
*/ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxGroup.java
1
请完成以下Java代码
public String[] getDecisionDefinitionIdIn() { return decisionDefinitionIdIn; } public void setDecisionDefinitionIdIn(String[] decisionDefinitionIdIn) { this.decisionDefinitionIdIn = decisionDefinitionIdIn; } public String[] getDecisionDefinitionKeyIn() { return decisionDefinitionKeyIn; } public void setDecisionDefinitionKeyIn(String[] decisionDefinitionKeyIn) { this.decisionDefinitionKeyIn = decisionDefinitionKeyIn; } public Date getCurrentTimestamp() { return currentTimestamp; } public void setCurrentTimestamp(Date currentTimestamp) { this.currentTimestamp = currentTimestamp; } public String[] getTenantIdIn() { return tenantIdIn; } public void setTenantIdIn(String[] tenantIdIn) { this.tenantIdIn = tenantIdIn; } public boolean isTenantIdSet() { return isTenantIdSet;
} public boolean isCompact() { return isCompact; } protected void provideHistoryCleanupStrategy(CommandContext commandContext) { String historyCleanupStrategy = commandContext.getProcessEngineConfiguration() .getHistoryCleanupStrategy(); isHistoryCleanupStrategyRemovalTimeBased = HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyCleanupStrategy); } public boolean isHistoryCleanupStrategyRemovalTimeBased() { return isHistoryCleanupStrategyRemovalTimeBased; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricDecisionInstanceReportImpl.java
1
请完成以下Java代码
public Resolver createResolver(VariableScope variableScope) { return this; } @Override public boolean containsKey(Object key) { if (key instanceof String) { return keySet.contains((String) key); } else { return false; } } @Override public Object get(Object key) { if (key instanceof String) { try { return applicationContext.getBean((String) key); } catch (BeanCreationException ex) { // Only swallow exceptions for beans with inactive scope. // Unfortunately, we cannot use ScopeNotActiveException directly as // it is only available starting with Spring 5.3, but we still support Spring 4. if (SCOPE_NOT_ACTIVE_EXCEPTION.equals(ex.getClass().getName())) { LOG.info("Bean '" + key + "' cannot be accessed since scope is not active. Instead, null is returned. "
+ "Full exception message: " + ex.getMessage()); return null; } else { throw ex; } } } else { return null; } } @Override public Set<String> keySet() { return keySet; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringBeansResolverFactory.java
1
请在Spring Boot框架中完成以下Java代码
public void beforeVoid( @NonNull final I_C_Order order, @NonNull final DocTimingType timing) { final RepairSalesProposalInfo proposal = salesOrderService.extractSalesProposalInfo(order).orElse(null); if (proposal != null) { beforeVoid_Proposal(proposal, timing); } else { salesOrderService.extractSalesOrderInfo(order).ifPresent(this::beforeVoid_SalesOrder); } }
private void beforeVoid_Proposal( @NonNull final RepairSalesProposalInfo proposal, @NonNull final DocTimingType timing) { if (timing.isVoid() || timing.isReverse()) { salesOrderService.unlinkProposalFromProject(proposal); } } private void beforeVoid_SalesOrder(@NonNull final RepairSalesOrderInfo salesOrder) { salesOrderService.transferVHUsFromSalesOrderToProject(salesOrder); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\sales_order\interceptor\C_Order.java
2
请完成以下Java代码
public Object readTree(String textValue) { try { return objectMapper.readTree(textValue); } catch (JsonProcessingException e) { throw new UncheckedIOException("Failed to read text value", e); } } @Override public Object readTree(byte[] bytes) { try { return objectMapper.readTree(bytes); } catch (IOException e) { throw new UncheckedIOException("Failed to read text value", e); } } @Override public Object deepCopy(Object value) { return ((JsonNode) value).deepCopy(); }
@Override public boolean isJsonNode(Object value) { return value instanceof JsonNode; } @Override public Object transformToJsonNode(Object value) { return FlowableJackson2JsonNode.asJsonNode(value, () -> objectMapper); } @Override public FlowableObjectNode createObjectNode() { return new FlowableJackson2ObjectNode(objectMapper.createObjectNode()); } @Override public FlowableArrayNode createArrayNode() { return new FlowableJackson2ArrayNode(objectMapper.createArrayNode()); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\json\jackson2\Jackson2VariableJsonMapper.java
1
请完成以下Java代码
public static Map<String, Object> map(Object... objects) { if (objects.length % 2 != 0) { throw new FlowableIllegalArgumentException("The input should always be even since we expect a list of key-value pairs!"); } Map<String, Object> map = new HashMap<>(); for (int i = 0; i < objects.length; i += 2) { map.put((String) objects[i], objects[i + 1]); } return map; } public static boolean isEmpty(@SuppressWarnings("rawtypes") Collection collection) { return (collection == null || collection.isEmpty()); } public static boolean isNotEmpty(@SuppressWarnings("rawtypes") Collection collection) { return !isEmpty(collection); } public static <T> List<List<T>> partition(Collection<T> values, int partitionSize) { if (values == null) { return null; } else if (values.isEmpty()) { return Collections.emptyList(); } List<T> valuesList; if (values instanceof List) { valuesList = (List<T>) values; } else { valuesList = new ArrayList<>(values); } int valuesSize = values.size(); if (valuesSize <= partitionSize) {
return Collections.singletonList(valuesList); } List<List<T>> safeValuesList = new ArrayList<>(); consumePartitions(values, partitionSize, safeValuesList::add); return safeValuesList; } public static <T> void consumePartitions(Collection<T> values, int partitionSize, Consumer<List<T>> partitionConsumer) { int valuesSize = values.size(); List<T> valuesList; if (values instanceof List) { valuesList = (List<T>) values; } else { valuesList = new ArrayList<>(values); } if (valuesSize <= partitionSize) { partitionConsumer.accept(valuesList); } else { for (int startIndex = 0; startIndex < valuesSize; startIndex += partitionSize) { int endIndex = startIndex + partitionSize; if (endIndex > valuesSize) { endIndex = valuesSize; // endIndex in #subList is exclusive } List<T> subList = valuesList.subList(startIndex, endIndex); partitionConsumer.accept(subList); } } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\util\CollectionUtil.java
1
请完成以下Java代码
public static void main(String[] args) { if (args.length != 4) { System.err.println("Usage: java " + ConnectionPerChannelPublisher.class.getName() + " <host> <#channels> <#messages> <payloadSize>"); System.exit(1); } ConnectionFactory factory = new ConnectionFactory(); factory.setHost(args[0]); int workerCount = Integer.parseInt(args[1]); int iterations = Integer.parseInt(args[2]); int payloadSize = Integer.parseInt(args[3]); // run the benchmark 10x and get the average throughput LongSummaryStatistics summary = IntStream.range(0, 9) .mapToObj(idx -> new ConnectionPerChannelPublisher(factory, workerCount, iterations, payloadSize)) .map(p -> p.call()) .collect(Collectors.summarizingLong((l) -> l)); log.info("[I66] workers={}, throughput={}", workerCount, (int)Math.floor(summary.getAverage())); } @Override public Long call() { try { List<Worker> workers = new ArrayList<>(); CountDownLatch counter = new CountDownLatch(workerCount); for (int i = 0; i < workerCount; i++) { Connection conn = factory.newConnection(); workers.add(new Worker("queue_" + i, conn, iterations, counter, payloadSize)); } ExecutorService executor = new ThreadPoolExecutor(workerCount, workerCount, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(workerCount, true));
long start = System.currentTimeMillis(); log.info("[I61] Starting {} workers...", workers.size()); executor.invokeAll(workers); if (counter.await(5, TimeUnit.MINUTES)) { long elapsed = System.currentTimeMillis() - start; log.info("[I59] Tasks completed: #workers={}, #iterations={}, elapsed={}ms, stats={}", workerCount, iterations, elapsed); return throughput(workerCount, iterations, elapsed); } else { throw new RuntimeException("[E61] Timeout waiting workers to complete"); } } catch (Exception ex) { throw new RuntimeException(ex); } } private static long throughput(int workerCount, int iterations, long elapsed) { return (iterations * workerCount * 1000) / elapsed; } }
repos\tutorials-master\messaging-modules\rabbitmq\src\main\java\com\baeldung\benchmark\ConnectionPerChannelPublisher.java
1
请完成以下Java代码
public class User implements Serializable, Cloneable { private static final long serialVersionUID = -3427002229954777557L; private String firstName; private String lastName; private Address address; public User(String firstName, String lastName, Address address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } public User(User that) { this(that.getFirstName(), that.getLastName(), new Address(that.getAddress())); } public User() { } @Override public Object clone() { User user; try {
user = (User) super.clone(); } catch (CloneNotSupportedException e) { user = new User(this.getFirstName(), this.getLastName(), this.getAddress()); } user.address = (Address) this.address.clone(); return user; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public Address getAddress() { return address; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-patterns\src\main\java\com\baeldung\deepcopy\User.java
1
请完成以下Java代码
protected void applyConfigurator(Map<String, DataFormat> dataFormats, DataFormatConfigurator configurator) { for (DataFormat dataFormat : dataFormats.values()) { if (configurator.getDataFormatClass().isAssignableFrom(dataFormat.getClass())) { configurator.configure(dataFormat); } } } public String checkHostname() { String hostname; try { hostname = getHostname(); } catch (UnknownHostException e) { throw LOG.cannotGetHostnameException(e); } return hostname; } public String getHostname() throws UnknownHostException { return InetAddress.getLocalHost().getHostName(); } public String getBaseUrl() { return urlResolver.getBaseUrl(); } protected String getWorkerId() { return workerId; } protected List<ClientRequestInterceptor> getInterceptors() { return interceptors; } protected int getMaxTasks() { return maxTasks; } protected Long getAsyncResponseTimeout() { return asyncResponseTimeout; } protected long getLockDuration() { return lockDuration; } protected boolean isAutoFetchingEnabled() { return isAutoFetchingEnabled; } protected BackoffStrategy getBackoffStrategy() { return backoffStrategy;
} public String getDefaultSerializationFormat() { return defaultSerializationFormat; } public String getDateFormat() { return dateFormat; } public ObjectMapper getObjectMapper() { return objectMapper; } public ValueMappers getValueMappers() { return valueMappers; } public TypedValues getTypedValues() { return typedValues; } public EngineClient getEngineClient() { return engineClient; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientBuilderImpl.java
1
请完成以下Java代码
public void setVariableLocal(String variableName, Object value) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public void setVariables(Map<String, ? extends Object> variables) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public void setVariablesLocal(Map<String, ? extends Object> variables) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public boolean hasVariables() { return false; } public boolean hasVariablesLocal() { return false; } public boolean hasVariable(String variableName) { return false; } public boolean hasVariableLocal(String variableName) { return false; } public void removeVariable(String variableName) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariableLocal(String variableName) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariables() { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariablesLocal() { throw new UnsupportedOperationException("No execution active, no variables can be removed");
} public void removeVariables(Collection<String> variableNames) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariablesLocal(Collection<String> variableNames) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public Map<String, CoreVariableInstance> getVariableInstances() { return Collections.emptyMap(); } public CoreVariableInstance getVariableInstance(String name) { return null; } public Map<String, CoreVariableInstance> getVariableInstancesLocal() { return Collections.emptyMap(); } public CoreVariableInstance getVariableInstanceLocal(String name) { return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\StartProcessVariableScope.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) {
this.lastName = lastName; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId=" + emailId + "]"; } }
repos\spring-boot-tutorial-master\springboot-mssql-jpa-hibernate-crud-example\src\main\java\net\javaguides\mssql\model\Employee.java
1
请在Spring Boot框架中完成以下Java代码
void configure(B http) { LogoutHandler oidcLogout = this.logoutHandler.apply(http); LogoutHandler sessionLogout = new SecurityContextLogoutHandler(); LogoutConfigurer<B> logout = http.getConfigurer(LogoutConfigurer.class); if (logout != null) { sessionLogout = new CompositeLogoutHandler(logout.getLogoutHandlers()); } OidcBackChannelLogoutFilter filter = new OidcBackChannelLogoutFilter(authenticationConverter(http), authenticationManager(), new EitherLogoutHandler(oidcLogout, sessionLogout)); http.addFilterBefore(filter, CsrfFilter.class); } @SuppressWarnings("unchecked") private <T> T getBeanOrNull(Class<?> clazz) { ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); if (context == null) { return null; } return (T) context.getBeanProvider(clazz).getIfUnique(); } private static final class EitherLogoutHandler implements LogoutHandler { private final LogoutHandler left;
private final LogoutHandler right; EitherLogoutHandler(LogoutHandler left, LogoutHandler right) { this.left = left; this.right = right; } @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { if (request.getParameter("_spring_security_internal_logout") == null) { this.left.logout(request, response, authentication); } else { this.right.logout(request, response, authentication); } } } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OidcLogoutConfigurer.java
2
请完成以下Java代码
public void afterSave(@NonNull final I_AD_User userRecord) { final BPartnerId bPartnerId = BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID()); if (bPartnerId == null) { //nothing to do return; } bpPartnerService.updateNameAndGreetingFromContacts(bPartnerId); } @ModelChange(timings = {ModelValidator.TYPE_BEFORE_DELETE}, ifUIAction = true) public void beforeDelete_UIAction(@NonNull final I_AD_User userRecord) { final UserId loggedInUserId = Env.getLoggedUserIdIfExists().orElse(null); if (loggedInUserId != null && loggedInUserId.getRepoId() == userRecord.getAD_User_ID()) { throw new AdempiereException(MSG_UserDelete) .setParameter("AD_User_ID", userRecord.getAD_User_ID()) .setParameter("Name", userRecord.getName()); } userBL.deleteUserDependency(userRecord); }
@ModelChange(timings = { ModelValidator.TYPE_AFTER_DELETE }, ifUIAction = true) public void afterDelete(@NonNull final I_AD_User userRecord) { final BPartnerId bPartnerId = BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID()); if (bPartnerId == null) { //nothing to do return; } bpPartnerService.updateNameAndGreetingFromContacts(bPartnerId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\AD_User.java
1
请在Spring Boot框架中完成以下Java代码
public String getUri() { return this.uri; } public void setUri(String uri) { this.uri = uri; } public Duration getMeterTimeToLive() { return this.meterTimeToLive; } public void setMeterTimeToLive(Duration meterTimeToLive) { this.meterTimeToLive = meterTimeToLive; } public boolean isLwcEnabled() { return this.lwcEnabled; } public void setLwcEnabled(boolean lwcEnabled) { this.lwcEnabled = lwcEnabled; } public Duration getLwcStep() { return this.lwcStep; } public void setLwcStep(Duration lwcStep) { this.lwcStep = lwcStep; } public boolean isLwcIgnorePublishStep() { return this.lwcIgnorePublishStep; } public void setLwcIgnorePublishStep(boolean lwcIgnorePublishStep) { this.lwcIgnorePublishStep = lwcIgnorePublishStep; }
public Duration getConfigRefreshFrequency() { return this.configRefreshFrequency; } public void setConfigRefreshFrequency(Duration configRefreshFrequency) { this.configRefreshFrequency = configRefreshFrequency; } public Duration getConfigTimeToLive() { return this.configTimeToLive; } public void setConfigTimeToLive(Duration configTimeToLive) { this.configTimeToLive = configTimeToLive; } public String getConfigUri() { return this.configUri; } public void setConfigUri(String configUri) { this.configUri = configUri; } public String getEvalUri() { return this.evalUri; } public void setEvalUri(String evalUri) { this.evalUri = evalUri; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasProperties.java
2
请完成以下Java代码
private void putIfNotEmpty(final DocumentLayoutDetailDescriptor detail, final ImmutableMap.Builder<DetailId, DocumentLayoutDetailDescriptor> map) { if (detail.isEmpty()) { return; } map.put(detail.getDetailId(), detail); } public Builder setWindowId(final WindowId windowId) { this.windowId = windowId; return this; } public Builder setCaption(final ITranslatableString caption) { this.caption = TranslatableStrings.nullToEmpty(caption); return this; } public Builder setDocumentSummaryElement(@Nullable final DocumentLayoutElementDescriptor documentSummaryElement) { this.documentSummaryElement = documentSummaryElement; return this; } public Builder setDocActionElement(@Nullable final DocumentLayoutElementDescriptor docActionElement) { this.docActionElement = docActionElement; return this; } public Builder setGridView(final ViewLayout.Builder gridView) { this._gridView = gridView; return this; } public Builder setSingleRowLayout(@NonNull final DocumentLayoutSingleRow.Builder singleRowLayout) { this.singleRowLayout = singleRowLayout; return this; } private DocumentLayoutSingleRow.Builder getSingleRowLayout() { return singleRowLayout; }
private ViewLayout.Builder getGridView() { return _gridView; } public Builder addDetail(@Nullable final DocumentLayoutDetailDescriptor detail) { if (detail == null) { return this; } if (detail.isEmpty()) { logger.trace("Skip adding detail to layout because it is empty; detail={}", detail); return this; } details.add(detail); return this; } public Builder setSideListView(final ViewLayout sideListViewLayout) { this._sideListView = sideListViewLayout; return this; } private ViewLayout getSideList() { Preconditions.checkNotNull(_sideListView, "sideList"); return _sideListView; } public Builder putDebugProperty(final String name, final String value) { debugProperties.put(name, value); return this; } public Builder setStopwatch(final Stopwatch stopwatch) { this.stopwatch = stopwatch; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDescriptor.java
1
请完成以下Java代码
public void setAD_Role(org.compiere.model.I_AD_Role AD_Role) { set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role); } /** Set Rolle. @param AD_Role_ID Responsibility Role */ @Override public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); } /** Get Rolle. @return Responsibility Role */ @Override public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Role Notification Group. @param AD_Role_NotificationGroup_ID Role Notification Group */ @Override public void setAD_Role_NotificationGroup_ID (int AD_Role_NotificationGroup_ID) { if (AD_Role_NotificationGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Role_NotificationGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_NotificationGroup_ID, Integer.valueOf(AD_Role_NotificationGroup_ID)); } /** Get Role Notification Group. @return Role Notification Group */ @Override public int getAD_Role_NotificationGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_NotificationGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description)
{ set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * NotificationType AD_Reference_ID=344 * Reference name: AD_User NotificationType */ public static final int NOTIFICATIONTYPE_AD_Reference_ID=344; /** EMail = E */ public static final String NOTIFICATIONTYPE_EMail = "E"; /** Notice = N */ public static final String NOTIFICATIONTYPE_Notice = "N"; /** None = X */ public static final String NOTIFICATIONTYPE_None = "X"; /** EMailPlusNotice = B */ public static final String NOTIFICATIONTYPE_EMailPlusNotice = "B"; /** NotifyUserInCharge = O */ public static final String NOTIFICATIONTYPE_NotifyUserInCharge = "O"; /** Set Benachrichtigungs-Art. @param NotificationType Art der Benachrichtigung */ @Override public void setNotificationType (java.lang.String NotificationType) { set_Value (COLUMNNAME_NotificationType, NotificationType); } /** Get Benachrichtigungs-Art. @return Art der Benachrichtigung */ @Override public java.lang.String getNotificationType () { return (java.lang.String)get_Value(COLUMNNAME_NotificationType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_NotificationGroup.java
1
请完成以下Java代码
public String getVatNumber() { return vatNumber; } /** * Sets the value of the vatNumber property. * * @param value * allowed object is * {@link String } * */ public void setVatNumber(String value) { this.vatNumber = value; } /** * Gets the value of the paymentPeriod property. * * @return * possible object is * {@link Duration } * */ public Duration getPaymentPeriod() {
return paymentPeriod; } /** * Sets the value of the paymentPeriod property. * * @param value * allowed object is * {@link Duration } * */ public void setPaymentPeriod(Duration value) { this.paymentPeriod = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\BalanceType.java
1
请完成以下Java代码
public class MybatisTest extends BaseTest { private SqlSessionFactory sqlSessionFactory; @Before public void init() throws IOException { String resource = "config/mybatis-config.xml"; try (InputStream inputStream = Resources.getResourceAsStream(resource)) { // 1.读取mybatis配置文件创SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } } @Test // 面向接口编程模型 public void quickStart() throws Exception { // 2.获取sqlSession try (SqlSession sqlSession = sqlSessionFactory.openSession()) { initH2dbMybatis(sqlSession); // 3.获取对应mapper PersonMapper mapper = sqlSession.getMapper(PersonMapper.class); JdkProxySourceClassUtil.writeClassToDisk(mapper.getClass().getSimpleName(), mapper.getClass()); // 4.执行查询语句并返回结果 Person person = mapper.selectByPrimaryKey(1L);
System.out.println(person.toString()); } } @Test // ibatis编程模型 public void quickStartIBatis() throws Exception { // 2.获取sqlSession try (SqlSession sqlSession = sqlSessionFactory.openSession()) { initH2dbMybatis(sqlSession); // ibatis编程模型(与配置文件耦合严重) Person person = sqlSession.selectOne("com.xiaolyuh.domain.mapper.PersonMapper.selectByPrimaryKey", 1L); System.out.println(person.toString()); } } }
repos\spring-boot-student-master\spring-boot-student-mybatis\src\main\java\com\xiaolyuh\mybatis\MybatisTest.java
1
请完成以下Java代码
public String getId() { return id; } public String getName() { return name; } public String getAssignee() { return assignee; } public Date getCreated() { return created; } public Date getDue() { return due; } public DelegationState getDelegationState() { return delegationState; } public String getDescription() { return description; } public String getExecutionId() { return executionId; } public String getOwner() { return owner; } public String getParentTaskId() { return parentTaskId; } public int getPriority() { return priority; } public String getProcessDefinitionId() {
return processDefinitionId; } public String getProcessInstanceId() { return processInstanceId; } public String getTaskDefinitionKey() { return taskDefinitionKey; } public Date getFollowUp() { return followUp; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseExecutionId() { return caseExecutionId; } public String getCaseInstanceId() { return caseInstanceId; } public boolean isSuspended() { return suspended; } public String getFormKey() { return formKey; } public CamundaFormRef getCamundaFormRef() { return camundaFormRef; } public String getTenantId() { return tenantId; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\task\HalTask.java
1
请完成以下Java代码
public static ExcelFormat getDefaultFormat() { return getFormatByFileExtension(getDefaultFileExtension()); } public static Set<String> getFileExtensionsDefaultFirst() { return ImmutableSet.<String> builder() .add(getDefaultFileExtension()) // default one first .addAll(getFileExtensions()) .build(); } public static Set<String> getFileExtensions() { return ALL_FORMATS.stream() .map(ExcelFormat::getFileExtension) .collect(ImmutableSet.toImmutableSet());
} public static ExcelFormat getFormatByFile(@NonNull final File file) { final String fileExtension = Files.getFileExtension(file.getPath()); return getFormatByFileExtension(fileExtension); } public static ExcelFormat getFormatByFileExtension(@NonNull final String fileExtension) { return ALL_FORMATS .stream() .filter(format -> fileExtension.equals(format.getFileExtension())) .findFirst() .orElseThrow(() -> new AdempiereException( "No " + ExcelFormat.class.getSimpleName() + " found for file extension '" + fileExtension + "'." + "\n Supported extensions are: " + getFileExtensions())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\ExcelFormats.java
1
请完成以下Java代码
public class MapExceptionEntry { String errorCode; String className; boolean andChildren; public MapExceptionEntry(String errorCode, String className, boolean andChildren) { this.errorCode = errorCode; this.className = className; this.andChildren = andChildren; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; }
public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public boolean isAndChildren() { return andChildren; } public void setAndChildren(boolean andChildren) { this.andChildren = andChildren; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MapExceptionEntry.java
1
请完成以下Java代码
public abstract class AbstractEntity implements Entity, HasRevision { protected String id; protected int revision = 1; protected boolean isInserted; protected boolean isUpdated; protected boolean isDeleted; @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } public int getRevisionNext() { return revision + 1; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; }
public boolean isInserted() { return isInserted; } public void setInserted(boolean isInserted) { this.isInserted = isInserted; } public boolean isUpdated() { return isUpdated; } public void setUpdated(boolean isUpdated) { this.isUpdated = isUpdated; } public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean isDeleted) { this.isDeleted = isDeleted; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractEntity.java
1
请完成以下Java代码
protected InputStream getResourceForFormKey(FormData formData, String formKey) { String resourceName = formKey; if (resourceName.startsWith(EMBEDDED_KEY)) { resourceName = resourceName.substring(EMBEDDED_KEY_LENGTH, resourceName.length()); } else if (resourceName.startsWith(CAMUNDA_FORMS_KEY)) { resourceName = resourceName.substring(CAMUNDA_FORMS_KEY_LENGTH, resourceName.length()); } if (!resourceName.startsWith(DEPLOYMENT_KEY)) { throw new BadUserRequestException("The form key '" + formKey + "' does not reference a deployed form."); } resourceName = resourceName.substring(DEPLOYMENT_KEY_LENGTH, resourceName.length()); return getDeploymentResource(formData.getDeploymentId(), resourceName); } protected InputStream getResourceForCamundaFormRef(CamundaFormRef camundaFormRef, String deploymentId) { CamundaFormDefinition definition = commandContext.runWithoutAuthorization( new GetCamundaFormDefinitionCmd(camundaFormRef, deploymentId));
if (definition == null) { throw new NotFoundException("No Camunda Form Definition was found for Camunda Form Ref: " + camundaFormRef); } return getDeploymentResource(definition.getDeploymentId(), definition.getResourceName()); } protected InputStream getDeploymentResource(String deploymentId, String resourceName) { GetDeploymentResourceCmd getDeploymentResourceCmd = new GetDeploymentResourceCmd(deploymentId, resourceName); try { return commandContext.runWithoutAuthorization(getDeploymentResourceCmd); } catch (DeploymentResourceNotFoundException e) { throw new NotFoundException("The form with the resource name '" + resourceName + "' cannot be found in deployment with id " + deploymentId, e); } } protected abstract FormData getFormData(); protected abstract void checkAuthorization(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractGetDeployedFormCmd.java
1
请完成以下Java代码
private JobExecutorXml getJobExecutorXml(DeploymentOperation operationContext) { BpmPlatformXml bpmPlatformXml = operationContext.getAttachment(Attachments.BPM_PLATFORM_XML); JobExecutorXml jobExecutorXml = bpmPlatformXml.getJobExecutor(); return jobExecutorXml; } private int getQueueSize(JobExecutorXml jobExecutorXml) { String queueSize = jobExecutorXml.getProperties().get(JobExecutorXml.QUEUE_SIZE); if (queueSize == null) { return DEFAULT_QUEUE_SIZE; } return Integer.parseInt(queueSize); } private long getKeepAliveTime(JobExecutorXml jobExecutorXml) { String keepAliveTime = jobExecutorXml.getProperties().get(JobExecutorXml.KEEP_ALIVE_TIME); if (keepAliveTime == null) { return DEFAULT_KEEP_ALIVE_TIME_MS; } return Long.parseLong(keepAliveTime); }
private int getMaxPoolSize(JobExecutorXml jobExecutorXml) { String maxPoolSize = jobExecutorXml.getProperties().get(JobExecutorXml.MAX_POOL_SIZE); if (maxPoolSize == null) { return DEFAULT_MAX_POOL_SIZE; } return Integer.parseInt(maxPoolSize); } private int getCorePoolSize(JobExecutorXml jobExecutorXml) { String corePoolSize = jobExecutorXml.getProperties().get(JobExecutorXml.CORE_POOL_SIZE); if (corePoolSize == null) { return DEFAULT_CORE_POOL_SIZE; } return Integer.parseInt(corePoolSize); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\jobexecutor\StartManagedThreadPoolStep.java
1
请完成以下Java代码
public void setText(final String text) { message.setText(text); display(); } // setText /** * Show Window * * @param visible true if visible */ @Override public void setVisible(final boolean visible) { super.setVisible(visible); if (visible) { toFront(); } } // setVisible /** * Calculate size and display
*/ private void display() { pack(); final Dimension ss = Toolkit.getDefaultToolkit().getScreenSize(); final Rectangle bounds = getBounds(); setBounds((ss.width - bounds.width) / 2, (ss.height - bounds.height) / 2, bounds.width, bounds.height); setVisible(true); } // display /** * Dispose Splash */ @Override public void dispose() { super.dispose(); s_splash = null; } // dispose } // Splash
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Splash.java
1
请完成以下Java代码
public class X_U_Web_Properties extends PO implements I_U_Web_Properties, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_U_Web_Properties (Properties ctx, int U_Web_Properties_ID, String trxName) { super (ctx, U_Web_Properties_ID, trxName); /** if (U_Web_Properties_ID == 0) { setU_Key (null); setU_Value (null); setU_Web_Properties_ID (0); } */ } /** Load Constructor */ public X_U_Web_Properties (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 7 - System - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_U_Web_Properties[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Key. @param U_Key Key */ public void setU_Key (String U_Key) { set_Value (COLUMNNAME_U_Key, U_Key); } /** Get Key. @return Key */ public String getU_Key () {
return (String)get_Value(COLUMNNAME_U_Key); } /** Set Value. @param U_Value Value */ public void setU_Value (String U_Value) { set_Value (COLUMNNAME_U_Value, U_Value); } /** Get Value. @return Value */ public String getU_Value () { return (String)get_Value(COLUMNNAME_U_Value); } /** Set Web Properties. @param U_Web_Properties_ID Web Properties */ public void setU_Web_Properties_ID (int U_Web_Properties_ID) { if (U_Web_Properties_ID < 1) set_ValueNoCheck (COLUMNNAME_U_Web_Properties_ID, null); else set_ValueNoCheck (COLUMNNAME_U_Web_Properties_ID, Integer.valueOf(U_Web_Properties_ID)); } /** Get Web Properties. @return Web Properties */ public int getU_Web_Properties_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_U_Web_Properties_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_U_Web_Properties.java
1
请完成以下Java代码
public class DefaultOutboundEvent<T> implements OutboundEvent<T> { protected final T body; protected final EventInstance eventInstance; protected final Map<String, Object> headers; public DefaultOutboundEvent(T body, EventInstance eventInstance) { this(body, eventInstance, Collections.emptyMap()); } public DefaultOutboundEvent(T body, EventInstance eventInstance, Map<String, Object> headers) { this.body = body; this.eventInstance = eventInstance; this.headers = headers; }
@Override public T getBody() { return body; } @Override public Map<String, Object> getHeaders() { return headers; } @Override public EventInstance getEventInstance() { return eventInstance; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\DefaultOutboundEvent.java
1
请完成以下Java代码
private final IMeter getMeter(final String meterName) { final String moduleName = Async_Constants.ENTITY_TYPE; final String meterNameFQ = workpackageProcessorName + "_" + meterName; return Services.get(IMonitoringBL.class).createOrGet(moduleName, meterNameFQ); } /** * NOTE: there is nothing to clone, since this is just an accessor for {@link IMeter}s * * @return this */ @Override public MonitorableQueueProcessorStatistics clone() { return this; } @Override public long getCountAll() { return getMeter(METERNAME_All).getGauge(); } @Override public void incrementCountAll() { getMeter(METERNAME_All).plusOne(); } @Override public long getCountProcessed() { return getMeter(METERNAME_Processed).getGauge(); } @Override public void incrementCountProcessed() { getMeter(METERNAME_Processed).plusOne(); } @Override public long getCountErrors() { return getMeter(METERNAME_Error).getGauge(); } @Override public void incrementCountErrors() { getMeter(METERNAME_Error).plusOne(); }
@Override public long getQueueSize() { return getMeter(METERNAME_QueueSize).getGauge(); } @Override public void incrementQueueSize() { getMeter(METERNAME_QueueSize).plusOne(); } @Override public void decrementQueueSize() { getMeter(METERNAME_QueueSize).minusOne(); } @Override public long getCountSkipped() { return getMeter(METERNAME_Skipped).getGauge(); } @Override public void incrementCountSkipped() { getMeter(METERNAME_Skipped).plusOne(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\MonitorableQueueProcessorStatistics.java
1
请完成以下Java代码
public void setIsNotifyUserInCharge (final boolean IsNotifyUserInCharge) { set_Value (COLUMNNAME_IsNotifyUserInCharge, IsNotifyUserInCharge); } @Override public boolean isNotifyUserInCharge() { return get_ValueAsBoolean(COLUMNNAME_IsNotifyUserInCharge); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setTermDuration (final int TermDuration) { set_Value (COLUMNNAME_TermDuration, TermDuration); } @Override public int getTermDuration() { return get_ValueAsInt(COLUMNNAME_TermDuration); } /** * TermDurationUnit AD_Reference_ID=540281 * Reference name: TermDurationUnit */ public static final int TERMDURATIONUNIT_AD_Reference_ID=540281; /** Monat(e) = month */ public static final String TERMDURATIONUNIT_MonatE = "month"; /** Woche(n) = week */ public static final String TERMDURATIONUNIT_WocheN = "week"; /** Tag(e) = day */ public static final String TERMDURATIONUNIT_TagE = "day";
/** Jahr(e) = year */ public static final String TERMDURATIONUNIT_JahrE = "year"; @Override public void setTermDurationUnit (final java.lang.String TermDurationUnit) { set_Value (COLUMNNAME_TermDurationUnit, TermDurationUnit); } @Override public java.lang.String getTermDurationUnit() { return get_ValueAsString(COLUMNNAME_TermDurationUnit); } @Override public void setTermOfNotice (final int TermOfNotice) { set_Value (COLUMNNAME_TermOfNotice, TermOfNotice); } @Override public int getTermOfNotice() { return get_ValueAsInt(COLUMNNAME_TermOfNotice); } /** * TermOfNoticeUnit AD_Reference_ID=540281 * Reference name: TermDurationUnit */ public static final int TERMOFNOTICEUNIT_AD_Reference_ID=540281; /** Monat(e) = month */ public static final String TERMOFNOTICEUNIT_MonatE = "month"; /** Woche(n) = week */ public static final String TERMOFNOTICEUNIT_WocheN = "week"; /** Tag(e) = day */ public static final String TERMOFNOTICEUNIT_TagE = "day"; /** Jahr(e) = year */ public static final String TERMOFNOTICEUNIT_JahrE = "year"; @Override public void setTermOfNoticeUnit (final java.lang.String TermOfNoticeUnit) { set_Value (COLUMNNAME_TermOfNoticeUnit, TermOfNoticeUnit); } @Override public java.lang.String getTermOfNoticeUnit() { return get_ValueAsString(COLUMNNAME_TermOfNoticeUnit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Transition.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; }
public String getArticleId() { return articleId; } public void setArticleId(String articleId) { this.articleId = articleId; } @Override public String toString() { return "CommentEntity{" + "id='" + id + '\'' + ", comment='" + comment + '\'' + ", articleId='" + articleId + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\CommentEntity.java
2
请在Spring Boot框架中完成以下Java代码
public static QuotationLineKey extractKey(@NonNull final ServiceRepairProjectCostCollector costCollector) { return QuotationLineKey.builder() .groupKey(QuotationLinesGroupAggregator.extractKey(costCollector)) .type(costCollector.getType()) .productId(costCollector.getProductId()) .uomId(costCollector.getUomId()) .asiId(costCollector.getAsiId()) .build(); } public QuotationLineAggregator add(@NonNull final ServiceRepairProjectCostCollector costCollector) { Check.assumeEquals(extractKey(costCollector), key, "key does not match for {}. Expected: {}", costCollector, key); qty = qty.add(costCollector.getQtyReservedOrConsumed()); costCollectorIds.add(costCollector.getId()); return this; } public void createOrderLines(@NonNull final OrderFactory orderFactory) { if (this.orderLineBuilderUsed != null) { throw new AdempiereException("Order line was already created for " + this); // shall not happen } this.orderLineBuilderUsed = orderFactory.newOrderLine() .productId(key.getProductId()) .asiId(key.getAsiId()) .qty(qty) .manualPrice(isZeroPrice() ? Money.zero(priceCalculator.getCurrencyId()) : null) .description(description) .hideWhenPrinting(isHideWhenPrinting()) .details(details); } private boolean isZeroPrice() { return zeroPrice != null ? zeroPrice : key.isZeroPrice(); }
private boolean isHideWhenPrinting() { return key.getType() == ServiceRepairProjectCostCollectorType.SparePartsOwnedByCustomer; } public Stream<Map.Entry<ServiceRepairProjectCostCollectorId, OrderAndLineId>> streamQuotationLineIdsIndexedByCostCollectorId() { if (orderLineBuilderUsed == null) { return Stream.empty(); } else { final OrderAndLineId quotationLineId = orderLineBuilderUsed.getCreatedOrderAndLineId(); return costCollectorIds.stream().map(costCollectorId -> GuavaCollectors.entry(costCollectorId, quotationLineId)); } } public QuotationLineAggregator description(@Nullable final String description) { this.description = description; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\createQuotationFromProjectCommand\QuotationLineAggregator.java
2
请完成以下Java代码
public static <K, V> KafkaResourceHolder<K, V> getTransactionalResourceHolder( final ProducerFactory<K, V> producerFactory, @Nullable String txIdPrefix, Duration closeTimeout) { Assert.notNull(producerFactory, "ProducerFactory must not be null"); @SuppressWarnings("unchecked") KafkaResourceHolder<K, V> resourceHolder = (KafkaResourceHolder<K, V>) TransactionSynchronizationManager .getResource(producerFactory); if (resourceHolder == null) { Producer<K, V> producer = producerFactory.createProducer(txIdPrefix); try { producer.beginTransaction(); } catch (RuntimeException e) { producer.close(closeTimeout); throw e; } resourceHolder = new KafkaResourceHolder<>(producer, closeTimeout); bindResourceToTransaction(resourceHolder, producerFactory); } return resourceHolder; } public static <K, V> void releaseResources(@Nullable KafkaResourceHolder<K, V> resourceHolder) { if (resourceHolder != null) { resourceHolder.close(); } } private static <K, V> void bindResourceToTransaction(KafkaResourceHolder<K, V> resourceHolder, ProducerFactory<K, V> producerFactory) { TransactionSynchronizationManager.bindResource(producerFactory, resourceHolder); resourceHolder.setSynchronizedWithTransaction(true); if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager .registerSynchronization(new KafkaResourceSynchronization<>(resourceHolder, producerFactory)); } } /** * Callback for resource cleanup at the end of a non-native Kafka transaction (e.g. when participating in a * JtaTransactionManager transaction). * @see org.springframework.transaction.jta.JtaTransactionManager */ private static final class KafkaResourceSynchronization<K, V> extends ResourceHolderSynchronization<KafkaResourceHolder<K, V>, Object> { private final KafkaResourceHolder<K, V> resourceHolder; KafkaResourceSynchronization(KafkaResourceHolder<K, V> resourceHolder, Object resourceKey) { super(resourceHolder, resourceKey); this.resourceHolder = resourceHolder; } @Override protected boolean shouldReleaseBeforeCompletion() { return false;
} @Override protected void processResourceAfterCommit(KafkaResourceHolder<K, V> resourceHolder) { resourceHolder.commit(); } @Override public void afterCompletion(int status) { try { if (status == TransactionSynchronization.STATUS_COMMITTED) { this.resourceHolder.commit(); } else { this.resourceHolder.rollback(); } } finally { super.afterCompletion(status); } } @Override protected void releaseResource(KafkaResourceHolder<K, V> holder, Object resourceKey) { ProducerFactoryUtils.releaseResources(holder); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\ProducerFactoryUtils.java
1
请完成以下Java代码
public Query<FlowNode> getSucceedingNodes() { Collection<FlowNode> succeedingNodes = new HashSet<FlowNode>(); for (SequenceFlow sequenceFlow : getOutgoing()) { succeedingNodes.add(sequenceFlow.getTarget()); } return new QueryImpl<FlowNode>(succeedingNodes); } /** Camunda Attributes */ public boolean isCamundaAsyncBefore() { return camundaAsyncBefore.getValue(this); } public void setCamundaAsyncBefore(boolean isCamundaAsyncBefore) { camundaAsyncBefore.setValue(this, isCamundaAsyncBefore); } public boolean isCamundaAsyncAfter() { return camundaAsyncAfter.getValue(this); } public void setCamundaAsyncAfter(boolean isCamundaAsyncAfter) {
camundaAsyncAfter.setValue(this, isCamundaAsyncAfter); } public boolean isCamundaExclusive() { return camundaExclusive.getValue(this); } public void setCamundaExclusive(boolean isCamundaExclusive) { camundaExclusive.setValue(this, isCamundaExclusive); } public String getCamundaJobPriority() { return camundaJobPriority.getValue(this); } public void setCamundaJobPriority(String jobPriority) { camundaJobPriority.setValue(this, jobPriority); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\FlowNodeImpl.java
1
请完成以下Java代码
public void addHandlers(List<BpmnParseHandler> bpmnParseHandlers) { for (BpmnParseHandler bpmnParseHandler : bpmnParseHandlers) { addHandler(bpmnParseHandler); } } public void addHandler(BpmnParseHandler bpmnParseHandler) { for (Class<? extends BaseElement> type : bpmnParseHandler.getHandledTypes()) { List<BpmnParseHandler> handlers = parseHandlers.get(type); if (handlers == null) { handlers = new ArrayList<BpmnParseHandler>(); parseHandlers.put(type, handlers); } handlers.add(bpmnParseHandler); } } public void parseElement(BpmnParse bpmnParse, BaseElement element) { if (element instanceof DataObject) { // ignore DataObject elements because they are processed on Process
// and Sub process level return; } if (element instanceof FlowElement) { bpmnParse.setCurrentFlowElement((FlowElement) element); } // Execute parse handlers List<BpmnParseHandler> handlers = parseHandlers.get(element.getClass()); if (handlers == null) { LOGGER.warn("Could not find matching parse handler for + " + element.getId() + " this is likely a bug."); } else { for (BpmnParseHandler handler : handlers) { handler.parse(bpmnParse, element); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParseHandlers.java
1
请完成以下Java代码
public EmployerAddressType getEmployer() { return employer; } /** * Sets the value of the employer property. * * @param value * allowed object is * {@link EmployerAddressType } * */ public void setEmployer(EmployerAddressType value) { this.employer = value; } /** * Gets the value of the paymentPeriod property. * * @return * possible object is
* {@link Duration } * */ public Duration getPaymentPeriod() { return paymentPeriod; } /** * Sets the value of the paymentPeriod property. * * @param value * allowed object is * {@link Duration } * */ public void setPaymentPeriod(Duration value) { this.paymentPeriod = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\GarantType.java
1
请在Spring Boot框架中完成以下Java代码
public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public Region timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Region region = (Region) o; return Objects.equals(this._id, region._id) && Objects.equals(this.label, region.label) && Objects.equals(this.parent, region.parent) && Objects.equals(this.timestamp, region.timestamp); } @Override public int hashCode() { return Objects.hash(_id, label, parent, timestamp); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Region {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" label: ").append(toIndentedString(label)).append("\n"); sb.append(" parent: ").append(toIndentedString(parent)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Region.java
2
请完成以下Java代码
public int write(ByteBuffer src) throws IOException { throw new NonWritableChannelException(); } @Override public long position() throws IOException { assertNotClosed(); return this.position; } @Override public SeekableByteChannel position(long position) throws IOException { assertNotClosed(); if (position < 0 || position >= this.size) { throw new IllegalArgumentException("Position must be in bounds"); } this.position = position; return this; } @Override public long size() throws IOException { assertNotClosed(); return this.size; } @Override public SeekableByteChannel truncate(long size) throws IOException { throw new NonWritableChannelException(); } private void assertNotClosed() throws ClosedChannelException { if (this.closed) { throw new ClosedChannelException(); } } /** * Resources used by the channel and suitable for registration with a {@link Cleaner}. */ static class Resources implements Runnable {
private final ZipContent zipContent; private final CloseableDataBlock data; Resources(Path path, String nestedEntryName) throws IOException { this.zipContent = ZipContent.open(path, nestedEntryName); this.data = this.zipContent.openRawZipData(); } DataBlock getData() { return this.data; } @Override public void run() { releaseAll(); } private void releaseAll() { IOException exception = null; try { this.data.close(); } catch (IOException ex) { exception = ex; } try { this.zipContent.close(); } catch (IOException ex) { if (exception != null) { ex.addSuppressed(exception); } exception = ex; } if (exception != null) { throw new UncheckedIOException(exception); } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedByteChannel.java
1
请完成以下Java代码
private static String extractParameter(final Evaluatee ctx, final String parameterName) { if (ctx instanceof Evaluatee2) { final Evaluatee2 ctx2 = (Evaluatee2)ctx; if (!ctx2.has_Variable(parameterName)) { return null; } return ctx2.get_ValueAsString(parameterName); } else { final String value = ctx.get_ValueAsString(parameterName); if (Env.isPropertyValueNull(parameterName, value)) { return null; } return value; } } public static final EffectiveValuesEvaluatee of(@Nullable final Map<String, String> values) { if (values == null || values.isEmpty()) { return EMPTY; } return new EffectiveValuesEvaluatee(ImmutableMap.copyOf(values)); } public static final EffectiveValuesEvaluatee EMPTY = new EffectiveValuesEvaluatee(ImmutableMap.of()); private final ImmutableMap<String, String> values; private EffectiveValuesEvaluatee(final ImmutableMap<String, String> values) { this.values = values; } @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(values) .toString(); } @Override public int hashCode() {
return Objects.hash(values); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!getClass().equals(obj.getClass())) { return false; } final EffectiveValuesEvaluatee other = (EffectiveValuesEvaluatee)obj; return values.equals(other.values); } @Override public String get_ValueAsString(final String variableName) { return values.get(variableName); } @Override public boolean has_Variable(final String variableName) { return values.containsKey(variableName); } @Override public String get_ValueOldAsString(final String variableName) { // TODO Auto-generated method stub return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\CachedStringExpression.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
repos\tutorials-master\persistence-modules\deltaspike\src\main\java\baeldung\model\User.java
1
请完成以下Java代码
public class MutableAttributeSplitRequest implements IAttributeSplitRequest { private final IAttributeStorage parentAttributeStorage; private final List<IAttributeStorage> attributeStorages; private final I_M_Attribute attribute; private IAttributeStorage attributeStorageCurrent; private Integer attributeStorageCurrentIndex = null; private Object valueInitial; private Object valueToSplit; public MutableAttributeSplitRequest(final IAttributeStorage parentAttributeStorage, final List<IAttributeStorage> attributeStorages, final org.compiere.model.I_M_Attribute attribute) { super(); Check.assumeNotNull(parentAttributeStorage, "parentAttributeStorage not null"); this.parentAttributeStorage = parentAttributeStorage; Check.assumeNotNull(attributeStorages, "attributeStorages not null"); this.attributeStorages = Collections.unmodifiableList(attributeStorages); Check.assumeNotNull(attribute, "attribute not null"); this.attribute = InterfaceWrapperHelper.create(attribute, I_M_Attribute.class); } @Override public IAttributeStorage getParentAttributeStorage() { return parentAttributeStorage; } @Override public List<IAttributeStorage> getAttributeStorages() { return attributeStorages; } @Override public IAttributeStorage getAttributeStorageCurrent() { Check.assumeNotNull(attributeStorageCurrent, "attributeStorageCurrent shall be set before"); return attributeStorageCurrent; } @Override public I_M_Attribute getM_Attribute() { return attribute; } public void setAttributeStorageCurrent(final IAttributeStorage attributeStorageCurrent) { this.attributeStorageCurrent = attributeStorageCurrent; } public void setAttributeStorageCurrentIndex(final int attributeStorageCurrentIndex) { this.attributeStorageCurrentIndex = attributeStorageCurrentIndex; } @Override
public int getAttributeStorageCurrentIndex() { Check.assumeNotNull(attributeStorageCurrentIndex, "attributeStorageCurrentIndex shall be set before"); return attributeStorageCurrentIndex; } @Override public Object getValueInitial() { return valueInitial; } public void setValueInitial(final Object valueInitial) { this.valueInitial = valueInitial; } @Override public Object getValueToSplit() { return valueToSplit; } public void setValueToSplit(final Object valueToSplit) { this.valueToSplit = valueToSplit; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\MutableAttributeSplitRequest.java
1
请在Spring Boot框架中完成以下Java代码
DispatcherFilter remoteDevToolsDispatcherFilter(AccessManager accessManager, Collection<HandlerMapper> mappers) { Dispatcher dispatcher = new Dispatcher(accessManager, mappers); return new DispatcherFilter(dispatcher); } /** * Configuration for remote update and restarts. */ @Configuration(proxyBeanMethods = false) @ConditionalOnBooleanProperty(name = "spring.devtools.remote.restart.enabled", matchIfMissing = true) static class RemoteRestartConfiguration { @Bean @ConditionalOnMissingBean SourceDirectoryUrlFilter remoteRestartSourceDirectoryUrlFilter() { return new DefaultSourceDirectoryUrlFilter(); } @Bean @ConditionalOnMissingBean
HttpRestartServer remoteRestartHttpRestartServer(SourceDirectoryUrlFilter sourceDirectoryUrlFilter) { return new HttpRestartServer(sourceDirectoryUrlFilter); } @Bean @ConditionalOnMissingBean(name = "remoteRestartHandlerMapper") UrlHandlerMapper remoteRestartHandlerMapper(HttpRestartServer server, ServerProperties serverProperties, DevToolsProperties properties) { Servlet servlet = serverProperties.getServlet(); RemoteDevToolsProperties remote = properties.getRemote(); String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : ""; String url = servletContextPath + remote.getContextPath() + "/restart"; logger.warn(LogMessage.format("Listening for remote restart updates on %s", url)); Handler handler = new HttpRestartServerHandler(server); return new UrlHandlerMapper(url, handler); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\RemoteDevToolsAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public int compareTo(ItemMetadata o) { return getName().compareTo(o.getName()); } public static ItemMetadata newGroup(String name, String type, String sourceType, String sourceMethod) { return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, sourceMethod, null, null, null); } public static ItemMetadata newProperty(String prefix, String name, String type, String sourceType, String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) { return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, sourceMethod, description, defaultValue, deprecation); } public static String newItemMetadataPrefix(String prefix, String suffix) { return prefix.toLowerCase(Locale.ENGLISH) + ConventionUtils.toDashedCase(suffix); } /** * The item type. */
public enum ItemType { /** * Group item type. */ GROUP, /** * Property item type. */ PROPERTY } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemMetadata.java
2
请完成以下Java代码
protected void configureQuery(BatchStatisticsQueryImpl batchQuery) { getAuthorizationManager().configureBatchStatisticsQuery(batchQuery); getTenantManager().configureQuery(batchQuery); } protected void checkReadProcessDefinition(ActivityStatisticsQueryImpl query) { CommandContext commandContext = getCommandContext(); if (isAuthorizationEnabled() && getCurrentAuthentication() != null && commandContext.isAuthorizationCheckEnabled()) { String processDefinitionId = query.getProcessDefinitionId(); ProcessDefinitionEntity definition = getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId); ensureNotNull("no deployed process definition found with id '" + processDefinitionId + "'", "processDefinition", definition); getAuthorizationManager().checkAuthorization(READ, PROCESS_DEFINITION, definition.getKey()); } } public long getStatisticsCountGroupedByDecisionRequirementsDefinition(HistoricDecisionInstanceStatisticsQueryImpl decisionRequirementsDefinitionStatisticsQuery) { configureQuery(decisionRequirementsDefinitionStatisticsQuery); return (Long) getDbEntityManager().selectOne("selectDecisionDefinitionStatisticsCount", decisionRequirementsDefinitionStatisticsQuery); }
protected void configureQuery(HistoricDecisionInstanceStatisticsQueryImpl decisionRequirementsDefinitionStatisticsQuery) { checkReadDecisionRequirementsDefinition(decisionRequirementsDefinitionStatisticsQuery); getTenantManager().configureQuery(decisionRequirementsDefinitionStatisticsQuery); } protected void checkReadDecisionRequirementsDefinition(HistoricDecisionInstanceStatisticsQueryImpl query) { CommandContext commandContext = getCommandContext(); if (isAuthorizationEnabled() && getCurrentAuthentication() != null && commandContext.isAuthorizationCheckEnabled()) { String decisionRequirementsDefinitionId = query.getDecisionRequirementsDefinitionId(); DecisionRequirementsDefinition definition = getDecisionRequirementsDefinitionManager().findDecisionRequirementsDefinitionById(decisionRequirementsDefinitionId); ensureNotNull("no deployed decision requirements definition found with id '" + decisionRequirementsDefinitionId + "'", "decisionRequirementsDefinition", definition); getAuthorizationManager().checkAuthorization(READ, DECISION_REQUIREMENTS_DEFINITION, definition.getKey()); } } public List<HistoricDecisionInstanceStatistics> getStatisticsGroupedByDecisionRequirementsDefinition(HistoricDecisionInstanceStatisticsQueryImpl query, Page page) { configureQuery(query); return getDbEntityManager().selectList("selectDecisionDefinitionStatistics", query, page); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\StatisticsManager.java
1
请完成以下Java代码
public class C_InvoiceExport extends AbstractEdiDocExtensionExport<I_C_Invoice> { /** * EXP_Format.Value for exporting Invoice EDI documents */ private static final String CST_INVOICE_EXP_FORMAT = "EDI_cctop_invoic_v"; private final IMsgBL msgBL = Services.get(IMsgBL.class); public C_InvoiceExport(final I_C_Invoice invoice, final String tableIdentifier, final ClientId clientId) { super(invoice, tableIdentifier, clientId); } @Override public List<Exception> doExport() { final IEDIDocumentBL ediDocumentBL = Services.get(IEDIDocumentBL.class); final I_C_Invoice document = getDocument(); final List<Exception> feedback = ediDocumentBL.isValidInvoice(document); final String EDIStatus = document.getEDI_ExportStatus(); final ValidationState validationState = ediDocumentBL.updateInvalid(document, EDIStatus, feedback, true); // saveLocally=true if (ValidationState.ALREADY_VALID != validationState) { // otherwise, it's either INVALID, or freshly updated (which, keeping the old logic, must be dealt with in one more step) return feedback; } assertEligible(document); // Mark the invoice as: EDI starting document.setEDI_ExportStatus(I_EDI_Document_Extension.EDI_EXPORTSTATUS_SendingStarted); InterfaceWrapperHelper.save(document);
try { exportEDI(I_EDI_cctop_invoic_v.class, C_InvoiceExport.CST_INVOICE_EXP_FORMAT, I_EDI_cctop_invoic_v.Table_Name, I_EDI_cctop_invoic_v.COLUMNNAME_C_Invoice_ID); } catch (final Exception e) { document.setEDI_ExportStatus(I_EDI_Document_Extension.EDI_EXPORTSTATUS_Error); final ITranslatableString errorMsgTrl = TranslatableStrings.parse(e.getLocalizedMessage()); document.setEDIErrorMsg(errorMsgTrl.translate(Env.getAD_Language())); InterfaceWrapperHelper.save(document); throw AdempiereException .wrapIfNeeded(e) .markAsUserValidationError(); } return Collections.emptyList(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\impl\C_InvoiceExport.java
1
请在Spring Boot框架中完成以下Java代码
private List<I_C_PaymentTerm_Break> getPaymentTermBreakRecords(@NonNull final PaymentTermId paymentTermId) { return CollectionUtils.getOrLoad(this.breakRecordsById, paymentTermId, this::retrievePaymentTermBreakRecords); } @NonNull private Map<PaymentTermId, List<I_C_PaymentTerm_Break>> retrievePaymentTermBreakRecords(@NonNull final Set<PaymentTermId> paymentTermIds) { if (paymentTermIds.isEmpty()) { return ImmutableMap.of(); } final Map<PaymentTermId, List<I_C_PaymentTerm_Break>> result = queryBL.createQueryBuilder(I_C_PaymentTerm_Break.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_PaymentTerm_Break.COLUMNNAME_C_PaymentTerm_ID, paymentTermIds) .stream() .collect(Collectors.groupingBy(PaymentTermBreakConverter::extractPaymentTermId, Collectors.toList())); return CollectionUtils.fillMissingKeys(result, paymentTermIds, ImmutableList.of()); } @NonNull private List<I_C_PaySchedule> getPayScheduleRecords(@NonNull final PaymentTermId paymentTermId) { return CollectionUtils.getOrLoad(this.scheduleRecordsById, paymentTermId, this::retrievePayScheduleRecords); } @NonNull private Map<PaymentTermId, List<I_C_PaySchedule>> retrievePayScheduleRecords(@NonNull final Set<PaymentTermId> paymentTermIds) { if (paymentTermIds.isEmpty()) { return ImmutableMap.of(); } final Map<PaymentTermId, List<I_C_PaySchedule>> result = queryBL.createQueryBuilder(I_C_PaySchedule.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_PaySchedule.COLUMNNAME_C_PaymentTerm_ID, paymentTermIds) .stream() .collect(Collectors.groupingBy(PayScheduleConverter::extractPaymentTermId, Collectors.toList())); return CollectionUtils.fillMissingKeys(result, paymentTermIds, ImmutableList.of()); } private PaymentTerm fromRecord(final I_C_PaymentTerm record) { @NonNull final PaymentTermId paymentTermId = PaymentTermConverter.extractId(record); @NonNull final List<I_C_PaymentTerm_Break> breakRecords = getPaymentTermBreakRecords(paymentTermId); @NonNull final List<I_C_PaySchedule> payScheduleRecords = getPayScheduleRecords(paymentTermId); return PaymentTermConverter.fromRecord(record, breakRecords, payScheduleRecords); } private void saveToDB(final I_C_PaymentTerm record)
{ InterfaceWrapperHelper.saveRecord(record); } public void syncStateToDatabase(final Set<PaymentTermId> paymentTermIds) { if (paymentTermIds.isEmpty()) {return;} trxManager.runInThreadInheritedTrx(() -> { warmUpByIds(paymentTermIds); for (final PaymentTermId paymentTermId : paymentTermIds) { final PaymentTerm paymentTerm = loadById(paymentTermId); saveToDB(paymentTerm); } }); } private void saveToDB(@NonNull final PaymentTerm paymentTerm) { final PaymentTermId paymentTermId = paymentTerm.getId(); final I_C_PaymentTerm record = getRecordById(paymentTermId); PaymentTermConverter.updateRecord(record, paymentTerm); saveToDB(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\repository\impl\PaymentTermLoaderAndSaver.java
2
请完成以下Java代码
/* package */ class BPCreditLimitImportHelper { private final BPartnerCreditLimitRepository creditLimitRepo; private final int Management_C_CreditLimit_Type_ID = 540001; private final int Insurance_C_CreditLimit_Type_ID = 540000; @Builder private BPCreditLimitImportHelper( @NonNull final BPartnerCreditLimitRepository creditLimitRepo) { this.creditLimitRepo = creditLimitRepo; } public final void importRecord(@NonNull final BPCreditLimitImportRequest request) { if (request.getInsuranceCreditLimit().signum() > 0) { createUpdateBPCreditLimit(request.getBpartnerId(), request.getInsuranceCreditLimit(), Insurance_C_CreditLimit_Type_ID); } if (request.getManagementCreditLimit().signum() > 0) { createUpdateBPCreditLimit(request.getBpartnerId(), request.getManagementCreditLimit(), Management_C_CreditLimit_Type_ID); } } private final void createUpdateBPCreditLimit( @NonNull final BPartnerId bpartnerId, @NonNull final BigDecimal amount, final int typeId) { final Optional<I_C_BPartner_CreditLimit> bpCreditLimit = creditLimitRepo.retrieveCreditLimitByBPartnerId(bpartnerId.getRepoId(), typeId); if (bpCreditLimit.isPresent()) {
final I_C_BPartner_CreditLimit creditLimit = bpCreditLimit.get(); creditLimit.setAmount(amount); InterfaceWrapperHelper.save(bpCreditLimit); } else { final I_C_BPartner_CreditLimit creditLimit = createBPCreditLimit(amount, typeId); creditLimit.setC_BPartner_ID(bpartnerId.getRepoId()); InterfaceWrapperHelper.save(bpCreditLimit); } } private final I_C_BPartner_CreditLimit createBPCreditLimit(@NonNull final BigDecimal amount, final int typeId) { final I_C_BPartner_CreditLimit bpCreditLimit = InterfaceWrapperHelper.newInstance(I_C_BPartner_CreditLimit.class); bpCreditLimit.setAmount(amount); bpCreditLimit.setC_CreditLimit_Type_ID(typeId); bpCreditLimit.setDateFrom(SystemTime.asDayTimestamp()); bpCreditLimit.setProcessed(true); return bpCreditLimit; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPCreditLimitImportHelper.java
1
请在Spring Boot框架中完成以下Java代码
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/user/**").authenticated() .anyRequest().permitAll() .and().exceptionHandling() .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")) // .and() // .formLogin().loginPage("/login").loginProcessingUrl("/login.do").defaultSuccessUrl("/user/info") // .failureUrl("/login?err=1") // .permitAll() .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/") .permitAll() .and().addFilterBefore(sso(), BasicAuthenticationFilter.class) ; } private Filter sso() { OAuth2ClientAuthenticationProcessingFilter githubFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/github"); OAuth2RestTemplate githubTemplate = new OAuth2RestTemplate(github(), oauth2ClientContext); githubFilter.setRestTemplate(githubTemplate); githubFilter.setTokenServices(new UserInfoTokenServices(githubResource().getUserInfoUri(), github().getClientId()));
return githubFilter; } @Bean @ConfigurationProperties("github.resource") public ResourceServerProperties githubResource() { return new ResourceServerProperties(); } @Bean @ConfigurationProperties("github.client") public AuthorizationCodeResourceDetails github() { return new AuthorizationCodeResourceDetails(); } @Bean public FilterRegistrationBean oauth2ClientFilterRegistration( OAuth2ClientContextFilter filter) { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(filter); registration.setOrder(-100); return registration; } }
repos\spring-boot-quick-master\quick-oauth2\quick-github-oauth\src\main\java\com\github\oauth\config\WebSecurityConfig.java
2
请完成以下Java代码
public class MChangeRequest extends X_M_ChangeRequest { /** * */ private static final long serialVersionUID = 8374119541472311165L; /** * Standard Constructor * @param ctx context * @param M_ChangeRequest_ID ix * @param trxName trx */ public MChangeRequest (Properties ctx, int M_ChangeRequest_ID, String trxName) { super (ctx, M_ChangeRequest_ID, trxName); if (M_ChangeRequest_ID == 0) { // setName (null); setIsApproved(false); setProcessed(false); } } // MChangeRequest /** * CRM Request Constructor * @param request request * @param group request group */ public MChangeRequest (MRequest request, MGroup group) { this (request.getCtx(), 0, request.get_TrxName()); setClientOrg(request); setName(Msg.getElement(getCtx(), "R_Request_ID") + ": " + request.getDocumentNo()); setHelp(request.getSummary()); // setPP_Product_BOM_ID(group.getPP_Product_BOM_ID()); setM_ChangeNotice_ID(group.getM_ChangeNotice_ID()); } // MChangeRequest /** * Load Constructor * @param ctx context * @param rs result set * @param trxName trx */ public MChangeRequest (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MChangeRequest /** * Get CRM Requests of Change Requests * TODO: implement it or delete * @return requests */
public MRequest[] getRequests() { // String sql = "SELECT * FROM R_Request WHERE M_ChangeRequest_ID=?"; return null; } // getRequests /** * Before Save * @param newRecord new * @return true/false */ @Override protected boolean beforeSave (boolean newRecord) { // Have at least one if (getPP_Product_BOM_ID() == 0 && getM_ChangeNotice_ID() == 0) { throw new AdempiereException("@NotFound@: @M_BOM_ID@ / @M_ChangeNotice_ID@"); } // Derive ChangeNotice from BOM if defined if (newRecord && getPP_Product_BOM_ID() > 0 && getM_ChangeNotice_ID() <= 0) { final I_PP_Product_BOM bom = Services.get(IProductBOMDAO.class).getById(getPP_Product_BOM_ID()); if (bom.getM_ChangeNotice_ID() > 0) { setM_ChangeNotice_ID(bom.getM_ChangeNotice_ID()); } } return true; } // beforeSave } // MChangeRequest
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MChangeRequest.java
1
请完成以下Java代码
public int getColumnIndex(final String columnName) { throw new UnsupportedOperationException("GridTabWrapper has no supported for column indexes"); } @Override public boolean isVirtualColumn(final String columnName) { final GridField field = getGridField(columnName); return field != null && field.isVirtualColumn(); } @Override public boolean isKeyColumnName(final String columnName) { final GridField field = getGridField(columnName); return field != null && field.isKey(); } @Override public boolean isCalculated(final String columnName) { final GridField field = getGridField(columnName); return field != null && field.getVO().isCalculated(); } @Override public boolean hasColumnName(final String columnName) { return gridTabWrapper.hasColumnName(columnName); } @Override public Object getValue(final String columnName, final int columnIndex, final Class<?> returnType) { return gridTabWrapper.getValue(columnName, returnType); } @Override public Object getValue(final String columnName, final Class<?> returnType) { return gridTabWrapper.getValue(columnName, returnType); } @Override public boolean setValue(final String columnName, final Object value)
{ gridTabWrapper.setValue(columnName, value); return true; } @Override public boolean setValueNoCheck(final String columnName, final Object value) { gridTabWrapper.setValue(columnName, value); return true; } @Override public Object getReferencedObject(final String columnName, final Method interfaceMethod) throws Exception { // TODO: implement throw new UnsupportedOperationException(); } @Override public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value) { // TODO: implement throw new UnsupportedOperationException(); } @Override public boolean invokeEquals(final Object[] methodArgs) { // TODO: implement throw new UnsupportedOperationException(); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { // TODO: implement throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\GridTabModelInternalAccessor.java
1
请完成以下Java代码
public void removeHUIdsAndInvalidate(final Collection<HuId> huIdsToRemove) { if (removeHUIds(huIdsToRemove)) { invalidateAll(); } } public boolean removeHUIds(final Collection<HuId> huIdsToRemove) { return rowsBuffer.removeHUIds(huIdsToRemove); } private static Set<HuId> extractHUIds(final Collection<I_M_HU> hus) { if (hus == null || hus.isEmpty()) { return ImmutableSet.of(); } return hus.stream() .filter(Objects::nonNull) .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(Collectors.toSet()); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO: notifyRecordsChanged: // get M_HU_IDs from recordRefs, // find the top level records from this view which contain our HUs // invalidate those top levels only final Set<HuId> huIdsToCheck = recordRefs .streamIds(I_M_HU.Table_Name, HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); if (huIdsToCheck.isEmpty()) { return; } final boolean containsSomeRecords = rowsBuffer.containsAnyOfHUIds(huIdsToCheck); if (!containsSomeRecords) { return; } invalidateAll(); } @Override public Stream<HUEditorRow> streamByIds(final DocumentIdsSelection rowIds) { if (rowIds.isEmpty()) { return Stream.empty(); } return streamByIds(HUEditorRowFilter.onlyRowIds(rowIds)); } public Stream<HUEditorRow> streamByIds(final HUEditorRowFilter filter) { return rowsBuffer.streamByIdsExcludingIncludedRows(filter); } /** * @return top level rows and included rows recursive stream which are matching the given filter */ public Stream<HUEditorRow> streamAllRecursive(final HUEditorRowFilter filter) {
return rowsBuffer.streamAllRecursive(filter); } /** * @return true if there is any top level or included row which is matching given filter */ public boolean matchesAnyRowRecursive(final HUEditorRowFilter filter) { return rowsBuffer.matchesAnyRowRecursive(filter); } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { final Set<HuId> huIds = streamByIds(rowIds) .filter(HUEditorRow::isPureHU) .map(HUEditorRow::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); if (huIds.isEmpty()) { return ImmutableList.of(); } final List<I_M_HU> hus = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU.class) .addInArrayFilter(I_M_HU.COLUMN_M_HU_ID, huIds) .create() .list(I_M_HU.class); return InterfaceWrapperHelper.createList(hus, modelClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorView.java
1
请完成以下Java代码
public String getValueDisplay(final Object value) { String infoDisplay = value == null ? "" : value.toString(); if (isLookup()) { final Lookup lookup = getLookup(); if (lookup != null) { infoDisplay = lookup.getDisplay(value); } } else if (getDisplayType() == DisplayType.YesNo) { final IMsgBL msgBL = Services.get(IMsgBL.class); infoDisplay = msgBL.getMsg(Env.getCtx(), infoDisplay); } return infoDisplay; } @Override public boolean matchesColumnName(final String columnName) { if (columnName == null || columnName.isEmpty()) { return false; }
if (columnName.equals(getColumnName())) { return true; } if (gridField.isVirtualColumn()) { if (columnName.equals(gridField.getColumnSQL(false))) { return true; } if (columnName.equals(gridField.getColumnSQL(true))) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelSearchField.java
1
请完成以下Java代码
private void createOrUpdateAllocation(final Object model) { final IDeliveryDayBL deliveryDayBL = Services.get(IDeliveryDayBL.class); final IContextAware context = InterfaceWrapperHelper.getContextAware(model); final IDeliveryDayAllocable deliveryDayAllocable = handler.asDeliveryDayAllocable(model); final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayBL.getCreateDeliveryDayAlloc(context, deliveryDayAllocable); if (deliveryDayAlloc == null) { // Case: no delivery day allocation was found and no delivery day on which we could allocate was found return; } deliveryDayBL.getDeliveryDayHandlers() .updateDeliveryDayAllocFromModel(deliveryDayAlloc, deliveryDayAllocable);
InterfaceWrapperHelper.save(deliveryDayAlloc); } private void deleteAllocation(Object model) { final IDeliveryDayDAO deliveryDayDAO = Services.get(IDeliveryDayDAO.class); final IContextAware context = InterfaceWrapperHelper.getContextAware(model); final IDeliveryDayAllocable deliveryDayAllocable = handler.asDeliveryDayAllocable(model); final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayDAO.retrieveDeliveryDayAllocForModel(context, deliveryDayAllocable); if (deliveryDayAlloc != null) { InterfaceWrapperHelper.delete(deliveryDayAlloc); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\DeliveryDayAllocableInterceptor.java
1
请完成以下Java代码
public static DocumentFieldLogicExpressionResultRevaluator using(@NonNull final IUserRolePermissions userRolePermissions) { return new DocumentFieldLogicExpressionResultRevaluator(null, userRolePermissions); } public boolean isReadonly(@NonNull final IDocumentField documentField) { return revaluate(documentField.getReadonly()).isTrue(); } public LogicExpressionResult revaluate(final LogicExpressionResult readonly) { if (alwaysReturnResult != null) { return alwaysReturnResult; } if (userRolePermissions == null) { return readonly; } final Map<String, String> newParameters = computeNewParametersIfChanged(readonly.getUsedParameters(), userRolePermissions); return newParameters != null ? revaluate(readonly, newParameters) : readonly; } @Nullable private static Map<String, String> computeNewParametersIfChanged( @NonNull final Map<CtxName, String> usedParameters, @NonNull final IUserRolePermissions userRolePermissions) { if (usedParameters.isEmpty()) { return null; } HashMap<String, String> newParameters = null; // lazy, instantiated only if needed for (final Map.Entry<CtxName, String> usedParameterEntry : usedParameters.entrySet()) { final CtxName usedParameterName = usedParameterEntry.getKey(); if (CTXNAME_AD_Role_Group.equalsByName(usedParameterName)) { final String usedValue = normalizeRoleGroupValue(usedParameterEntry.getValue()); final String newValue = normalizeRoleGroupValue(userRolePermissions.getRoleGroup() != null ? userRolePermissions.getRoleGroup().getName() : null); if (!Objects.equals(usedValue, newValue)) { newParameters = newParameters == null ? copyToNewParameters(usedParameters) : newParameters; newParameters.put(CTXNAME_AD_Role_Group.getName(), newValue); }
} } return newParameters; } private static String normalizeRoleGroupValue(String roleGroupValue) { String result = LogicExpressionEvaluator.stripQuotes(roleGroupValue); result = StringUtils.trimBlankToNull(result); return result != null ? result : ""; } @NonNull private static HashMap<String, String> copyToNewParameters(final @NonNull Map<CtxName, String> usedParameters) { final HashMap<String, String> newParameters = new HashMap<>(usedParameters.size()); for (Map.Entry<CtxName, String> entry : usedParameters.entrySet()) { newParameters.put(entry.getKey().getName(), entry.getValue()); } return newParameters; } private static LogicExpressionResult revaluate( @NonNull final LogicExpressionResult result, @NonNull final Map<String, String> newParameters) { try { return result.getExpression().evaluateToResult(Evaluatees.ofMap(newParameters), IExpressionEvaluator.OnVariableNotFound.Fail); } catch (final Exception ex) { // shall not happen logger.warn("Failed evaluating expression using `{}`. Returning previous result: {}", newParameters, result, ex); return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldLogicExpressionResultRevaluator.java
1
请完成以下Java代码
public void setC_Invoice_From_ID (final int C_Invoice_From_ID) { if (C_Invoice_From_ID < 1) set_Value (COLUMNNAME_C_Invoice_From_ID, null); else set_Value (COLUMNNAME_C_Invoice_From_ID, C_Invoice_From_ID); } @Override public int getC_Invoice_From_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_From_ID); } @Override public void setC_Invoice_Relation_ID (final int C_Invoice_Relation_ID) { if (C_Invoice_Relation_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Relation_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Relation_ID, C_Invoice_Relation_ID); } @Override public int getC_Invoice_Relation_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Relation_ID); } /** * C_Invoice_Relation_Type AD_Reference_ID=541475 * Reference name: C_Invoice_Relation_Types */ public static final int C_INVOICE_RELATION_TYPE_AD_Reference_ID=541475; /** PurchaseToSales = POtoSO */ public static final String C_INVOICE_RELATION_TYPE_PurchaseToSales = "POtoSO"; @Override public void setC_Invoice_Relation_Type (final java.lang.String C_Invoice_Relation_Type) {
set_Value (COLUMNNAME_C_Invoice_Relation_Type, C_Invoice_Relation_Type); } @Override public java.lang.String getC_Invoice_Relation_Type() { return get_ValueAsString(COLUMNNAME_C_Invoice_Relation_Type); } @Override public org.compiere.model.I_C_Invoice getC_Invoice_To() { return get_ValueAsPO(COLUMNNAME_C_Invoice_To_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setC_Invoice_To(final org.compiere.model.I_C_Invoice C_Invoice_To) { set_ValueFromPO(COLUMNNAME_C_Invoice_To_ID, org.compiere.model.I_C_Invoice.class, C_Invoice_To); } @Override public void setC_Invoice_To_ID (final int C_Invoice_To_ID) { if (C_Invoice_To_ID < 1) set_Value (COLUMNNAME_C_Invoice_To_ID, null); else set_Value (COLUMNNAME_C_Invoice_To_ID, C_Invoice_To_ID); } @Override public int getC_Invoice_To_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_To_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Relation.java
1
请完成以下Java代码
public TaskTemplateDefinition getDefaultTemplate() { return defaultTemplate; } public void setDefaultTemplate(TaskTemplateDefinition defaultTemplate) { this.defaultTemplate = defaultTemplate; } public Optional<TemplateDefinition> findAssigneeTemplateForTask(String taskUUID) { TaskTemplateDefinition taskTemplateDefinition = tasks.get(taskUUID); if (taskTemplateDefinition == null) { return Optional.empty(); } return Optional.ofNullable(taskTemplateDefinition.getAssignee()); } public Optional<TemplateDefinition> findCandidateTemplateForTask(String taskUUID) { TaskTemplateDefinition taskTemplateDefinition = tasks.get(taskUUID); if (taskTemplateDefinition == null) { return Optional.empty(); } return Optional.ofNullable(taskTemplateDefinition.getCandidate()); } public boolean isEmailNotificationEnabledForTask(String taskUUID) { TaskTemplateDefinition taskTemplateDefinition = tasks.get(taskUUID); if (taskTemplateDefinition == null) { return true; } return taskTemplateDefinition.isEmailNotificationEnabled(); } @Override
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TemplatesDefinition that = (TemplatesDefinition) o; return Objects.equals(tasks, that.tasks) && Objects.equals(defaultTemplate, that.defaultTemplate); } @Override public int hashCode() { return Objects.hash(tasks, defaultTemplate); } }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\TemplatesDefinition.java
1
请完成以下Java代码
public void createQtyChange(final @NonNull I_C_Flatrate_Term term, @Nullable final BigDecimal newQty) { insertSubscriptionProgressEvent(term, X_C_SubscriptionProgress.EVENTTYPE_Quantity, newQty); } private void insertSubscriptionProgressEvent(@NonNull final I_C_Flatrate_Term term, @NonNull final String eventType, @Nullable final Object eventValue) { final Timestamp today = SystemTime.asDayTimestamp(); final List<I_C_SubscriptionProgress> subscriptionProgressList = subscriptionDAO.retrieveSubscriptionProgresses(SubscriptionProgressQuery.builder() .term(term).build()); final int seqNoToUse = getSeqNoToUse(today, subscriptionProgressList);//default start seq number. Should not happen. final I_C_SubscriptionProgress changeEvent = newInstance(I_C_SubscriptionProgress.class); changeEvent.setEventType(eventType); changeEvent.setC_Flatrate_Term(term); changeEvent.setStatus(X_C_SubscriptionProgress.STATUS_Planned); changeEvent.setContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_Running); changeEvent.setEventDate(today); changeEvent.setSeqNo(seqNoToUse); changeEvent.setDropShip_BPartner_ID(term.getDropShip_BPartner_ID()); changeEvent.setDropShip_Location_ID(term.getDropShip_Location_ID()); addEventValue(changeEvent, eventType, eventValue); save(changeEvent); subscriptionProgressList.stream() .filter(sp -> today.before(sp.getEventDate())) .forEach(this::incrementSeqNoAndSave); } private int getSeqNoToUse(final Timestamp today, final List<I_C_SubscriptionProgress> subscriptionProgressList) { return subscriptionProgressList.stream() .filter(sp -> today.before(sp.getEventDate())) .mapToInt(I_C_SubscriptionProgress::getSeqNo) .min()//smallest seqNo after today's date .orElse(subscriptionProgressList.stream() .mapToInt(I_C_SubscriptionProgress::getSeqNo) .map(Math::incrementExact) .max()//greatest seqNo + 1 before today .orElse(SEQNO_FIRST_VALUE)); } private void addEventValue(final I_C_SubscriptionProgress changeEvent, final String eventType, @Nullable final Object eventValue) { if (Objects.equals(eventType, X_C_SubscriptionProgress.EVENTTYPE_Quantity) && eventValue != null) { changeEvent.setQty((BigDecimal)eventValue); }
} private void incrementSeqNoAndSave(final I_C_SubscriptionProgress subscriptionProgress) { subscriptionProgress.setSeqNo(subscriptionProgress.getSeqNo() + 1); save(subscriptionProgress); } public boolean isSubscription(@NonNull final I_C_OrderLine ol) { final ConditionsId conditionsId = ConditionsId.ofRepoIdOrNull(ol.getC_Flatrate_Conditions_ID()); if (conditionsId == null) { return false; } final I_C_Flatrate_Conditions typeConditions = flatrateDAO.getConditionsById(conditionsId); return X_C_Flatrate_Term.TYPE_CONDITIONS_Subscription.equals(typeConditions.getType_Conditions()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\SubscriptionBL.java
1
请完成以下Java代码
public void setM_DiscountSchema_ID (final int M_DiscountSchema_ID) { if (M_DiscountSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, M_DiscountSchema_ID); } @Override public int getM_DiscountSchema_ID() { return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID); } @Override public void setM_DiscountSchemaBreak_V_ID (final int M_DiscountSchemaBreak_V_ID) { if (M_DiscountSchemaBreak_V_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DiscountSchemaBreak_V_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DiscountSchemaBreak_V_ID, M_DiscountSchemaBreak_V_ID); } @Override public int getM_DiscountSchemaBreak_V_ID() { return get_ValueAsInt(COLUMNNAME_M_DiscountSchemaBreak_V_ID); }
@Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchemaBreak_V.java
1
请完成以下Java代码
public void setKey(String key) { this.key = key; } @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } @Override public byte[] getPasswordBytes() { return passwordBytes; } @Override public void setPasswordBytes(byte[] passwordBytes) { this.passwordBytes = passwordBytes; } @Override public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public String getName() { return key; } @Override public String getUsername() { return value; }
@Override public String getParentId() { return parentId; } @Override public void setParentId(String parentId) { this.parentId = parentId; } @Override public Map<String, String> getDetails() { return details; } @Override public void setDetails(Map<String, String> details) { this.details = details; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\IdentityInfoEntityImpl.java
1
请完成以下Java代码
public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_UserGroup getAD_UserGroup() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_UserGroup_ID, org.compiere.model.I_AD_UserGroup.class); } @Override public void setAD_UserGroup(org.compiere.model.I_AD_UserGroup AD_UserGroup) { set_ValueFromPO(COLUMNNAME_AD_UserGroup_ID, org.compiere.model.I_AD_UserGroup.class, AD_UserGroup); } /** Set Nutzergruppe. @param AD_UserGroup_ID Nutzergruppe */ @Override public void setAD_UserGroup_ID (int AD_UserGroup_ID) { if (AD_UserGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, Integer.valueOf(AD_UserGroup_ID)); } /** Get Nutzergruppe. @return Nutzergruppe */ @Override public int getAD_UserGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Private_Access.java
1
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Summe Zeilen. @param TotalLines Total of all document lines */
@Override public void setTotalLines (java.math.BigDecimal TotalLines) { set_Value (COLUMNNAME_TotalLines, TotalLines); } /** Get Summe Zeilen. @return Total of all document lines */ @Override public java.math.BigDecimal getTotalLines () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalLines); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Requisition.java
1
请在Spring Boot框架中完成以下Java代码
public class M_InOut { private final IDocumentLocationBL documentLocationBL; public M_InOut(@NonNull final IDocumentLocationBL documentLocationBL) { this.documentLocationBL = documentLocationBL; final IProgramaticCalloutProvider programaticCalloutProvider = Services.get(IProgramaticCalloutProvider.class); programaticCalloutProvider.registerAnnotatedCallout(this); } @CalloutMethod(columnNames = { I_M_InOut.COLUMNNAME_C_BPartner_ID, I_M_InOut.COLUMNNAME_C_BPartner_Location_ID, I_M_InOut.COLUMNNAME_AD_User_ID }, skipIfCopying = true)
public void updateBPartnerAddress(final I_M_InOut inout) { documentLocationBL.updateRenderedAddressAndCapturedLocation(InOutDocumentLocationAdapterFactory.locationAdapter(inout)); } @CalloutMethod(columnNames = { I_M_InOut.COLUMNNAME_IsDropShip, I_M_InOut.COLUMNNAME_DropShip_BPartner_ID, I_M_InOut.COLUMNNAME_DropShip_Location_ID, I_M_InOut.COLUMNNAME_DropShip_User_ID, I_M_InOut.COLUMNNAME_M_Warehouse_ID }, skipIfCopying = true) public void updateDeliveryToAddress(final I_M_InOut inout) { documentLocationBL.updateRenderedAddressAndCapturedLocation(InOutDocumentLocationAdapterFactory.deliveryLocationAdapter(inout)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\callout\M_InOut.java
2