instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static String jiami(String content) { SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes()); String encryptResultStr = aes.encryptHex(content); return encryptResultStr; } /**解密 * @param encryptResultStr * @return */ public static String jiemi(String encryptResultStr){ SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes()); //解密为字符串 String decryptResult = aes.decryptStr(encryptResultStr, CharsetUtil.CHARSET_UTF_8); return decryptResult;
} //---AES加密---------end--------- /** * 主函数 */ public static void main(String[] args) { String content="test1111"; String encrypt = jiami(content); System.out.println(encrypt); //构建 String decrypt = jiemi(encrypt); //解密为字符串 System.out.println(decrypt); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\util\SecurityUtil.java
1
请完成以下Java代码
public static DocumentLayoutElementFieldDescriptor.LookupSource extractLookupSource(final int displayType, @Nullable final ReferenceId adReferenceValueId) { if (DisplayType.Search == displayType) { return DocumentLayoutElementFieldDescriptor.LookupSource.lookup; } else if (DisplayType.List == displayType) { return DocumentLayoutElementFieldDescriptor.LookupSource.list; } else if (DisplayType.TableDir == displayType) { return DocumentLayoutElementFieldDescriptor.LookupSource.list; } else if (DisplayType.Table == displayType) {
return DocumentLayoutElementFieldDescriptor.LookupSource.list; } else if (DisplayType.isAnyLookup(displayType)) { return DocumentLayoutElementFieldDescriptor.LookupSource.lookup; } else if (DisplayType.Button == displayType && adReferenceValueId != null) { return DocumentLayoutElementFieldDescriptor.LookupSource.list; } else { return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\DescriptorsFactoryHelper.java
1
请在Spring Boot框架中完成以下Java代码
public Object getDiscountDuration() { return discountDuration; } /** * Sets the value of the discountDuration property. * * @param value * allowed object is * {@link Object } * */ public void setDiscountDuration(Object value) { this.discountDuration = value; } /** * Contitions which apply for the payment. Please use EDIFACT code list values. (PAI 4439) * * @return * possible object is * {@link String } * */ public String getPaymentCondition() { return paymentCondition; } /** * Sets the value of the paymentCondition property. * * @param value * allowed object is * {@link String } * */ public void setPaymentCondition(String value) { this.paymentCondition = value; }
/** * Payment means coded. Please use EDIFACT code list values. (PAI 4461) * * @return * possible object is * {@link String } * */ public String getPaymentMeans() { return paymentMeans; } /** * Sets the value of the paymentMeans property. * * @param value * allowed object is * {@link String } * */ public void setPaymentMeans(String value) { this.paymentMeans = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\PaymentConditionsExtensionType.java
2
请完成以下Java代码
public boolean isUseStrongUuids() { return useStrongUuids; } public void setUseStrongUuids(boolean useStrongUuids) { this.useStrongUuids = useStrongUuids; } public boolean isCopyVariablesToLocalForTasks() { return copyVariablesToLocalForTasks; } public void setCopyVariablesToLocalForTasks(boolean copyVariablesToLocalForTasks) { this.copyVariablesToLocalForTasks = copyVariablesToLocalForTasks; } public String getDeploymentMode() { return deploymentMode; } public void setDeploymentMode(String deploymentMode) { this.deploymentMode = deploymentMode; } public boolean isSerializePOJOsInVariablesToJson() { return serializePOJOsInVariablesToJson; } public void setSerializePOJOsInVariablesToJson(boolean serializePOJOsInVariablesToJson) { this.serializePOJOsInVariablesToJson = serializePOJOsInVariablesToJson; } public String getJavaClassFieldForJackson() { return javaClassFieldForJackson;
} public void setJavaClassFieldForJackson(String javaClassFieldForJackson) { this.javaClassFieldForJackson = javaClassFieldForJackson; } public Integer getProcessDefinitionCacheLimit() { return processDefinitionCacheLimit; } public void setProcessDefinitionCacheLimit(Integer processDefinitionCacheLimit) { this.processDefinitionCacheLimit = processDefinitionCacheLimit; } public String getProcessDefinitionCacheName() { return processDefinitionCacheName; } public void setProcessDefinitionCacheName(String processDefinitionCacheName) { this.processDefinitionCacheName = processDefinitionCacheName; } public void setDisableExistingStartEventSubscriptions(boolean disableExistingStartEventSubscriptions) { this.disableExistingStartEventSubscriptions = disableExistingStartEventSubscriptions; } public boolean shouldDisableExistingStartEventSubscriptions() { return disableExistingStartEventSubscriptions; } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\ActivitiProperties.java
1
请在Spring Boot框架中完成以下Java代码
public SpringBeanJobFactory springBeanJobFactory() { AutoWiringSpringBeanJobFactory jobFactory = new AutoWiringSpringBeanJobFactory(); logger.debug("Configuring Job factory"); jobFactory.setApplicationContext(applicationContext); return jobFactory; } @Bean public Scheduler scheduler(Trigger trigger, JobDetail job, SchedulerFactoryBean factory) throws SchedulerException { logger.debug("Getting a handle to the Scheduler"); Scheduler scheduler = factory.getScheduler(); scheduler.scheduleJob(job, trigger); logger.debug("Starting Scheduler threads"); scheduler.start(); return scheduler; } @Bean public SchedulerFactoryBean schedulerFactoryBean() throws IOException { SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setJobFactory(springBeanJobFactory()); factory.setQuartzProperties(quartzProperties()); return factory; } public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); } @Bean public JobDetail jobDetail() { return newJob().ofType(SampleJob.class).storeDurably().withIdentity(JobKey.jobKey("Qrtz_Job_Detail")).withDescription("Invoke Sample Job service...").build(); } @Bean public Trigger trigger(JobDetail job) { int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")).withDescription("Sample trigger").withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()).build(); } }
repos\tutorials-master\spring-quartz\src\main\java\org\baeldung\springquartz\basics\scheduler\QrtzScheduler.java
2
请完成以下Java代码
public void addHandler(final IFlatrateTermEventListener handler) { Check.assumeNotNull(handler, "handler not null"); handlers.addIfAbsent(handler); } @Override public void beforeFlatrateTermReactivate(final I_C_Flatrate_Term term) { handlers.forEach(h -> h.beforeFlatrateTermReactivate(term)); } @Override public void afterSaveOfNextTermForPredecessor(I_C_Flatrate_Term next, I_C_Flatrate_Term predecessor) {
handlers.forEach(h -> h.afterSaveOfNextTermForPredecessor(next, predecessor)); } @Override public void afterFlatrateTermEnded(I_C_Flatrate_Term term) { handlers.forEach(h -> h.afterFlatrateTermEnded(term)); } @Override public void beforeSaveOfNextTermForPredecessor(I_C_Flatrate_Term next, I_C_Flatrate_Term predecessor) { handlers.forEach(h -> h.beforeSaveOfNextTermForPredecessor(next,predecessor)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\CompositeFlatrateTermEventListener.java
1
请在Spring Boot框架中完成以下Java代码
public String logoutPage(){ return "logout"; } @GetMapping("/todos") public String todos(Model model){ model.addAttribute("todos", todoRepository.findAll()); return "todos"; } @PostMapping("/todoNew") public String add(@RequestParam String todoItem, @RequestParam String status, Model model){ ToDo todo = new ToDo(); todo.setTodoItem(todoItem); todo.setCompleted(status); todoRepository.save(todo); model.addAttribute("todos", todoRepository.findAll()); return "redirect:/todos"; } @PostMapping("/todoDelete/{id}")
public String delete(@PathVariable long id, Model model){ todoRepository.deleteById(id); model.addAttribute("todos", todoRepository.findAll()); return "redirect:/todos"; } @PostMapping("/todoUpdate/{id}") public String update(@PathVariable long id, Model model){ ToDo toDo = todoRepository.findById(id).get(); if("Yes".equals(toDo.getCompleted())){ toDo.setCompleted("No"); } else { toDo.setCompleted("Yes"); } todoRepository.save(toDo); model.addAttribute("todos", todoRepository.findAll()); return "redirect:/todos"; } }
repos\Spring-Boot-Advanced-Projects-main\SpringBoot-Todo-Project\src\main\java\spring\project\controller\ToDoController.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_User_Occupation_Job_ID (final int AD_User_Occupation_Job_ID) { if (AD_User_Occupation_Job_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Job_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Job_ID, AD_User_Occupation_Job_ID); } @Override public int getAD_User_Occupation_Job_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_Job_ID); }
@Override public org.compiere.model.I_CRM_Occupation getCRM_Occupation() { return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class); } @Override public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation) { set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation); } @Override public void setCRM_Occupation_ID (final int CRM_Occupation_ID) { if (CRM_Occupation_ID < 1) set_Value (COLUMNNAME_CRM_Occupation_ID, null); else set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID); } @Override public int getCRM_Occupation_ID() { return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_Job.java
1
请完成以下Java代码
public WFProcess continueWorkflow(final WFProcessId wfProcessId, final UserId callerId) { final InventoryId inventoryId = toInventoryId(wfProcessId); final Inventory inventory = jobService.reassignJob(inventoryId, callerId); return toWFProcess(inventory); } @Override public void abort(final WFProcessId wfProcessId, final UserId callerId) { jobService.abort(wfProcessId, callerId); } @Override public void abortAll(final UserId callerId) { jobService.abortAll(callerId); } @Override public void logout(final @NonNull UserId userId) { abortAll(userId); } @Override public WFProcess getWFProcessById(final WFProcessId wfProcessId) { final Inventory inventory = jobService.getById(toInventoryId(wfProcessId)); return toWFProcess(inventory); } @Override public WFProcessHeaderProperties getHeaderProperties(final @NonNull WFProcess wfProcess) { final WarehousesLoadingCache warehouses = warehouseService.newLoadingCache(); final Inventory inventory = getInventory(wfProcess); return WFProcessHeaderProperties.builder() .entry(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adElementOrMessage("DocumentNo")) .value(inventory.getDocumentNo())
.build()) .entry(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adElementOrMessage("MovementDate")) .value(TranslatableStrings.date(inventory.getMovementDate().toLocalDate())) .build()) .entry(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adElementOrMessage("M_Warehouse_ID")) .value(inventory.getWarehouseId() != null ? warehouses.getById(inventory.getWarehouseId()).getWarehouseName() : "") .build()) .build(); } @NonNull public static Inventory getInventory(final @NonNull WFProcess wfProcess) { return wfProcess.getDocumentAs(Inventory.class); } public static WFProcess mapJob(@NonNull final WFProcess wfProcess, @NonNull final UnaryOperator<Inventory> mapper) { final Inventory inventory = getInventory(wfProcess); final Inventory inventoryChanged = mapper.apply(inventory); return !Objects.equals(inventory, inventoryChanged) ? toWFProcess(inventoryChanged) : wfProcess; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\InventoryMobileApplication.java
1
请完成以下Java代码
public GatewayFilter apply(Config config) { return new GatewayFilter() { final UriTemplate uriTemplate = new UriTemplate( Objects.requireNonNull(config.prefix, "prefix must not be null")); @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { boolean alreadyPrefixed = exchange.getAttributeOrDefault(GATEWAY_ALREADY_PREFIXED_ATTR, false); if (alreadyPrefixed) { return chain.filter(exchange); } exchange.getAttributes().put(GATEWAY_ALREADY_PREFIXED_ATTR, true); ServerHttpRequest req = exchange.getRequest(); addOriginalRequestUrl(exchange, req.getURI()); Map<String, String> uriVariables = getUriTemplateVariables(exchange); URI uri = uriTemplate.expand(uriVariables); String newPath = uri.getRawPath() + req.getURI().getRawPath(); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri); ServerHttpRequest request = req.mutate().path(newPath).build(); if (log.isTraceEnabled()) { log.trace("Prefixed URI with: " + config.prefix + " -> " + request.getURI()); } return chain.filter(exchange.mutate().request(request).build()); } @Override public String toString() { return filterToStringCreator(PrefixPathGatewayFilterFactory.this).append("prefix", config.getPrefix()) .toString(); }
}; } public static class Config { private @Nullable String prefix; public @Nullable String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\PrefixPathGatewayFilterFactory.java
1
请完成以下Java代码
public abstract class DockerUtils { private static final Logger LOGGER = LoggerFactory.getLogger(DockerUtils.class); /** Environment param keys */ private static final String ENV_KEY_HOST = "JPAAS_HOST"; private static final String ENV_KEY_PORT = "JPAAS_HTTP_PORT"; private static final String ENV_KEY_PORT_ORIGINAL = "JPAAS_HOST_PORT_8080"; /** Docker host & port */ private static String DOCKER_HOST = ""; private static String DOCKER_PORT = ""; /** Whether is docker */ private static boolean IS_DOCKER; static { retrieveFromEnv(); } /** * Retrieve docker host * * @return empty string if not a docker */ public static String getDockerHost() { return DOCKER_HOST; } /** * Retrieve docker port * * @return empty string if not a docker */ public static String getDockerPort() { return DOCKER_PORT; } /** * Whether a docker * * @return */ public static boolean isDocker() { return IS_DOCKER; } /** * Retrieve host & port from environment */ private static void retrieveFromEnv() { // retrieve host & port from environment DOCKER_HOST = System.getenv(ENV_KEY_HOST); DOCKER_PORT = System.getenv(ENV_KEY_PORT);
// not found from 'JPAAS_HTTP_PORT', then try to find from 'JPAAS_HOST_PORT_8080' if (StringUtils.isBlank(DOCKER_PORT)) { DOCKER_PORT = System.getenv(ENV_KEY_PORT_ORIGINAL); } boolean hasEnvHost = StringUtils.isNotBlank(DOCKER_HOST); boolean hasEnvPort = StringUtils.isNotBlank(DOCKER_PORT); // docker can find both host & port from environment if (hasEnvHost && hasEnvPort) { IS_DOCKER = true; // found nothing means not a docker, maybe an actual machine } else if (!hasEnvHost && !hasEnvPort) { IS_DOCKER = false; } else { LOGGER.error("Missing host or port from env for Docker. host:{}, port:{}", DOCKER_HOST, DOCKER_PORT); throw new RuntimeException( "Missing host or port from env for Docker. host:" + DOCKER_HOST + ", port:" + DOCKER_PORT); } } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\utils\DockerUtils.java
1
请完成以下Java代码
public void execute(boolean writeUserOperationLog) { commandExecutor.execute(new ProcessInstanceModificationCmd(this, writeUserOperationLog)); } @Override public void execute() { execute(true); } @Override public Batch executeAsync() { return commandExecutor.execute(new ProcessInstanceModificationBatchCmd(this)); } public CommandExecutor getCommandExecutor() { return commandExecutor; } public ProcessInstanceQuery getProcessInstanceQuery() { return processInstanceQuery; } public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; }
public List<AbstractProcessInstanceModificationCommand> getInstructions() { return instructions; } public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) { this.instructions = instructions; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public boolean isSkipIoMappings() { return skipIoMappings; } public String getAnnotation() { return annotation; } public void setAnnotationInternal(String annotation) { this.annotation = annotation; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ModificationBuilderImpl.java
1
请完成以下Java代码
public Integer getReceiveStatus() { return receiveStatus; } public void setReceiveStatus(Integer receiveStatus) { this.receiveStatus = receiveStatus; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; }
public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getDetailAddress() { return detailAddress; } public void setDetailAddress(String detailAddress) { this.detailAddress = detailAddress; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", addressName=").append(addressName); sb.append(", sendStatus=").append(sendStatus); sb.append(", receiveStatus=").append(receiveStatus); sb.append(", name=").append(name); sb.append(", phone=").append(phone); sb.append(", province=").append(province); sb.append(", city=").append(city); sb.append(", region=").append(region); sb.append(", detailAddress=").append(detailAddress); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCompanyAddress.java
1
请完成以下Java代码
public static boolean isOverlapping(@NonNull final Range<Instant> range1, @NonNull final Range<Instant> range2) { if (!range1.isConnected(range2)) { return false; } return !range1.intersection(range2).isEmpty(); } /** * Compute the days between two dates as if each year is 360 days long. * More details and an implementation for Excel can be found in {@link org.apache.poi.ss.formula.functions.Days360} */ public static long getDaysBetween360(@NonNull final ZonedDateTime from, @NonNull final ZonedDateTime to) { if (from.isEqual(to)) { return 0; } if (to.isBefore(from)) { return getDaysBetween360(to, from) * -1; } ZonedDateTime dayFrom = from; ZonedDateTime dayTo = to; if (dayFrom.getDayOfMonth() == 31) { dayFrom = dayFrom.withDayOfMonth(30); } if (dayTo.getDayOfMonth() == 31) {
dayTo = dayTo.withDayOfMonth(30); } final long months = ChronoUnit.MONTHS.between( YearMonth.from(dayFrom), YearMonth.from(dayTo)); final int daysLeft = dayTo.getDayOfMonth() - dayFrom.getDayOfMonth(); return 30 * months + daysLeft; } /** * Compute the days between two dates as if each year is 360 days long. * More details and an implementation for Excel can be found in {@link org.apache.poi.ss.formula.functions.Days360} */ public static long getDaysBetween360(@NonNull final Instant from, @NonNull final Instant to) { return getDaysBetween360(asZonedDateTime(from), asZonedDateTime(to)); } public static Instant addDays(@NonNull final Instant baseInstant, final long daysToAdd) { return baseInstant.plus(daysToAdd, ChronoUnit.DAYS); } } // TimeUtil
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\TimeUtil.java
1
请完成以下Java代码
public int getSeqNoGrid() { return get_ValueAsInt(COLUMNNAME_SeqNoGrid); } @Override public void setSeqNo_SideList (final int SeqNo_SideList) { set_Value (COLUMNNAME_SeqNo_SideList, SeqNo_SideList); } @Override public int getSeqNo_SideList() { return get_ValueAsInt(COLUMNNAME_SeqNo_SideList); } @Override public void setUIStyle (final @Nullable java.lang.String UIStyle) { set_Value (COLUMNNAME_UIStyle, UIStyle); } @Override public java.lang.String getUIStyle() { return get_ValueAsString(COLUMNNAME_UIStyle); } /** * ViewEditMode AD_Reference_ID=541263 * Reference name: ViewEditMode */ public static final int VIEWEDITMODE_AD_Reference_ID=541263; /** Never = N */ public static final String VIEWEDITMODE_Never = "N"; /** OnDemand = D */ public static final String VIEWEDITMODE_OnDemand = "D"; /** Always = Y */ public static final String VIEWEDITMODE_Always = "Y"; @Override public void setViewEditMode (final @Nullable java.lang.String ViewEditMode) { set_Value (COLUMNNAME_ViewEditMode, ViewEditMode); } @Override public java.lang.String getViewEditMode() { return get_ValueAsString(COLUMNNAME_ViewEditMode);
} /** * WidgetSize AD_Reference_ID=540724 * Reference name: WidgetSize_WEBUI */ public static final int WIDGETSIZE_AD_Reference_ID=540724; /** Small = S */ public static final String WIDGETSIZE_Small = "S"; /** Medium = M */ public static final String WIDGETSIZE_Medium = "M"; /** Large = L */ public static final String WIDGETSIZE_Large = "L"; /** ExtraLarge = XL */ public static final String WIDGETSIZE_ExtraLarge = "XL"; /** XXL = XXL */ public static final String WIDGETSIZE_XXL = "XXL"; @Override public void setWidgetSize (final @Nullable java.lang.String WidgetSize) { set_Value (COLUMNNAME_WidgetSize, WidgetSize); } @Override public java.lang.String getWidgetSize() { return get_ValueAsString(COLUMNNAME_WidgetSize); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Element.java
1
请完成以下Java代码
public void bufferedWriter10Writes() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH, true), BUFSIZE)) { for (int i = 0; i < 10; i++) { writer.write(CONTENT); } writer.close(); } catch (IOException e) { log.error("Error in BufferedWriter 10 writes", e); } } @Benchmark public void fileWriter1000Writes() { try (FileWriter writer = new FileWriter(FILE_PATH, true)) { for (int i = 0; i < 1000; i++) { writer.write(CONTENT); } writer.close(); } catch (IOException e) { log.error("Error in FileWriter 1000 writes", e); } } @Benchmark public void bufferedWriter1000Writes() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH, true), BUFSIZE)) { for (int i = 0; i < 1000; i++) { writer.write(CONTENT); } writer.close(); } catch (IOException e) { log.error("Error in BufferedWriter 1000 writes", e); } } @Benchmark public void fileWriter10000Writes() { try (FileWriter writer = new FileWriter(FILE_PATH, true)) { for (int i = 0; i < 10000; i++) { writer.write(CONTENT); } writer.close(); } catch (IOException e) { log.error("Error in FileWriter 10000 writes", e); } } @Benchmark public void bufferedWriter10000Writes() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH, true), BUFSIZE)) { for (int i = 0; i < 10000; i++) { writer.write(CONTENT); } writer.close(); } catch (IOException e) { log.error("Error in BufferedWriter 10000 writes", e); } }
@Benchmark public void fileWriter100000Writes() { try (FileWriter writer = new FileWriter(FILE_PATH, true)) { for (int i = 0; i < 100000; i++) { writer.write(CONTENT); } writer.close(); } catch (IOException e) { log.error("Error in FileWriter 100000 writes", e); } } @Benchmark public void bufferedWriter100000Writes() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH, true), BUFSIZE)) { for (int i = 0; i < 100000; i++) { writer.write(CONTENT); } writer.close(); } catch (IOException e) { log.error("Error in BufferedWriter 100000 writes", e); } } public static void main(String[] args) throws Exception { Files.deleteIfExists(Paths.get(FILE_PATH)); org.openjdk.jmh.Main.main(args); } }
repos\tutorials-master\core-java-modules\core-java-io-6\src\main\java\com\baeldung\filewritervsbufferedwriter\BenchmarkWriters.java
1
请在Spring Boot框架中完成以下Java代码
public class ArticlesApi { private ArticleRepository articleRepository; private ArticleQueryService articleQueryService; @Autowired public ArticlesApi(ArticleRepository articleRepository, ArticleQueryService articleQueryService) { this.articleRepository = articleRepository; this.articleQueryService = articleQueryService; } @PostMapping public ResponseEntity createArticle(@Valid @RequestBody NewArticleParam newArticleParam, BindingResult bindingResult, @AuthenticationPrincipal User user) { if (bindingResult.hasErrors()) { throw new InvalidRequestException(bindingResult); } Article article = new Article( newArticleParam.getTitle(), newArticleParam.getDescription(), newArticleParam.getBody(), newArticleParam.getTagList(), user.getId()); articleRepository.save(article); return ResponseEntity.ok(new HashMap<String, Object>() {{ put("article", articleQueryService.findById(article.getId(), user).get()); }}); } @GetMapping(path = "feed") public ResponseEntity getFeed(@RequestParam(value = "offset", defaultValue = "0") int offset, @RequestParam(value = "limit", defaultValue = "20") int limit, @AuthenticationPrincipal User user) { return ResponseEntity.ok(articleQueryService.findUserFeed(user, new Page(offset, limit))); } @GetMapping
public ResponseEntity getArticles(@RequestParam(value = "offset", defaultValue = "0") int offset, @RequestParam(value = "limit", defaultValue = "20") int limit, @RequestParam(value = "tag", required = false) String tag, @RequestParam(value = "favorited", required = false) String favoritedBy, @RequestParam(value = "author", required = false) String author, @AuthenticationPrincipal User user) { return ResponseEntity.ok(articleQueryService.findRecentArticles(tag, author, favoritedBy, new Page(offset, limit), user)); } } @Getter @JsonRootName("article") @NoArgsConstructor class NewArticleParam { @NotBlank(message = "can't be empty") private String title; @NotBlank(message = "can't be empty") private String description; @NotBlank(message = "can't be empty") private String body; private String[] tagList; }
repos\spring-boot-realworld-example-app-master (1)\src\main\java\io\spring\api\ArticlesApi.java
2
请完成以下Java代码
private boolean isAttrDocumentRelevant(final I_M_Attribute attribute) { final String docTableName = getSourceTableName(); if (I_C_InvoiceLine.Table_Name.equals(docTableName)) { return attribute.isAttrDocumentRelevant(); } else { return true; } } public BPartnerAwareAttributeUpdater setSourceModel(final Object sourceModel) { this.sourceModel = sourceModel; return this; } private Object getSourceModel() { Check.assumeNotNull(sourceModel, "sourceModel not null"); return sourceModel; } private String getSourceTableName() { return InterfaceWrapperHelper.getModelTableName(getSourceModel()); } public BPartnerAwareAttributeUpdater setBPartnerAwareFactory(final IBPartnerAwareFactory bpartnerAwareFactory) { this.bpartnerAwareFactory = bpartnerAwareFactory; return this; } private IBPartnerAwareFactory getBPartnerAwareFactory() {
Check.assumeNotNull(bpartnerAwareFactory, "bpartnerAwareFactory not null"); return bpartnerAwareFactory; } public final BPartnerAwareAttributeUpdater setBPartnerAwareAttributeService(final IBPartnerAwareAttributeService bpartnerAwareAttributeService) { this.bpartnerAwareAttributeService = bpartnerAwareAttributeService; return this; } private IBPartnerAwareAttributeService getBPartnerAwareAttributeService() { Check.assumeNotNull(bpartnerAwareAttributeService, "bpartnerAwareAttributeService not null"); return bpartnerAwareAttributeService; } /** * Sets if we shall copy the attribute even if it's a sales transaction (i.e. IsSOTrx=true) */ public final BPartnerAwareAttributeUpdater setForceApplyForSOTrx(final boolean forceApplyForSOTrx) { this.forceApplyForSOTrx = forceApplyForSOTrx; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\BPartnerAwareAttributeUpdater.java
1
请完成以下Java代码
public int getKeepAliveTimeMillis () { Integer ii = (Integer)get_Value(COLUMNNAME_KeepAliveTimeMillis); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Pool Size. @param PoolSize The number of threads to keep in the pool, even if they are idle */ @Override public void setPoolSize (int PoolSize) { set_Value (COLUMNNAME_PoolSize, Integer.valueOf(PoolSize)); } /** Get Pool Size. @return The number of threads to keep in the pool, even if they are idle */ @Override public int getPoolSize () { Integer ii = (Integer)get_Value(COLUMNNAME_PoolSize); if (ii == null) return 0; return ii.intValue(); }
/** * Priority AD_Reference_ID=154 * Reference name: _PriorityRule */ public static final int PRIORITY_AD_Reference_ID=154; /** High = 3 */ public static final String PRIORITY_High = "3"; /** Medium = 5 */ public static final String PRIORITY_Medium = "5"; /** Low = 7 */ public static final String PRIORITY_Low = "7"; /** Urgent = 1 */ public static final String PRIORITY_Urgent = "1"; /** Minor = 9 */ public static final String PRIORITY_Minor = "9"; /** Set Priority. @param Priority Indicates if this request is of a high, medium or low priority. */ @Override public void setPriority (java.lang.String Priority) { set_Value (COLUMNNAME_Priority, Priority); } /** Get Priority. @return Indicates if this request is of a high, medium or low priority. */ @Override public java.lang.String getPriority () { return (java.lang.String)get_Value(COLUMNNAME_Priority); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Processor.java
1
请完成以下Java代码
public ArticleRecord values(Integer value1, String value2, String value3, Integer value4) { value1(value1); value2(value2); value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached ArticleRecord */
public ArticleRecord() { super(Article.ARTICLE); } /** * Create a detached, initialised ArticleRecord */ public ArticleRecord(Integer id, String title, String description, Integer authorId) { super(Article.ARTICLE); set(0, id); set(1, title); set(2, description); set(3, authorId); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\ArticleRecord.java
1
请完成以下Java代码
public void onMsg(TbContext ctx, TbMsg msg) { withCallback(transform(ctx, msg), m -> transformSuccess(ctx, msg, m), t -> transformFailure(ctx, msg, t), MoreExecutors.directExecutor()); } protected abstract C loadNodeConfiguration(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException; protected void transformFailure(TbContext ctx, TbMsg msg, Throwable t) { ctx.tellFailure(msg, t); } protected void transformSuccess(TbContext ctx, TbMsg msg, List<TbMsg> msgs) { if (msgs == null || msgs.isEmpty()) { ctx.tellFailure(msg, new RuntimeException("Message or messages list are empty!")); } else if (msgs.size() == 1) { ctx.tellSuccess(msgs.get(0)); } else { TbMsgCallbackWrapper wrapper = new MultipleTbMsgsCallbackWrapper(msgs.size(), new TbMsgCallback() {
@Override public void onSuccess() { ctx.ack(msg); } @Override public void onFailure(RuleEngineException e) { ctx.tellFailure(msg, e); } }); msgs.forEach(newMsg -> ctx.enqueueForTellNext(newMsg, TbNodeConnectionType.SUCCESS, wrapper::onSuccess, wrapper::onFailure)); } } protected abstract ListenableFuture<List<TbMsg>> transform(TbContext ctx, TbMsg msg); }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\transform\TbAbstractTransformNode.java
1
请完成以下Java代码
public boolean equals(Object o) { return getDelegate().equals(o); } @SuppressWarnings("deprecation") @Override public void save(OutputStream out, String comments) { getDelegate().save(out, comments); } @Override public int hashCode() { return getDelegate().hashCode(); } @Override public void store(Writer writer, String comments) throws IOException { getDelegate().store(writer, comments); } @Override public void store(OutputStream out, String comments) throws IOException { getDelegate().store(out, comments); } @Override public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { getDelegate().loadFromXML(in); } @Override public void storeToXML(OutputStream os, String comment) throws IOException { getDelegate().storeToXML(os, comment); } @Override public void storeToXML(OutputStream os, String comment, String encoding) throws IOException { getDelegate().storeToXML(os, comment, encoding); } @Override public String getProperty(String key) { return getDelegate().getProperty(key); }
@Override public String getProperty(String key, String defaultValue) { return getDelegate().getProperty(key, defaultValue); } @Override public Enumeration<?> propertyNames() { return getDelegate().propertyNames(); } @Override public Set<String> stringPropertyNames() { return getDelegate().stringPropertyNames(); } @Override public void list(PrintStream out) { getDelegate().list(out); } @Override public void list(PrintWriter out) { getDelegate().list(out); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
1
请完成以下Java代码
public boolean unlinkModelFromMaterialTrackings(final Object model) { final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class); final List<I_M_Material_Tracking_Ref> existingRefs = materialTrackingDAO.retrieveMaterialTrackingRefsForModel(model); for (final I_M_Material_Tracking_Ref exitingRef : existingRefs) { unlinkModelFromMaterialTracking(model, exitingRef); } return true; } @Override public boolean unlinkModelFromMaterialTrackings(final Object model, @NonNull final I_M_Material_Tracking materialTracking) { final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class); final List<I_M_Material_Tracking_Ref> existingRefs = materialTrackingDAO.retrieveMaterialTrackingRefsForModel(model); if (existingRefs.isEmpty()) { return false; } boolean atLeastOneUnlinked = false; for (final I_M_Material_Tracking_Ref exitingRef : existingRefs) { if (exitingRef.getM_Material_Tracking_ID() != materialTracking.getM_Material_Tracking_ID()) { continue;
} unlinkModelFromMaterialTracking(model, exitingRef); atLeastOneUnlinked = true; } return atLeastOneUnlinked; } private final void unlinkModelFromMaterialTracking(final Object model, final I_M_Material_Tracking_Ref ref) { final I_M_Material_Tracking materialTrackingOld = ref.getM_Material_Tracking(); InterfaceWrapperHelper.delete(ref); listeners.afterModelUnlinked(model, materialTrackingOld); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingBL.java
1
请在Spring Boot框架中完成以下Java代码
public class Oauth2AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { private final HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository; private final SystemSecurityService systemSecurityService; @Autowired public Oauth2AuthenticationFailureHandler(final HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository, final SystemSecurityService systemSecurityService) { this.httpCookieOAuth2AuthorizationRequestRepository = httpCookieOAuth2AuthorizationRequestRepository; this.systemSecurityService = systemSecurityService; } @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { String baseUrl;
String errorPrefix; String callbackUrlScheme = null; OAuth2AuthorizationRequest authorizationRequest = httpCookieOAuth2AuthorizationRequestRepository.loadAuthorizationRequest(request); if (authorizationRequest != null) { callbackUrlScheme = authorizationRequest.getAttribute(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME); } if (!StringUtils.isEmpty(callbackUrlScheme)) { baseUrl = callbackUrlScheme + ":"; errorPrefix = "/?error="; } else { baseUrl = this.systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request); errorPrefix = "/login?loginError="; } httpCookieOAuth2AuthorizationRequestRepository.removeAuthorizationRequestCookies(request, response); getRedirectStrategy().sendRedirect(request, response, baseUrl + errorPrefix + URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8.toString())); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\Oauth2AuthenticationFailureHandler.java
2
请完成以下Java代码
public void printStats() { if (log.isDebugEnabled()) { storage.forEach((topic, queue) -> { if (queue.size() > 0) { log.debug("[{}] Queue Size [{}]", topic, queue.size()); } }); } } @Override public int getLagTotal() { return storage.values().stream().map(BlockingQueue::size).reduce(0, Integer::sum); } @Override public int getLag(String topic) { return Optional.ofNullable(storage.get(topic)).map(Collection::size).orElse(0); } @Override public boolean put(String topic, TbQueueMsg msg) { return storage.computeIfAbsent(topic, (t) -> new LinkedBlockingQueue<>()).add(msg); } @SuppressWarnings("unchecked")
@Override public <T extends TbQueueMsg> List<T> get(String topic) throws InterruptedException { final BlockingQueue<TbQueueMsg> queue = storage.get(topic); if (queue != null) { final TbQueueMsg firstMsg = queue.poll(); if (firstMsg != null) { final int queueSize = queue.size(); if (queueSize > 0) { final List<TbQueueMsg> entities = new ArrayList<>(Math.min(queueSize, 999) + 1); entities.add(firstMsg); queue.drainTo(entities, 999); return (List<T>) entities; } return Collections.singletonList((T) firstMsg); } } return Collections.emptyList(); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\memory\DefaultInMemoryStorage.java
1
请完成以下Java代码
protected String getInternalValueString() { return attributeInstance.getValue(); } @Override protected BigDecimal getInternalValueNumber() { return attributeInstance.getValueNumber(); } @Override protected String getInternalValueStringInitial() { return null; } /** * @return <code>null</code>. */ @Override protected BigDecimal getInternalValueNumberInitial() { return null; } @Override protected void setInternalValueStringInitial(final String value) { throw new UnsupportedOperationException("Setting initial value not supported"); } @Override protected void setInternalValueNumberInitial(final BigDecimal value) { throw new UnsupportedOperationException("Setting initial value not supported"); } @Override public boolean isNew() { return InterfaceWrapperHelper.isNew(attributeInstance); } @Override protected void setInternalValueDate(Date value) { attributeInstance.setValueDate(TimeUtil.asTimestamp(value)); } @Override protected Date getInternalValueDate() { return attributeInstance.getValueDate(); } @Override protected void setInternalValueDateInitial(Date value) { throw new UnsupportedOperationException("Setting initial value not supported"); } @Override protected Date getInternalValueDateInitial() { return null; } /** * @return {@code PROPAGATIONTYPE_NoPropagation}. */ @Override public String getPropagationType() { return X_M_HU_PI_Attribute.PROPAGATIONTYPE_NoPropagation; } /** * @return {@link NullAggregationStrategy#instance}. */ @Override public IAttributeAggregationStrategy retrieveAggregationStrategy() { return NullAggregationStrategy.instance; } /** * @return {@link NullSplitterStrategy#instance}. */ @Override public IAttributeSplitterStrategy retrieveSplitterStrategy() { return NullSplitterStrategy.instance; } /**
* @return {@link CopyHUAttributeTransferStrategy#instance}. */ @Override public IHUAttributeTransferStrategy retrieveTransferStrategy() { return CopyHUAttributeTransferStrategy.instance; } /** * @return {@code true}. */ @Override public boolean isReadonlyUI() { return true; } /** * @return {@code true}. */ @Override public boolean isDisplayedUI() { return true; } @Override public boolean isMandatory() { return false; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } /** * @return our attribute instance's {@code M_Attribute_ID}. */ @Override public int getDisplaySeqNo() { return attributeInstance.getM_Attribute_ID(); } /** * @return {@code true} */ @Override public boolean isUseInASI() { return true; } /** * @return {@code false}, since no HU-PI attribute is involved. */ @Override public boolean isDefinedByTemplate() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\AIAttributeValue.java
1
请完成以下Java代码
public List<Model> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getModelEntityManager().findModelsByQueryCriteria(this, page); } // getters //////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() { return nameLike; } public Integer getVersion() { return version; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public static long getSerialversionuid() { return serialVersionUID; } public String getKey() {
return key; } public boolean isLatest() { return latest; } public String getDeploymentId() { return deploymentId; } public boolean isNotDeployed() { return notDeployed; } public boolean isDeployed() { return deployed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ModelQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getUsername() { return this.username; } public void setUsername(@Nullable String username) { this.username = username; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } boolean isAvailable() { return StringUtils.hasText(this.username) && StringUtils.hasText(this.password); } } public static class Validation { /** * Whether to enable LDAP schema validation. */ private boolean enabled = true; /** * Path to the custom schema. */ private @Nullable Resource schema; public boolean isEnabled() { return this.enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable Resource getSchema() { return this.schema; } public void setSchema(@Nullable Resource schema) { this.schema = schema; } } }
repos\spring-boot-4.0.1\module\spring-boot-ldap\src\main\java\org\springframework\boot\ldap\autoconfigure\embedded\EmbeddedLdapProperties.java
2
请完成以下Java代码
public Book where(Condition condition) { return new Book(getQualifiedName(), aliased() ? this : null, null, condition); } /** * Create an inline derived table from this table */ @Override public Book where(Collection<? extends Condition> conditions) { return where(DSL.and(conditions)); } /** * Create an inline derived table from this table */ @Override public Book where(Condition... conditions) { return where(DSL.and(conditions)); } /** * Create an inline derived table from this table */ @Override public Book where(Field<Boolean> condition) { return where(DSL.condition(condition)); } /** * Create an inline derived table from this table */ @Override @PlainSQL public Book where(SQL condition) { return where(DSL.condition(condition)); } /** * Create an inline derived table from this table */ @Override
@PlainSQL public Book where(@Stringly.SQL String condition) { return where(DSL.condition(condition)); } /** * Create an inline derived table from this table */ @Override @PlainSQL public Book where(@Stringly.SQL String condition, Object... binds) { return where(DSL.condition(condition, binds)); } /** * Create an inline derived table from this table */ @Override @PlainSQL public Book where(@Stringly.SQL String condition, QueryPart... parts) { return where(DSL.condition(condition, parts)); } /** * Create an inline derived table from this table */ @Override public Book whereExists(Select<?> select) { return where(DSL.exists(select)); } /** * Create an inline derived table from this table */ @Override public Book whereNotExists(Select<?> select) { return where(DSL.notExists(select)); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\Book.java
1
请完成以下Java代码
private static void markCovered(final boolean[] pagesCovered, final int pageFrom, final int pageTo) { for (int i = pageFrom; i <= pageTo; i++) { pagesCovered[i - 1] = true; } } public boolean hasData() { return data != null; } public int getNumberOfPages() { Integer numberOfPages = this._numberOfPages; if (numberOfPages == null) { numberOfPages = this._numberOfPages = computeNumberOfPages(); } return numberOfPages; } private int computeNumberOfPages() { if (!hasData()) { return 0; } PdfReader reader = null; try { reader = new PdfReader(getData()); return reader.getNumberOfPages(); } catch (final IOException e) { throw new AdempiereException("Cannot get number of pages for C_Printing_Queue_ID=" + printingQueueItemId.getRepoId(), e); } finally { if (reader != null) { try { reader.close(); } catch (final Exception ignored)
{ } } } } public PrintingData onlyWithType(@NonNull final OutputType outputType) { final ImmutableList<PrintingSegment> filteredSegments = segments.stream() .filter(segment -> segment.isMatchingOutputType(outputType)) .collect(ImmutableList.toImmutableList()); return toBuilder() .clearSegments() .segments(filteredSegments) .adjustSegmentPageRanges(false) .build(); } public PrintingData onlyQueuedForExternalSystems() { final ImmutableList<PrintingSegment> filteredSegments = segments.stream() .filter(PrintingSegment::isQueuedForExternalSystems) .collect(ImmutableList.toImmutableList()); return toBuilder() .clearSegments() .segments(filteredSegments) .adjustSegmentPageRanges(false) .build(); } public boolean hasSegments() {return !getSegments().isEmpty();} public int getSegmentsCount() {return getSegments().size();} public ImmutableSet<String> getPrinterNames() { return segments.stream() .map(segment -> segment.getPrinter().getName()) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingData.java
1
请完成以下Java代码
public boolean callStoredProcedure() throws SQLException { try (CallableStatement callableStatement = connection.prepareCall("{CALL InsertMultipleUsers()}")) { callableStatement.execute(); return true; } } public List<User> executeMultipleSelectStatements() throws SQLException { String sql = "SELECT * FROM users WHERE email = 'alice@example.com';" + "SELECT * FROM users WHERE email = 'bob@example.com';"; List<User> users = new ArrayList<>(); try (Statement statement = connection.createStatement()) { statement.execute(sql); // Here we execute the multiple queries
do { try (ResultSet resultSet = statement.getResultSet()) { while (resultSet != null && resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String email = resultSet.getString("email"); users.add(new User(id, name, email)); } } } while (statement.getMoreResults()); } return users; } }
repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\sql\MultipleSQLExecution.java
1
请完成以下Java代码
public class Todo { public Todo() { } public Todo(String title, String text) { this.title = title; this.text = text; createdOn = new Date(); } private String title; private String text; private boolean done = false; private Date createdOn; private Date completedOn; public void markAsDone() { done = true; completedOn = new Date(); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; }
public boolean getDone() { return done; } public Date getCreatedOn() { return createdOn; } public Date getCompletedOn() { return completedOn; } public void setDone(boolean done) { this.done = done; } public void setCompletedOn(Date completedOn) { this.completedOn = completedOn; } public long doneSince() { return done ? Duration .between(createdOn.toInstant(), completedOn.toInstant()) .toMinutes() : 0; } public Function<Object, Object> handleDone() { return (obj) -> done ? String.format("<small>Done %s minutes ago<small>", obj) : ""; } }
repos\tutorials-master\mustache\src\main\java\com\baeldung\mustache\model\Todo.java
1
请完成以下Java代码
public org.compiere.model.I_C_DataImport getC_DataImport() { return get_ValueAsPO(COLUMNNAME_C_DataImport_ID, org.compiere.model.I_C_DataImport.class); } @Override public void setC_DataImport(org.compiere.model.I_C_DataImport C_DataImport) { set_ValueFromPO(COLUMNNAME_C_DataImport_ID, org.compiere.model.I_C_DataImport.class, C_DataImport); } /** Set Daten Import. @param C_DataImport_ID Daten Import */ @Override public void setC_DataImport_ID (int C_DataImport_ID) { if (C_DataImport_ID < 1) set_Value (COLUMNNAME_C_DataImport_ID, null); else set_Value (COLUMNNAME_C_DataImport_ID, Integer.valueOf(C_DataImport_ID)); } /** Get Daten Import. @return Daten Import */ @Override public int getC_DataImport_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Data Import Run. @param C_DataImport_Run_ID Data Import Run */ @Override public void setC_DataImport_Run_ID (int C_DataImport_Run_ID) { if (C_DataImport_Run_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DataImport_Run_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DataImport_Run_ID, Integer.valueOf(C_DataImport_Run_ID)); } /** Get Data Import Run. @return Data Import Run */ @Override
public int getC_DataImport_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_Run_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beleg fertig stellen. @param IsDocComplete Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen. */ @Override public void setIsDocComplete (boolean IsDocComplete) { set_Value (COLUMNNAME_IsDocComplete, Boolean.valueOf(IsDocComplete)); } /** Get Beleg fertig stellen. @return Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen. */ @Override public boolean isDocComplete () { Object oo = get_Value(COLUMNNAME_IsDocComplete); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DataImport_Run.java
1
请完成以下Spring Boot application配置
spring.jackson.serialization.fail-on-empty-beans=false server.servlet.session.timeout=65s spring.mvc.view.prefix=/WEB-INF/view/ spring.mvc.view.suffix=.jsp ## Secure Session Cookie configurations #
server.servlet.session.cookie.http-only=true #server.servlet.session.cookie.secure=true
repos\tutorials-master\spring-security-modules\spring-security-web-mvc\src\main\resources\application.properties
2
请完成以下Java代码
private OrderQueryReq buildOrderQueryReq(String orderId, String buyerId) { OrderQueryReq orderQueryReq = new OrderQueryReq(); orderQueryReq.setId(orderId); orderQueryReq.setBuyerId(buyerId); return orderQueryReq; } /** * 构建prodIdCountMap * @param ordersEntity 订单详情 * @return prodIdCountMap */ private Map<String, Integer> buildProdIdCountMap(OrdersEntity ordersEntity) { // 初始化结果集 Map<String, Integer> prodIdCountMap = Maps.newHashMap(); // 获取产品列表 List<ProductOrderEntity> productOrderList = ordersEntity.getProductOrderList(); // 构造结果集 for (ProductOrderEntity productOrderEntity : productOrderList) { // 产品ID String prodId = productOrderEntity.getProductEntity().getId(); // 购买数量 Integer count = productOrderEntity.getCount(); prodIdCountMap.put(prodId, count); } return prodIdCountMap; }
/** * 将prodIdCountMap装入Context * @param prodIdCountMap * @param payModeEnum * @param orderProcessContext */ private void setIntoContext(Map<String, Integer> prodIdCountMap, PayModeEnum payModeEnum, OrderProcessContext orderProcessContext) { // 构造 订单插入请求 OrderInsertReq orderInsertReq = new OrderInsertReq(); // 插入prodIdCountMap orderInsertReq.setProdIdCountMap(prodIdCountMap); // 插入支付方式 orderInsertReq.setPayModeCode(payModeEnum.getCode()); orderProcessContext.getOrderProcessReq().setReqData(orderInsertReq); } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\datatransfer\ProdIdCountMapTransferComponent.java
1
请完成以下Java代码
public List<DDOrderReference> getCollectedItems() { processPendingRequests(); return _result; } @NonNull private DistributionJobLoader newLoader() { return new DistributionJobLoader(loadingSupportServices); } private void processPendingRequests() { if (collectedDDOrders.isEmpty()) {return;} newLoader() .loadByRecords(collectedDDOrders) .stream() .map(DDOrderReferenceCollector::toDDOrderReference) .forEach(_result::add); collectedDDOrders.clear(); } @NonNull private static DDOrderReference toDDOrderReference(final DistributionJob job) { return DDOrderReference.builder() .ddOrderId(job.getDdOrderId())
.documentNo(job.getDocumentNo()) .seqNo(job.getSeqNo()) .datePromised(job.getDateRequired()) .pickDate(job.getPickDate()) .fromWarehouseId(job.getPickFromWarehouse().getWarehouseId()) .toWarehouseId(job.getDropToWarehouse().getWarehouseId()) .salesOrderId(job.getSalesOrderRef() != null ? job.getSalesOrderRef().getId() : null) .ppOrderId(job.getManufacturingOrderRef() != null ? job.getManufacturingOrderRef().getId() : null) .isJobStarted(job.isJobAssigned()) .plantId(job.getPlantInfo() != null ? job.getPlantInfo().getResourceId() : null) .priority(job.getPriority()) .fromLocatorId(job.getSinglePickFromLocatorIdOrNull()) .toLocatorId(job.getSingleDropToLocatorIdOrNull()) .productId(job.getSingleProductIdOrNull()) .qty(job.getSingleUnitQuantityOrNull()) .isInTransit(job.isInTransit()) .build(); } @NonNull private static DDOrderId extractDDOrderId(final I_DD_Order ddOrder) {return DDOrderId.ofRepoId(ddOrder.getDD_Order_ID());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DDOrderReferenceCollector.java
1
请完成以下Java代码
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddress(from); } public void setFromBillLocation(@NonNull final I_C_Order from) { setFrom(OrderDocumentLocationAdapterFactory.billLocationAdapter(from).toDocumentLocation()); } @Override public I_C_Order getWrappedRecord() {
return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public OrderBillLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new OrderBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderBillLocationAdapter.java
1
请完成以下Java代码
private static final class VEditorInnerTextComponentUI implements PropertyChangeListener { public static final transient VEditorInnerTextComponentUI instance = new VEditorInnerTextComponentUI(); /** Component's UI property */ private static final String PROPERTY_UI = "UI"; private VEditorInnerTextComponentUI() { super(); } public void installUI(final JComponent comp) { updateUI(comp); comp.addPropertyChangeListener("UI", this); } /** Actually sets the UI properties */ private void updateUI(final JComponent comp) { comp.setBorder(null); comp.setFont(AdempierePLAF.getFont_Field()); comp.setForeground(AdempierePLAF.getTextColor_Normal()); }
@Override public void propertyChange(PropertyChangeEvent evt) { if (PROPERTY_UI.equals(evt.getPropertyName())) { final JComponent comp = (JComponent)evt.getSource(); updateUI(comp); } } } private VEditorUtils() { super(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorUtils.java
1
请在Spring Boot框架中完成以下Java代码
private String determineEmbeddedUsername(R2dbcProperties properties) { String username = ifHasText(properties.getUsername()); return (username != null) ? username : "sa"; } private ConnectionFactoryBeanCreationException connectionFactoryBeanCreationException(String message, @Nullable String r2dbcUrl, EmbeddedDatabaseConnection embeddedDatabaseConnection) { return new ConnectionFactoryBeanCreationException(message, r2dbcUrl, embeddedDatabaseConnection); } private @Nullable String ifHasText(@Nullable String candidate) { return (StringUtils.hasText(candidate)) ? candidate : null; } static class ConnectionFactoryBeanCreationException extends BeanCreationException { private final @Nullable String url; private final EmbeddedDatabaseConnection embeddedDatabaseConnection; ConnectionFactoryBeanCreationException(String message, @Nullable String url,
EmbeddedDatabaseConnection embeddedDatabaseConnection) { super(message); this.url = url; this.embeddedDatabaseConnection = embeddedDatabaseConnection; } @Nullable String getUrl() { return this.url; } EmbeddedDatabaseConnection getEmbeddedDatabaseConnection() { return this.embeddedDatabaseConnection; } } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\ConnectionFactoryOptionsInitializer.java
2
请完成以下Java代码
private int appendNode() { int id; if (_recycleBin.empty()) { id = _nodes.size(); _nodes.add(new DawgNode()); } else { id = _recycleBin.get(_recycleBin.size() - 1); _nodes.get(id).reset(); _recycleBin.deleteLast(); } return id; } private void freeNode(int id) { _recycleBin.add(id); }
private static int hash(int key) { key = ~key + (key << 15); // key = (key << 15) - key - 1; key = key ^ (key >>> 12); key = key + (key << 2); key = key ^ (key >>> 4); key = key * 2057; // key = (key + (key << 3)) + (key << 11); key = key ^ (key >>> 16); return key; } private static final int INITIAL_TABLE_SIZE = 1 << 10; private ArrayList<DawgNode> _nodes = new ArrayList<DawgNode>(); private AutoIntPool _units = new AutoIntPool(); private AutoBytePool _labels = new AutoBytePool(); private BitVector _isIntersections = new BitVector(); private AutoIntPool _table = new AutoIntPool(); private AutoIntPool _nodeStack = new AutoIntPool(); private AutoIntPool _recycleBin = new AutoIntPool(); private int _numStates; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\DawgBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public void setDateEnd(final LocalDate dateEnd) { this.dateEnd = DateUtils.toSqlDate(dateEnd); } public Long getBpartnerId() { return getBpartner().getId(); } public LocalDate getDateClose() { return DateUtils.toLocalDate(dateClose); } public void setDateClose(final LocalDate dateClose) { this.dateClose = DateUtils.toSqlDate(dateClose); } public List<RfqQty> getQuantities() { return quantities; } public ImmutableSet<LocalDate> generateAllDaysSet() { final ArrayList<LocalDate> dates = DateUtils.getDaysList(getDateStart(), getDateEnd()); dates.addAll(quantities .stream() .map(RfqQty::getDatePromised) .collect(ImmutableSet.toImmutableSet())); dates.sort(LocalDate::compareTo); return ImmutableSet.copyOf(dates); } public void setPricePromisedUserEntered(@NonNull final BigDecimal pricePromisedUserEntered) { this.pricePromisedUserEntered = pricePromisedUserEntered; } public BigDecimal getQtyPromisedUserEntered() { return quantities.stream() .map(RfqQty::getQtyPromisedUserEntered) .reduce(BigDecimal.ZERO, BigDecimal::add); } public void setQtyPromised(@NonNull final LocalDate date, @NonNull final BigDecimal qtyPromised) { final RfqQty rfqQty = getOrCreateQty(date); rfqQty.setQtyPromisedUserEntered(qtyPromised); updateConfirmedByUser(); } private RfqQty getOrCreateQty(@NonNull final LocalDate date) { final RfqQty existingRfqQty = getRfqQtyByDate(date); if (existingRfqQty != null) { return existingRfqQty; } else { final RfqQty rfqQty = RfqQty.builder() .rfq(this) .datePromised(date) .build(); addRfqQty(rfqQty); return rfqQty; } } private void addRfqQty(final RfqQty rfqQty) {
rfqQty.setRfq(this); quantities.add(rfqQty); } @Nullable public RfqQty getRfqQtyByDate(@NonNull final LocalDate date) { for (final RfqQty rfqQty : quantities) { if (date.equals(rfqQty.getDatePromised())) { return rfqQty; } } return null; } private void updateConfirmedByUser() { this.confirmedByUser = computeConfirmedByUser(); } private boolean computeConfirmedByUser() { if (pricePromised.compareTo(pricePromisedUserEntered) != 0) { return false; } for (final RfqQty rfqQty : quantities) { if (!rfqQty.isConfirmedByUser()) { return false; } } return true; } public void closeIt() { this.closed = true; } public void confirmByUser() { this.pricePromised = getPricePromisedUserEntered(); quantities.forEach(RfqQty::confirmByUser); updateConfirmedByUser(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Rfq.java
2
请在Spring Boot框架中完成以下Java代码
public void requestOrdersStatus() throws Exception{ List<Orders> ordersList = orderRepository.findAllByStatusAndPaymentNumberIsNotNull(OrderStatus.awaitingPayment); for(Orders orders: ordersList){ PaymentStatusResponse paymentStatusResponse = paymentService.getPaymentStatus(orders.getPaymentNumber()); if (paymentStatusResponse.getState().equals("payed") || paymentStatusResponse.getState().equals("processed") || paymentStatusResponse.getState().equals("holded")) { orders.setStatus(OrderStatus.paid); orderRepository.save(orders); producer.sendOrderRequest(orders); taxiOrderProcess.createTaxiOrder(orders, orders.getOrderDetailsList().get(0).getGood().getRetailer()); } } } @Scheduled(fixedDelayString = "${tm.requestTaxiOrderStatus.pauseTimeSec}000") public void requestTaxiOrderStatus() throws Exception{ List<Orders> ordersList = orderRepository.findAllByStatusAndPaymentNumberIsNotNull(OrderStatus.awaitingPayment); for(Orders orders: ordersList){ OrderStatus prevOrderStatus = orders.getStatus(); Map<String, String> mapResult = taxiOrderProcess.getTaxiOrderStatus(orders.getTaxiOrderId(), orders.getOrderDetailsList().get(0).getGood().getRetailer()); if(mapResult !=null){ switch (mapResult.get("get_order_state")) { case "new_order": ordersSave(orders, OrderStatus.courierSearch, mapResult); break; case "driver_assigned": ordersSave(orders, OrderStatus.courierFound, mapResult); break; case "car_at_place": ordersSave(orders, OrderStatus.courierFound, mapResult);
break; case "client_inside": ordersSave(orders, OrderStatus.deliveryInProgress, mapResult); break; case "finished": ordersSave(orders, OrderStatus.awaitingConfirmation, mapResult); break; } } if(!prevOrderStatus.equals(orders.getStatus())){ producer.sendOrderRequest(orders); } } } private void ordersSave(Orders orders, OrderStatus status, Map<String, String> mapResult) { orders.setCarColor(mapResult.get("car_color")); orders.setCarMark(mapResult.get("car_mark")); orders.setCarModel(mapResult.get("car_model")); orders.setCarNumber(mapResult.get("car_number")); orders.setStatus(status); orders.setNameDriver(mapResult.get("name")); orders.setPhoneDriver(mapResult.get("phones")); orderRepository.save(orders); } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\schedule\OrderStatusRequester.java
2
请在Spring Boot框架中完成以下Java代码
public void audit(String userNo, String auditStatus){ RpUserPayConfig rpUserPayConfig = getByUserNo(userNo, null); if(rpUserPayConfig == null){ throw new PayBizException(PayBizException.USER_PAY_CONFIG_IS_NOT_EXIST,"支付配置不存在!"); } if(auditStatus.equals(PublicEnum.YES.name())){ //检查是否已关联生效的支付产品 RpPayProduct rpPayProduct = rpPayProductService.getByProductCode(rpUserPayConfig.getProductCode(), PublicEnum.YES.name()); if(rpPayProduct == null){ throw new PayBizException(PayBizException.PAY_PRODUCT_IS_NOT_EXIST,"未关联已生效的支付产品,无法操作!"); } //检查是否已设置第三方支付信息 } rpUserPayConfig.setAuditStatus(auditStatus); rpUserPayConfig.setEditTime(new Date());
updateData(rpUserPayConfig); } /** * 根据商户key获取已生效的支付配置 * @param payKey * @return */ public RpUserPayConfig getByPayKey(String payKey){ Map<String , Object> paramMap = new HashMap<String , Object>(); paramMap.put("payKey", payKey); paramMap.put("status", PublicStatusEnum.ACTIVE.name()); paramMap.put("auditStatus", PublicEnum.YES.name()); return rpUserPayConfigDao.getBy(paramMap); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\RpUserPayConfigServiceImpl.java
2
请完成以下Java代码
public boolean isZero() { return amtSource.signum() == 0 && amtAcct.signum() == 0; } public boolean isZeroAmtSource() { return amtSource.signum() == 0; } public AmountSourceAndAcct negate() { return isZero() ? this : toBuilder().amtSource(this.amtSource.negate()).amtAcct(this.amtAcct.negate()).build(); } public AmountSourceAndAcct add(@NonNull final AmountSourceAndAcct other) { assertCurrencyAndRateMatching(other); if (other.isZero()) { return this; } else if (this.isZero()) { return other; } else { return toBuilder() .amtSource(this.amtSource.add(other.amtSource))
.amtAcct(this.amtAcct.add(other.amtAcct)) .build(); } } public AmountSourceAndAcct subtract(@NonNull final AmountSourceAndAcct other) { return add(other.negate()); } private void assertCurrencyAndRateMatching(@NonNull final AmountSourceAndAcct other) { if (!Objects.equals(this.currencyAndRate, other.currencyAndRate)) { throw new AdempiereException("Currency rate not matching: " + this.currencyAndRate + ", " + other.currencyAndRate); } } } } // Doc_Bank
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\Doc_BankStatement.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonCreatedUpdatedInfo { @ApiModelProperty( // allowEmptyValue = false, // dataType = "java.lang.Integer", // value = "This translates to `AD_User_ID`.") UserId createdBy; ZonedDateTime created; @ApiModelProperty( // allowEmptyValue = false, // dataType = "java.lang.Integer", // value = "This translates to `AD_User_ID`.") UserId updatedBy; ZonedDateTime updated;
@Builder @JsonCreator private JsonCreatedUpdatedInfo( @NonNull @JsonProperty("createdBy") final UserId createdBy, @NonNull @JsonProperty("created") final ZonedDateTime created, @NonNull @JsonProperty("updatedBy") final UserId updatedBy, @NonNull @JsonProperty("updated") final ZonedDateTime updated) { this.createdBy = createdBy; this.created = created; this.updatedBy = updatedBy; this.updated = updated; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\JsonCreatedUpdatedInfo.java
2
请在Spring Boot框架中完成以下Java代码
private void validateAlgorithm(Token token) { String algorithm = token.getSignatureAlgorithm(); if (algorithm == null) { throw new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, "Signing algorithm cannot be null"); } if (!algorithm.equals("RS256")) { throw new CloudFoundryAuthorizationException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM, "Signing algorithm " + algorithm + " not supported"); } } private void validateKeyIdAndSignature(Token token) { String keyId = token.getKeyId(); Map<String, String> tokenKeys = this.tokenKeys; if (tokenKeys == null || !hasValidKeyId(tokenKeys, keyId)) { tokenKeys = this.securityService.fetchTokenKeys(); if (!hasValidKeyId(tokenKeys, keyId)) { throw new CloudFoundryAuthorizationException(Reason.INVALID_KEY_ID, "Key Id present in token header does not match"); } this.tokenKeys = tokenKeys; } String key = tokenKeys.get(keyId); Assert.state(key != null, "'key' must not be null"); if (!hasValidSignature(token, key)) { throw new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, "RSA Signature did not match content"); } } private boolean hasValidKeyId(Map<String, String> tokenKeys, String tokenKey) { return tokenKeys.containsKey(tokenKey); } private boolean hasValidSignature(Token token, String key) { try { PublicKey publicKey = getPublicKey(key); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initVerify(publicKey); signature.update(token.getContent()); return signature.verify(token.getSignature()); } catch (GeneralSecurityException ex) { return false; } }
private PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException { key = key.replace("-----BEGIN PUBLIC KEY-----\n", ""); key = key.replace("-----END PUBLIC KEY-----", ""); key = key.trim().replace("\n", ""); byte[] bytes = Base64.getDecoder().decode(key); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); return KeyFactory.getInstance("RSA").generatePublic(keySpec); } private void validateExpiry(Token token) { long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); if (currentTime > token.getExpiry()) { throw new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, "Token expired"); } } private void validateIssuer(Token token) { String uaaUrl = this.securityService.getUaaUrl(); String issuerUri = String.format("%s/oauth/token", uaaUrl); if (!issuerUri.equals(token.getIssuer())) { throw new CloudFoundryAuthorizationException(Reason.INVALID_ISSUER, "Token issuer does not match " + uaaUrl + "/oauth/token"); } } private void validateAudience(Token token) { if (!token.getScope().contains("actuator.read")) { throw new CloudFoundryAuthorizationException(Reason.INVALID_AUDIENCE, "Token does not have audience actuator"); } } }
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\servlet\TokenValidator.java
2
请完成以下Java代码
public static long getSerialversionuid() { return serialVersionUID; } public String getKey() { return key; } public boolean isLatest() { return latest; } public String getDeploymentId() { return deploymentId; } public boolean isNotDeployed() { return notDeployed;
} public boolean isDeployed() { return deployed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ModelQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setAdditionalAddress2(String additionalAddress2) { this.additionalAddress2 = additionalAddress2; } public OrderDeliveryAddress postalCode(String postalCode) { this.postalCode = postalCode; return this; } /** * Get postalCode * @return postalCode **/ @Schema(example = "90489", required = true, description = "") public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public OrderDeliveryAddress city(String city) { this.city = city; return this; } /** * Get city * @return city **/ @Schema(example = "Nürnberg", required = true, description = "") public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderDeliveryAddress orderDeliveryAddress = (OrderDeliveryAddress) o; return Objects.equals(this.gender, orderDeliveryAddress.gender) && Objects.equals(this.title, orderDeliveryAddress.title) && Objects.equals(this.name, orderDeliveryAddress.name) && Objects.equals(this.address, orderDeliveryAddress.address) && Objects.equals(this.additionalAddress, orderDeliveryAddress.additionalAddress) && Objects.equals(this.additionalAddress2, orderDeliveryAddress.additionalAddress2) && Objects.equals(this.postalCode, orderDeliveryAddress.postalCode) && Objects.equals(this.city, orderDeliveryAddress.city); } @Override public int hashCode() { return Objects.hash(gender, title, name, address, additionalAddress, additionalAddress2, postalCode, city); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderDeliveryAddress {\n"); sb.append(" gender: ").append(toIndentedString(gender)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" additionalAddress: ").append(toIndentedString(additionalAddress)).append("\n"); sb.append(" additionalAddress2: ").append(toIndentedString(additionalAddress2)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).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\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderDeliveryAddress.java
2
请在Spring Boot框架中完成以下Java代码
public DataResponse<HistoricDetailResponse> getHistoricDetailInfo(@ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams) { // Populate query based on request HistoricDetailQueryRequest queryRequest = new HistoricDetailQueryRequest(); if (allRequestParams.get("id") != null) { queryRequest.setId(allRequestParams.get("id")); } if (allRequestParams.get("processInstanceId") != null) { queryRequest.setProcessInstanceId(allRequestParams.get("processInstanceId")); } if (allRequestParams.get("executionId") != null) { queryRequest.setExecutionId(allRequestParams.get("executionId")); } if (allRequestParams.get("activityInstanceId") != null) { queryRequest.setActivityInstanceId(allRequestParams.get("activityInstanceId"));
} if (allRequestParams.get("taskId") != null) { queryRequest.setTaskId(allRequestParams.get("taskId")); } if (allRequestParams.get("selectOnlyFormProperties") != null) { queryRequest.setSelectOnlyFormProperties(Boolean.valueOf(allRequestParams.get("selectOnlyFormProperties"))); } if (allRequestParams.get("selectOnlyVariableUpdates") != null) { queryRequest.setSelectOnlyVariableUpdates(Boolean.valueOf(allRequestParams.get("selectOnlyVariableUpdates"))); } return getQueryResponse(queryRequest, allRequestParams); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailCollectionResource.java
2
请完成以下Java代码
public class CoapEfentoUtils { public static final int PULSE_CNT_ACC_MINOR_METADATA_FACTOR = 6; public static final int PULSE_CNT_ACC_MAJOR_METADATA_FACTOR = 4; public static final int ELEC_METER_ACC_MINOR_METADATA_FACTOR = 6; public static final int ELEC_METER_ACC_MAJOR_METADATA_FACTOR = 4; public static final int PULSE_CNT_ACC_WIDE_MINOR_METADATA_FACTOR = 6; public static final int PULSE_CNT_ACC_WIDE_MAJOR_METADATA_FACTOR = 4; public static final int WATER_METER_ACC_MINOR_METADATA_FACTOR = 6; public static final int WATER_METER_ACC_MAJOR_METADATA_FACTOR = 4; public static final int IAQ_METADATA_FACTOR = 3; public static final int STATIC_IAQ_METADATA_FACTOR = 3; public static final int CO2_GAS_METADATA_FACTOR = 3; public static final int CO2_EQUIVALENT_METADATA_FACTOR = 3; public static final int BREATH_VOC_METADATA_FACTOR = 3; public static String convertByteArrayToString(byte[] a) { StringBuilder out = new StringBuilder(); for (byte b : a) { out.append(String.format("%02X", b)); } return out.toString(); } public static String convertTimestampToUtcString(long timestampInMillis) { String dateFormat = "yyyy-MM-dd HH:mm:ss"; String utcZone = "UTC"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); simpleDateFormat.setTimeZone(TimeZone.getTimeZone(utcZone)); return String.format("%s UTC", simpleDateFormat.format(new Date(timestampInMillis))); } public static JsonObject setDefaultMeasurements(String serialNumber, boolean batteryStatus, long measurementPeriod, long nextTransmissionAtMillis, long signal, long startTimestampMillis) { JsonObject values = new JsonObject();
values.addProperty("serial", serialNumber); values.addProperty("battery", batteryStatus ? "ok" : "low"); values.addProperty("measured_at", convertTimestampToUtcString(startTimestampMillis)); values.addProperty("next_transmission_at", convertTimestampToUtcString(nextTransmissionAtMillis)); values.addProperty("signal", signal); values.addProperty("measurement_interval", measurementPeriod); return values; } public static boolean isBinarySensor(MeasurementType type) { return type == MEASUREMENT_TYPE_OK_ALARM || type == MEASUREMENT_TYPE_FLOODING || type == MEASUREMENT_TYPE_OUTPUT_CONTROL; } public static boolean isSensorError(int sampleOffset) { return sampleOffset >= 8355840 && sampleOffset <= 8388607; } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\efento\utils\CoapEfentoUtils.java
1
请完成以下Java代码
public static File getClasspathFile(String filename) { if(filename == null) { throw LOG.nullParameter("filename"); } return getClasspathFile(filename, null); } /** * Returns the File for a filename. * * @param filename the filename to load * @param classLoader the classLoader to load file with, if null falls back to TCCL and then this class's classloader * @return the file object * @throws IoUtilException if the file cannot be loaded */ public static File getClasspathFile(String filename, ClassLoader classLoader) { if(filename == null) { throw LOG.nullParameter("filename"); } URL fileUrl = null; if (classLoader != null) { fileUrl = classLoader.getResource(filename); } if (fileUrl == null) {
// Try the current Thread context classloader classLoader = Thread.currentThread().getContextClassLoader(); fileUrl = classLoader.getResource(filename); if (fileUrl == null) { // Finally, try the classloader for this class classLoader = IoUtil.class.getClassLoader(); fileUrl = classLoader.getResource(filename); } } if(fileUrl == null) { throw LOG.fileNotFoundException(filename); } try { return new File(fileUrl.toURI()); } catch(URISyntaxException e) { throw LOG.fileNotFoundException(filename, e); } } }
repos\camunda-bpm-platform-master\commons\utils\src\main\java\org\camunda\commons\utils\IoUtil.java
1
请完成以下Java代码
public static final Object[] getUIDefaults() { return new Object[] { // // Notifications settings NOTIFICATIONS_MaxDisplayed, NOTIFICATIONS_MaxDisplayed_Default , NOTIFICATIONS_AutoFadeAwayTimeMillis, NOTIFICATIONS_AutoFadeAwayTimeMillis_Default , NOTIFICATIONS_BottomGap, NOTIFICATIONS_BottomGap_Default // // Item settings , ITEM_BackgroundColor, AdempierePLAF.createActiveValueProxy(AdempiereLookAndFeel.MANDATORY_BG_KEY, Color.WHITE) // same as mandatory background color , ITEM_Border, new BorderUIResource(BorderFactory.createLineBorder(Color.GRAY, 1)) , ITEM_SummaryText_Font, new FontUIResource("Serif", Font.BOLD, 12) , ITEM_DetailText_Font, new FontUIResource("Serif", Font.PLAIN, 12) , ITEM_TextColor, null
, ITEM_MinimumSize, new DimensionUIResource(230, 45) , ITEM_MaximumSize, null // // Button settings (i.e. the close button) , ITEM_Button_Insets, new InsetsUIResource(1, 4, 1, 4) , ITEM_Button_Size, 20 , ITEM_Button_Border, new BorderUIResource(BorderFactory.createEmptyBorder()) }; } private SwingEventNotifierUI() { super(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\SwingEventNotifierUI.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_CM_AccessContainer[") .append(get_ID()).append("]"); return sb.toString(); } public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException { return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name) .getPO(getCM_AccessProfile_ID(), get_TrxName()); } /** Set Web Access Profile. @param CM_AccessProfile_ID Web Access Profile */ public void setCM_AccessProfile_ID (int CM_AccessProfile_ID) { if (CM_AccessProfile_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID)); } /** Get Web Access Profile. @return Web Access Profile */ public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_Container getCM_Container() throws RuntimeException { return (I_CM_Container)MTable.get(getCtx(), I_CM_Container.Table_Name) .getPO(getCM_Container_ID(), get_TrxName()); } /** Set Web Container. @param CM_Container_ID Web Container contains content like images, text etc. */
public void setCM_Container_ID (int CM_Container_ID) { if (CM_Container_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Container_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Container_ID, Integer.valueOf(CM_Container_ID)); } /** Get Web Container. @return Web Container contains content like images, text etc. */ public int getCM_Container_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_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_CM_AccessContainer.java
1
请完成以下Java代码
public void setPrintServiceName (java.lang.String PrintServiceName) { set_ValueNoCheck (COLUMNNAME_PrintServiceName, PrintServiceName); } @Override public java.lang.String getPrintServiceName() { return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName); } @Override public void setPrintServiceTray (java.lang.String PrintServiceTray) { set_ValueNoCheck (COLUMNNAME_PrintServiceTray, PrintServiceTray); } @Override public java.lang.String getPrintServiceTray() { return (java.lang.String)get_Value(COLUMNNAME_PrintServiceTray); } @Override public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); } @Override public void setS_Resource(org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } @Override public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } @Override public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions) { set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions)); } @Override public boolean isStatus_Print_Job_Instructions()
{ return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions); } @Override public void setTrayNumber (int TrayNumber) { set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber)); } @Override public int getTrayNumber() { return get_ValueAsInt(COLUMNNAME_TrayNumber); } @Override public void setWP_IsError (boolean WP_IsError) { set_ValueNoCheck (COLUMNNAME_WP_IsError, Boolean.valueOf(WP_IsError)); } @Override public boolean isWP_IsError() { return get_ValueAsBoolean(COLUMNNAME_WP_IsError); } @Override public void setWP_IsProcessed (boolean WP_IsProcessed) { set_ValueNoCheck (COLUMNNAME_WP_IsProcessed, Boolean.valueOf(WP_IsProcessed)); } @Override public boolean isWP_IsProcessed() { return get_ValueAsBoolean(COLUMNNAME_WP_IsProcessed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Order_MFGWarehouse_Report_PrintInfo_v.java
1
请完成以下Java代码
public boolean isCondition() { return (this.environment != null) && this.environment.acceptsProfiles(this.profiles); } @PluginBuilderFactory static Builder newBuilder() { return new Builder(); } /** * Standard Builder to create the Arbiter. */ static final class Builder implements org.apache.logging.log4j.core.util.Builder<SpringProfileArbiter> { private static final Logger statusLogger = StatusLogger.getLogger(); @PluginBuilderAttribute @SuppressWarnings("NullAway.Init") private String name; @PluginConfiguration @SuppressWarnings("NullAway.Init") private Configuration configuration; @PluginLoggerContext @SuppressWarnings("NullAway.Init") private LoggerContext loggerContext; private Builder() { } /** * Sets the profile name or expression.
* @param name the profile name or expression * @return this * @see Profiles#of(String...) */ public Builder setName(String name) { this.name = name; return this; } @Override public SpringProfileArbiter build() { Environment environment = Log4J2LoggingSystem.getEnvironment(this.loggerContext); if (environment == null) { statusLogger.debug("Creating Arbiter without a Spring Environment"); } String name = this.configuration.getStrSubstitutor().replace(this.name); String[] profiles = trimArrayElements(StringUtils.commaDelimitedListToStringArray(name)); return new SpringProfileArbiter(environment, profiles); } // The array has no nulls in it, but StringUtils.trimArrayElements return // @Nullable String[] @SuppressWarnings("NullAway") private String[] trimArrayElements(String[] array) { return StringUtils.trimArrayElements(array); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\SpringProfileArbiter.java
1
请完成以下Java代码
private void startQueueProcessors() { // task 04585: start queue processors only if we are running on the backend server. // =>why not always run them? // if we start it on clients without having a central monitoring-gathering point we never know what's going on // => it can all be solved, but as of now isn't if (!SpringContextHolder.instance.isSpringProfileActive(Profiles.PROFILE_App)) { return; } if (StringUtils.toBoolean(System.getProperty(SYSTEM_PROPERTY_ASYNC_DISABLE))) { logger.warn("\n----------------------------------------------------------------------------------------------" + "\n Avoid starting asynchronous queue processors because " + SYSTEM_PROPERTY_ASYNC_DISABLE + "=true." + "\n----------------------------------------------------------------------------------------------"); return; } final int initDelayMillis = getInitDelayMillis(); Services.get(IQueueProcessorExecutorService.class).init(initDelayMillis); } /** * Gets how many milliseconds to wait until to actually initialize the {@link IQueueProcessorExecutorService}. * <p> * Mainly we use this delay to make sure everything else is started before the queue processors will start to process. * * @return how many milliseconds to wait until to actually initialize the {@link IQueueProcessorExecutorService}. */ private int getInitDelayMillis() { // I will leave the default value of 3 minutes, which was the common time until #2894 return Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_ASYNC_INIT_DELAY_MILLIS, THREE_MINUTES); } @Override protected void registerInterceptors(@NonNull final IModelValidationEngine engine) { engine.addModelValidator(new C_Queue_PackageProcessor()); engine.addModelValidator(new C_Queue_Processor()); engine.addModelValidator(new de.metas.lock.model.validator.Main()); engine.addModelValidator(new C_Async_Batch()); } /** * Init the async queue processor service on user login. */ @Override
public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { if (!Ini.isSwingClient()) { return; } final int delayMillis = getInitDelayMillis(); Services.get(IQueueProcessorExecutorService.class).init(delayMillis); } /** * Destroy all queueud processors on user logout. */ @Override public void beforeLogout(final MFSession session) { if (!Ini.isSwingClient()) { return; } Services.get(IQueueProcessorExecutorService.class).removeAllQueueProcessors(); } @Override protected List<Topic> getAvailableUserNotificationsTopics() { return ImmutableList.of( Async_Constants.WORKPACKAGE_ERROR_USER_NOTIFICATIONS_TOPIC, DataImportService.USER_NOTIFICATIONS_TOPIC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\model\validator\Main.java
1
请完成以下Java代码
public Duration getTimeout() { return this.timeout; } public void setTimeout(Duration timeout) { this.timeout = timeout; } public List<String> getArguments() { return this.arguments; } } /** * Profiles properties. */ public static class Profiles { /** * Docker compose profiles that should be active. */ private Set<String> active = new LinkedHashSet<>(); public Set<String> getActive() { return this.active; } public void setActive(Set<String> active) { this.active = active; } } /** * Skip options. */ public static class Skip { /** * Whether to skip in tests. */ private boolean inTests = true; public boolean isInTests() { return this.inTests; } public void setInTests(boolean inTests) { this.inTests = inTests; } } /** * Readiness properties. */ public static class Readiness { /** * Wait strategy to use. */ private Wait wait = Wait.ALWAYS; /** * Timeout of the readiness checks. */ private Duration timeout = Duration.ofMinutes(2); /** * TCP properties. */ private final Tcp tcp = new Tcp(); public Wait getWait() { return this.wait; } public void setWait(Wait wait) { this.wait = wait; } public Duration getTimeout() { return this.timeout; }
public void setTimeout(Duration timeout) { this.timeout = timeout; } public Tcp getTcp() { return this.tcp; } /** * Readiness wait strategies. */ public enum Wait { /** * Always perform readiness checks. */ ALWAYS, /** * Never perform readiness checks. */ NEVER, /** * Only perform readiness checks if docker was started with lifecycle * management. */ ONLY_IF_STARTED } /** * TCP properties. */ public static class Tcp { /** * Timeout for connections. */ private Duration connectTimeout = Duration.ofMillis(200); /** * Timeout for reads. */ private Duration readTimeout = Duration.ofMillis(200); public Duration getConnectTimeout() { return this.connectTimeout; } public void setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; } public Duration getReadTimeout() { return this.readTimeout; } public void setReadTimeout(Duration readTimeout) { this.readTimeout = readTimeout; } } } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\lifecycle\DockerComposeProperties.java
1
请完成以下Java代码
public String getSameSiteCookieValue() { return sameSiteCookieValue; } public void setSameSiteCookieValue(String sameSiteCookieValue) { this.sameSiteCookieValue = sameSiteCookieValue; } public String getCookieName() { return cookieName; } public void setCookieName(String cookieName) { this.cookieName = cookieName; } public Map<String, String> getInitParams() { Map<String, String> initParams = new HashMap<>(); if (StringUtils.isNotBlank(targetOrigin)) { initParams.put("targetOrigin", targetOrigin); } if (denyStatus != null) { initParams.put("denyStatus", denyStatus.toString()); } if (StringUtils.isNotBlank(randomClass)) { initParams.put("randomClass", randomClass); } if (!entryPoints.isEmpty()) { initParams.put("entryPoints", StringUtils.join(entryPoints, ",")); } if (enableSecureCookie) { // only add param if it's true; default is false initParams.put("enableSecureCookie", String.valueOf(enableSecureCookie)); } if (!enableSameSiteCookie) { // only add param if it's false; default is true initParams.put("enableSameSiteCookie", String.valueOf(enableSameSiteCookie)); } if (StringUtils.isNotBlank(sameSiteCookieOption)) { initParams.put("sameSiteCookieOption", sameSiteCookieOption); } if (StringUtils.isNotBlank(sameSiteCookieValue)) { initParams.put("sameSiteCookieValue", sameSiteCookieValue);
} if (StringUtils.isNotBlank(cookieName)) { initParams.put("cookieName", cookieName); } return initParams; } @Override public String toString() { return joinOn(this.getClass()) .add("targetOrigin=" + targetOrigin) .add("denyStatus='" + denyStatus + '\'') .add("randomClass='" + randomClass + '\'') .add("entryPoints='" + entryPoints + '\'') .add("enableSecureCookie='" + enableSecureCookie + '\'') .add("enableSameSiteCookie='" + enableSameSiteCookie + '\'') .add("sameSiteCookieOption='" + sameSiteCookieOption + '\'') .add("sameSiteCookieValue='" + sameSiteCookieValue + '\'') .add("cookieName='" + cookieName + '\'') .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\CsrfProperties.java
1
请在Spring Boot框架中完成以下Java代码
protected boolean isAsyncExecutorActive() { return isExecutorActive(jobServiceConfiguration.getAsyncExecutor()); } protected boolean isAsyncExecutorRemainingCapacitySufficient(int neededCapacity) { return getAsyncExecutor().isActive() && getAsyncExecutor().getTaskExecutor().getRemainingCapacity() >= neededCapacity; } protected boolean isAsyncHistoryExecutorActive() { return isExecutorActive(jobServiceConfiguration.getAsyncHistoryExecutor()); } protected boolean isExecutorActive(AsyncExecutor asyncExecutor) { return asyncExecutor != null && asyncExecutor.isActive(); } protected CommandContext getCommandContext() { return Context.getCommandContext(); } protected AsyncExecutor getAsyncExecutor() {
return jobServiceConfiguration.getAsyncExecutor(); } protected AsyncExecutor getAsyncHistoryExecutor() { return jobServiceConfiguration.getAsyncHistoryExecutor(); } protected void callJobProcessors(JobProcessorContext.Phase processorType, AbstractJobEntity abstractJobEntity) { JobProcessorUtil.callJobProcessors(jobServiceConfiguration, processorType, abstractJobEntity); } protected void callHistoryJobProcessors(HistoryJobProcessorContext.Phase processorType, HistoryJobEntity historyJobEntity) { JobProcessorUtil.callHistoryJobProcessors(jobServiceConfiguration, processorType, historyJobEntity); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\DefaultJobManager.java
2
请完成以下Java代码
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; }
public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public Integer getReadSum() { return readSum; } public void setReadSum(Integer readSum) { this.readSum = readSum; } }
repos\springBoot-master\springboot-dynamicDataSource\src\main\java\cn\abel\bean\News.java
1
请完成以下Java代码
private ProductsProposalRowsLoader createRowsLoaderFromOrderId(@NonNull final OrderId orderId) { final Order order = orderProductProposalsService.getOrderById(orderId); final CampaignPriceProvider campaignPriceProvider = createCampaignPriceProvider(order); return ProductsProposalRowsLoader.builder() .lookupDataSourceFactory(lookupDataSourceFactory) .bpartnerProductStatsService(bpartnerProductStatsService) .campaignPriceProvider(campaignPriceProvider) .orderProductProposalsService(orderProductProposalsService) // .priceListVersionId(order.getPriceListVersionId()) .order(order) .bpartnerId(order.getBpartnerId()) .soTrx(order.getSoTrx()) .currencyId(order.getCurrency().getId()) // .build(); } private CampaignPriceProvider createCampaignPriceProvider(@NonNull final Order order) { if (!order.getSoTrx().isSales()) { return CampaignPriceProviders.none(); } if (order.getCountryId() == null) { return CampaignPriceProviders.none(); } if (!bpartnersRepo.isCampaignPriceAllowed(order.getBpartnerId())) { return CampaignPriceProviders.none(); } final BPGroupId bpGroupId = bpartnersRepo.getBPGroupIdByBPartnerId(order.getBpartnerId()); return CampaignPriceProviders.standard() .campaignPriceService(campaignPriceService) .bpartnerId(order.getBpartnerId()) .bpGroupId(bpGroupId) .pricingSystemId(order.getPricingSystemId()) .countryId(order.getCountryId()) .currencyId(order.getCurrency().getId()) .date(TimeUtil.asLocalDate(order.getDatePromised())) .build(); } @Override protected List<RelatedProcessDescriptor> getRelatedProcessDescriptors()
{ return ImmutableList.of( createProcessDescriptor(WEBUI_ProductsProposal_SaveProductPriceToCurrentPriceListVersion.class), createProcessDescriptor(WEBUI_ProductsProposal_ShowProductsToAddFromBasePriceList.class), createProcessDescriptor(WEBUI_ProductsProposal_ShowProductsSoldToOtherCustomers.class), createProcessDescriptor(WEBUI_ProductsProposal_Delete.class)); } @Override protected void beforeViewClose(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { if (ViewCloseAction.DONE.equals(closeAction)) { final ProductsProposalView view = getById(viewId); if (view.getOrderId() != null) { createOrderLines(view); } } } private void createOrderLines(final ProductsProposalView view) { OrderLinesFromProductProposalsProducer.builder() .orderId(view.getOrderId().get()) .rows(view.getAllRows()) .build() .produce(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\OrderProductsProposalViewFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class ViewConfiguration implements InitializingBean { private static final Logger logger = LogManager.getLogger(ViewConfiguration.class); private static final String SYSCONFIG_ClearViewSelectionsRateInSeconds = "metasfresh.view.clearViewSelectionsRateInSeconds"; @Override public void afterPropertiesSet() { final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); final int clearViewSelectionsRateInSeconds = sysConfigBL.getIntValue(SYSCONFIG_ClearViewSelectionsRateInSeconds, 1800); if (clearViewSelectionsRateInSeconds > 0) { final ScheduledExecutorService scheduledExecutor = viewMaintenanceScheduledExecutorService(); scheduledExecutor.scheduleAtFixedRate( SqlViewSelectionToDeleteHelper::deleteScheduledSelectionsNoFail, // command, don't fail because on failure the task won't be re-scheduled, so it's game over clearViewSelectionsRateInSeconds, // initialDelay clearViewSelectionsRateInSeconds, // period TimeUnit.SECONDS // timeUnit ); logger.info("Clearing view selections each {} seconds (see {} sysconfig)", clearViewSelectionsRateInSeconds, SYSCONFIG_ClearViewSelectionsRateInSeconds);
} else { logger.info("Clearing view selections disabled (see {} sysconfig)", SYSCONFIG_ClearViewSelectionsRateInSeconds); } } private ScheduledExecutorService viewMaintenanceScheduledExecutorService() { return Executors.newScheduledThreadPool( 1, // corePoolSize CustomizableThreadFactory.builder() .setDaemon(true) .setThreadNamePrefix("webui-views-maintenance") .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewConfiguration.java
2
请完成以下Java代码
public boolean doCatch(final Throwable e) { final String errmsg = "@Error@: @C_Payment_ID@ " + payment.getDocumentNo() + ": " + e.getLocalizedMessage(); addLog(errmsg); log.error(errmsg, e); return true; // rollback } }); } private Iterator<I_C_Payment> retrievePayments() { final Stopwatch stopwatch = Stopwatch.createStarted(); // // Create the selection which we might need to update final IQueryBuilder<I_C_Payment> queryBuilder = queryBL .createQueryBuilder(I_C_Payment.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Payment.COLUMNNAME_AD_Client_ID, getClientId()) .addEqualsFilter(I_C_Payment.COLUMNNAME_IsAllocated, false); if (!getProcessInfo().isInvokedByScheduler()) { // user selection..if any final IQueryFilter<I_C_Payment> userSelectionFilter = getProcessInfo().getQueryFilterOrElseFalse(); queryBuilder.filter(userSelectionFilter); } if (p_SOTrx != null) {
queryBuilder.addEqualsFilter(I_C_Payment.COLUMNNAME_IsReceipt, p_SOTrx.toBoolean()); } if (p_PaymentDateFrom != null) { queryBuilder.addCompareFilter(I_C_Payment.COLUMNNAME_DateTrx, Operator.GREATER_OR_EQUAL, p_PaymentDateFrom); } if (p_PaymentDateTo != null) { queryBuilder.addCompareFilter(I_C_Payment.COLUMNNAME_DateTrx, Operator.LESS_OR_EQUAL, p_PaymentDateTo); } final IQuery<I_C_Payment> query = queryBuilder .orderBy(I_C_Payment.COLUMNNAME_C_Payment_ID) .create(); addLog("Using query: " + query); final int count = query.count(); if (count > 0) { final Iterator<I_C_Payment> iterator = query.iterate(I_C_Payment.class); addLog("Found " + count + " payments to evaluate. Took " + stopwatch); return iterator; } else { addLog("No payments found. Took " + stopwatch); return Collections.emptyIterator(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\payment\process\C_Payment_MassWriteOff.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; VariableInstanceEntity other = (VariableInstanceEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } /** * @param isTransient * <code>true</code>, if the variable is not stored in the data base. * Default is <code>false</code>. */ public void setTransient(boolean isTransient) { this.isTransient = isTransient; } /** * @return <code>true</code>, if the variable is transient. A transient * variable is not stored in the data base. */ public boolean isTransient() { return isTransient; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<>();
if (processInstanceId != null){ referenceIdAndClass.put(processInstanceId, ExecutionEntity.class); } if (executionId != null){ referenceIdAndClass.put(executionId, ExecutionEntity.class); } if (caseInstanceId != null){ referenceIdAndClass.put(caseInstanceId, CaseExecutionEntity.class); } if (caseExecutionId != null){ referenceIdAndClass.put(caseExecutionId, CaseExecutionEntity.class); } if (getByteArrayValueId() != null){ referenceIdAndClass.put(getByteArrayValueId(), ByteArrayEntity.class); } return referenceIdAndClass; } /** * * @return <code>true</code> <code>processDefinitionId</code> is introduced in 7.13, * the check is used to created missing history at {@link LegacyBehavior#createMissingHistoricVariables(org.camunda.bpm.engine.impl.pvm.runtime.PvmExecutionImpl) LegacyBehavior#createMissingHistoricVariables} */ public boolean wasCreatedBefore713() { return this.getProcessDefinitionId() == null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceEntity.java
1
请完成以下Java代码
public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } @Override public boolean isTree() { Object oo = get_Value(COLUMNNAME_IsTree); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public void setIsTree(boolean IsTree) { set_Value (COLUMNNAME_IsTree, Boolean.valueOf(IsTree)); } @Override public boolean isParameterNextLine() { Object oo = get_Value(COLUMNNAME_IsParameterNextLine); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public void setIsParameterNextLine(boolean IsParameterNextLine) { set_Value (COLUMNNAME_IsParameterNextLine, Boolean.valueOf(IsParameterNextLine)); } public void setParameterSeqNo (int ParameterSeqNo) { set_Value (COLUMNNAME_ParameterSeqNo, Integer.valueOf(ParameterSeqNo)); } public int getParameterSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_ParameterSeqNo); if (ii == null) return 0; return ii.intValue(); } public void setParameterDisplayLogic (String ParameterDisplayLogic) { set_Value (COLUMNNAME_ParameterDisplayLogic, ParameterDisplayLogic); } public String getParameterDisplayLogic () { return (String)get_Value(COLUMNNAME_ParameterDisplayLogic); } public void setColumnName (String ColumnName) { set_Value (COLUMNNAME_ColumnName, ColumnName);
} public String getColumnName () { return (String)get_Value(COLUMNNAME_ColumnName); } /** Set Query Criteria Function. @param QueryCriteriaFunction column used for adding a sql function to query criteria */ public void setQueryCriteriaFunction (String QueryCriteriaFunction) { set_Value (COLUMNNAME_QueryCriteriaFunction, QueryCriteriaFunction); } /** Get Query Criteria Function. @return column used for adding a sql function to query criteria */ public String getQueryCriteriaFunction () { return (String)get_Value(COLUMNNAME_QueryCriteriaFunction); } @Override public void setDefaultValue (String DefaultValue) { set_Value (COLUMNNAME_DefaultValue, DefaultValue); } @Override public String getDefaultValue () { return (String)get_Value(COLUMNNAME_DefaultValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoColumn.java
1
请完成以下Java代码
public void rollbackAndCloseActiveTrx(final String trxName) { final ITrxManager trxManager = getTrxManager(); if (trxManager.isNull(trxName)) { throw new IllegalArgumentException("Only not null transactions are allowed: " + trxName); } final ITrx trx = trxManager.getTrx(trxName); if (trxManager.isNull(trx)) { // shall not happen because getTrx is already throwning an exception throw new IllegalArgumentException("No transaction was found for: " + trxName); } boolean rollbackOk = false; try { rollbackOk = trx.rollback(true); } catch (SQLException e) { throw new RuntimeException("Could not rollback '" + trx + "' because: " + e.getLocalizedMessage(), e); }
if (!rollbackOk) { throw new RuntimeException("Could not rollback '" + trx + "' for unknown reason"); } } @Override public void setDebugConnectionBackendId(boolean debugConnectionBackendId) { getTrxManager().setDebugConnectionBackendId(debugConnectionBackendId); } @Override public boolean isDebugConnectionBackendId() { return getTrxManager().isDebugConnectionBackendId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\jmx\JMXTrxManager.java
1
请完成以下Java代码
public ModelApiResponse type(String type) { this.type = type; return this; } /** * Get type * @return type **/ @ApiModelProperty(value = "") public String getType() { return type; } public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { this.message = message; return this; } /** * Get message * @return message **/ @ApiModelProperty(value = "") public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; return Objects.equals(this.code, _apiResponse.code) && Objects.equals(this.type, _apiResponse.type) && Objects.equals(this.message, _apiResponse.message); } @Override public int hashCode() { return Objects.hash(code, type, message); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ModelApiResponse {\n"); sb.append(" code: ").append(toIndentedString(code)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" message: ").append(toIndentedString(message)).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\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\ModelApiResponse.java
1
请在Spring Boot框架中完成以下Java代码
public void handleComponentLifecycleEvent(ComponentLifecycleMsg event) { if (event.getEntityId().getEntityType() == EntityType.TENANT) { if (event.getEvent() == ComponentLifecycleEvent.DELETED) { List<QueueKey> toRemove = consumers.keySet().stream() .filter(queueKey -> queueKey.getTenantId().equals(event.getTenantId())) .toList(); toRemove.forEach(queueKey -> { removeConsumer(queueKey).ifPresent(consumer -> consumer.delete(false)); }); } } } private Optional<TbRuleEngineQueueConsumerManager> getConsumer(QueueKey queueKey) { return Optional.ofNullable(consumers.get(queueKey)); } private TbRuleEngineQueueConsumerManager createConsumer(QueueKey queueKey, Queue queue) { var consumer = TbRuleEngineQueueConsumerManager.create() .ctx(ctx) .queueKey(queueKey) .consumerExecutor(consumersExecutor)
.scheduler(scheduler) .taskExecutor(mgmtExecutor) .build(); consumers.put(queueKey, consumer); consumer.init(queue); return consumer; } private Optional<TbRuleEngineQueueConsumerManager> removeConsumer(QueueKey queueKey) { return Optional.ofNullable(consumers.remove(queueKey)); } @Scheduled(fixedDelayString = "${queue.rule-engine.stats.print-interval-ms}") public void printStats() { if (ctx.isStatsEnabled()) { long ts = System.currentTimeMillis(); consumers.values().forEach(manager -> manager.printStats(ts)); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\DefaultTbRuleEngineConsumerService.java
2
请完成以下Java代码
public void onEvent(ActivitiEvent event) { if (isValidEvent(event)) { getDelegateInstance().onEvent(event); } } @Override public boolean isFailOnException() { if (delegateInstance != null) { return delegateInstance.isFailOnException(); } return failOnException; } protected ActivitiEventListener getDelegateInstance() {
if (delegateInstance == null) { Object instance = ReflectUtil.instantiate(className); if (instance instanceof ActivitiEventListener) { delegateInstance = (ActivitiEventListener) instance; } else { // Force failing of the listener invocation, since the delegate // cannot be created failOnException = true; throw new ActivitiIllegalArgumentException( "Class " + className + " does not implement " + ActivitiEventListener.class.getName() ); } } return delegateInstance; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\DelegateActivitiEventListener.java
1
请完成以下Java代码
public boolean isAckAfterHandle() { return this.ackAfterHandle; } @Override public void setAckAfterHandle(boolean ackAfterHandle) { this.ackAfterHandle = ackAfterHandle; } @Override public boolean handleOne(Exception thrownException, ConsumerRecord<?, ?> record, Consumer<?, ?> consumer, MessageListenerContainer container) { LOGGER.error(thrownException, () -> "Error occurred while processing: " + KafkaUtils.format(record)); return true; } @Override public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) {
StringBuilder message = new StringBuilder("Error occurred while processing:\n"); for (ConsumerRecord<?, ?> record : data) { message.append(KafkaUtils.format(record)).append('\n'); } LOGGER.error(thrownException, () -> message.substring(0, message.length() - 1)); } @Override public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer, MessageListenerContainer container, boolean batchListener) { LOGGER.error(thrownException, () -> "Error occurred while not processing records"); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonLoggingErrorHandler.java
1
请在Spring Boot框架中完成以下Java代码
public CalculatedFieldType getType() { return CalculatedFieldType.PROPAGATION; } @Override public void validate() { baseCalculatedFieldRestriction(); propagationRestriction(); if (!applyExpressionToResolvedArguments) { arguments.forEach((name, argument) -> { if (!currentEntitySource(argument)) { throw new IllegalArgumentException("Arguments in 'Arguments only' propagation mode support only the 'Current entity' source entity type!"); } if (argument.getRefEntityKey() == null) { throw new IllegalArgumentException("Argument: '" + name + "' doesn't have reference entity key configured!"); } if (argument.getRefEntityKey().getType() == ArgumentType.TS_ROLLING) { throw new IllegalArgumentException("Argument type: 'Time series rolling' detected for argument: '" + name + "'. " + "Only 'Attribute' or 'Latest telemetry' arguments are allowed for 'Arguments only' propagation mode!"); } }); } else { boolean noneMatchCurrentEntitySource = arguments.entrySet() .stream() .noneMatch(entry -> currentEntitySource(entry.getValue())); if (noneMatchCurrentEntitySource) { throw new IllegalArgumentException("At least one argument must be configured with the 'Current entity' " + "source entity type for 'Expression result' propagation mode!"); } if (StringUtils.isBlank(expression)) { throw new IllegalArgumentException("Expression must be specified for 'Expression result' propagation mode!");
} } } public Argument toPropagationArgument() { var refDynamicSourceConfiguration = new RelationPathQueryDynamicSourceConfiguration(); refDynamicSourceConfiguration.setLevels(List.of(relation)); var propagationArgument = new Argument(); propagationArgument.setRefDynamicSourceConfiguration(refDynamicSourceConfiguration); return propagationArgument; } private void propagationRestriction() { if (arguments.entrySet().stream().anyMatch(entry -> entry.getKey().equals(PROPAGATION_CONFIG_ARGUMENT))) { throw new IllegalArgumentException("Argument name '" + PROPAGATION_CONFIG_ARGUMENT + "' is reserved and cannot be used."); } } private boolean currentEntitySource(Argument argument) { return argument.getRefEntityId() == null && argument.getRefDynamicSourceConfiguration() == null; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\PropagationCalculatedFieldConfiguration.java
2
请完成以下Java代码
public void setDLM_Partition_ID(final int DLM_Partition_ID) { if (DLM_Partition_ID < 1) { set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, null); } else { set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, Integer.valueOf(DLM_Partition_ID)); } } /** * Get Partition. * * @return Partition */ @Override public int getDLM_Partition_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Partitionierungswarteschlange. * * @param DLM_Partition_Workqueue_ID Partitionierungswarteschlange */ @Override public void setDLM_Partition_Workqueue_ID(final int DLM_Partition_Workqueue_ID) { if (DLM_Partition_Workqueue_ID < 1) { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Workqueue_ID, null); } else { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Workqueue_ID, Integer.valueOf(DLM_Partition_Workqueue_ID)); } } /** * Get Partitionierungswarteschlange. * * @return Partitionierungswarteschlange */ @Override public int getDLM_Partition_Workqueue_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Workqueue_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Datensatz-ID. * * @param Record_ID * Direct internal record ID */ @Override public void setRecord_ID(final int Record_ID) { if (Record_ID < 0) { set_Value(COLUMNNAME_Record_ID, null); }
else { set_Value(COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } } /** * Get Datensatz-ID. * * @return Direct internal record ID */ @Override public int getRecord_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Name der DB-Tabelle. * * @param TableName Name der DB-Tabelle */ @Override public void setTableName(final java.lang.String TableName) { throw new IllegalArgumentException("TableName is virtual column"); } /** * Get Name der DB-Tabelle. * * @return Name der DB-Tabelle */ @Override public java.lang.String getTableName() { return (java.lang.String)get_Value(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Workqueue.java
1
请完成以下Java代码
Set<String> getRouteEnabledHeaders() { return routeEnabledHeaders; } /** * bind the route specific/opt-out header names to disable, in lower case. */ void setDisable(Set<String> disable) { if (disable != null) { this.routeFilterConfigProvided = true; this.routeDisabledHeaders = disable.stream() .map(String::toLowerCase) .collect(Collectors.toUnmodifiableSet()); } } /** * @return the route specific/opt-out header names to disable, in lower case */ Set<String> getRouteDisabledHeaders() { return routeDisabledHeaders; } /** * @return the route specific/opt-out permission policies. */ protected @Nullable String getRoutePermissionsPolicyHeaderValue() { return routePermissionsPolicyHeaderValue; } /**
* bind the route specific/opt-out permissions policy. */ void setPermissionsPolicy(@Nullable String permissionsPolicy) { this.routeFilterConfigProvided = true; this.routePermissionsPolicyHeaderValue = permissionsPolicy; } /** * @return flag whether route specific arguments were bound. */ boolean isRouteFilterConfigProvided() { return routeFilterConfigProvided; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SecureHeadersGatewayFilterFactory.java
1
请完成以下Java代码
public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public void setProcessDefinitionTenantId(String processDefinitionTenantId) { this.processDefinitionTenantId = processDefinitionTenantId; } public void setProcessDefinitionWithoutTenantId(boolean processDefinitionWithoutTenantId) { this.processDefinitionWithoutTenantId = processDefinitionWithoutTenantId; } @Override public void updateSuspensionState(ProcessEngine engine) { int params = (jobId != null ? 1 : 0) + (jobDefinitionId != null ? 1 : 0) + (processInstanceId != null ? 1 : 0) + (processDefinitionId != null ? 1 : 0) + (processDefinitionKey != null ? 1 : 0); if (params > 1) { String message = "Only one of jobId, jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; throw new InvalidRequestException(Status.BAD_REQUEST, message); } else if(params == 0) { String message = "Either jobId, jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; throw new InvalidRequestException(Status.BAD_REQUEST, message); } UpdateJobSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateBuilder(engine); if(getSuspended()) { updateSuspensionStateBuilder.suspend();
} else { updateSuspensionStateBuilder.activate(); } } protected UpdateJobSuspensionStateBuilder createUpdateSuspensionStateBuilder(ProcessEngine engine) { UpdateJobSuspensionStateSelectBuilder selectBuilder = engine.getManagementService().updateJobSuspensionState(); if (jobId != null) { return selectBuilder.byJobId(jobId); } else if (jobDefinitionId != null) { return selectBuilder.byJobDefinitionId(jobDefinitionId); } else if (processInstanceId != null) { return selectBuilder.byProcessInstanceId(processInstanceId); } else if (processDefinitionId != null) { return selectBuilder.byProcessDefinitionId(processDefinitionId); } else { UpdateJobSuspensionStateTenantBuilder tenantBuilder = selectBuilder.byProcessDefinitionKey(processDefinitionKey); if (processDefinitionTenantId != null) { tenantBuilder.processDefinitionTenantId(processDefinitionTenantId); } else if (processDefinitionWithoutTenantId) { tenantBuilder.processDefinitionWithoutTenantId(); } return tenantBuilder; } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\JobSuspensionStateDto.java
1
请完成以下Java代码
public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.matcher = requestMatcher; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!this.matcher.matches(request)) { filterChain.doFilter(request, response); return; } Supplier<SecurityContext> context = this.securityContextHolderStrategy.getDeferredContext(); Supplier<Authentication> authentication = () -> context.get().getAuthentication(); AuthorizationResult result = this.authorization.authorize(authentication, request); if (result == null || !result.isGranted()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } PublicKeyCredentialCreationOptions options = this.rpOperations.createPublicKeyCredentialCreationOptions( new ImmutablePublicKeyCredentialCreationOptionsRequest(authentication.get())); this.repository.save(request, response, options); response.setStatus(HttpServletResponse.SC_OK); response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.converter.write(options, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response)); } /**
* Sets the {@link PublicKeyCredentialCreationOptionsRepository} to use. The default * is {@link HttpSessionPublicKeyCredentialCreationOptionsRepository}. * @param creationOptionsRepository the * {@link PublicKeyCredentialCreationOptionsRepository} to use. Cannot be null. */ public void setCreationOptionsRepository(PublicKeyCredentialCreationOptionsRepository creationOptionsRepository) { Assert.notNull(creationOptionsRepository, "creationOptionsRepository cannot be null"); this.repository = creationOptionsRepository; } /** * Set the {@link HttpMessageConverter} to read the * {@link WebAuthnRegistrationFilter.WebAuthnRegistrationRequest} and write the * response. The default is {@link JacksonJsonHttpMessageConverter}. * @param converter the {@link HttpMessageConverter} to use. Cannot be null. */ public void setConverter(HttpMessageConverter<Object> converter) { Assert.notNull(converter, "converter cannot be null"); this.converter = converter; } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\registration\PublicKeyCredentialCreationOptionsFilter.java
1
请完成以下Java代码
public class HttpExchangesWebFilter implements WebFilter, Ordered { private static final Object NONE = new Object(); // Not LOWEST_PRECEDENCE, but near the end, so it has a good chance of catching all // enriched headers, but users can add stuff after this if they want to private int order = Ordered.LOWEST_PRECEDENCE - 10; private final HttpExchangeRepository repository; private final Set<Include> includes; /** * Create a new {@link HttpExchangesWebFilter} instance. * @param repository the repository used to record events * @param includes the include options */ public HttpExchangesWebFilter(HttpExchangeRepository repository, Set<Include> includes) { this.repository = repository; this.includes = includes; } @Override public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { Mono<?> principal = exchange.getPrincipal().cast(Object.class).defaultIfEmpty(NONE); Mono<Object> session = exchange.getSession().cast(Object.class).defaultIfEmpty(NONE); return Mono.zip(PrincipalAndSession::new, principal, session) .flatMap((principalAndSession) -> filter(exchange, chain, principalAndSession)); } private Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain, PrincipalAndSession principalAndSession) { return Mono.fromRunnable(() -> addExchangeOnCommit(exchange, principalAndSession)).and(chain.filter(exchange)); } private void addExchangeOnCommit(ServerWebExchange exchange, PrincipalAndSession principalAndSession) { RecordableServerHttpRequest sourceRequest = new RecordableServerHttpRequest(exchange.getRequest()); HttpExchange.Started startedHttpExchange = HttpExchange.start(sourceRequest); exchange.getResponse().beforeCommit(() -> { RecordableServerHttpResponse sourceResponse = new RecordableServerHttpResponse(exchange.getResponse()); HttpExchange finishedExchange = startedHttpExchange.finish(sourceResponse, principalAndSession::getPrincipal, principalAndSession::getSessionId, this.includes); this.repository.add(finishedExchange); return Mono.empty();
}); } /** * A {@link Principal} and {@link WebSession}. */ private static class PrincipalAndSession { private final @Nullable Principal principal; private final @Nullable WebSession session; PrincipalAndSession(Object[] zipped) { this.principal = (zipped[0] != NONE) ? (Principal) zipped[0] : null; this.session = (zipped[1] != NONE) ? (WebSession) zipped[1] : null; } @Nullable Principal getPrincipal() { return this.principal; } @Nullable String getSessionId() { return (this.session != null && this.session.isStarted()) ? this.session.getId() : null; } } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\web\exchanges\HttpExchangesWebFilter.java
1
请完成以下Java代码
public PageData<WidgetTypeId> findAllWidgetTypesIds(PageLink pageLink) { return widgetTypeDao.findAllWidgetTypesIds(pageLink); } @Override public void deleteByTenantId(TenantId tenantId) { deleteWidgetTypesByTenantId(tenantId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findWidgetTypeById(tenantId, new WidgetTypeId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(widgetTypeDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.WIDGET_TYPE; } private final PaginatedRemover<TenantId, WidgetTypeInfo> tenantWidgetTypeRemover = new PaginatedRemover<>() { @Override protected PageData<WidgetTypeInfo> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return widgetTypeDao.findTenantWidgetTypesByTenantId( WidgetTypeFilter.builder() .tenantId(id) .fullSearch(false) .deprecatedFilter(DeprecatedFilter.ALL) .widgetTypes(null).build(), pageLink); } @Override protected void removeEntity(TenantId tenantId, WidgetTypeInfo entity) { deleteWidgetType(tenantId, new WidgetTypeId(entity.getUuidId()));
} }; private final PaginatedRemover<WidgetsBundleId, WidgetTypeInfo> bundleWidgetTypesRemover = new PaginatedRemover<>() { @Override protected PageData<WidgetTypeInfo> findEntities(TenantId tenantId, WidgetsBundleId widgetsBundleId, PageLink pageLink) { return findWidgetTypesInfosByWidgetsBundleId(tenantId, widgetsBundleId, false, DeprecatedFilter.ALL, null, pageLink); } @Override protected void removeEntity(TenantId tenantId, WidgetTypeInfo widgetTypeInfo) { deleteWidgetType(tenantId, widgetTypeInfo.getId()); } }; }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\widget\WidgetTypeServiceImpl.java
1
请完成以下Java代码
protected Cache createCache(Class<? extends Cache> cacheClass, Map<String, Object> cacheConfiguration) { Cache cache = createCacheInstance(cacheClass); configureCache(cache, cacheConfiguration); return cache; } protected void configureCache(Cache cache, Map<String, Object> cacheConfiguration) { for (Map.Entry<String, Object> configuration : cacheConfiguration.entrySet()) { configureCache(cache, configuration.getKey(), configuration.getValue()); } } protected Cache createCacheInstance(Class<? extends Cache> cacheClass) { try { return ReflectUtil.instantiate(cacheClass); } catch (ProcessEngineException e) { throw new HalRelationCacheConfigurationException("Unable to instantiate cache class " + cacheClass.getName(), e); } } protected void configureCache(Cache cache, String property, Object value) { Method setter; try { setter = ReflectUtil.getSingleSetter(property, cache.getClass()); } catch (ProcessEngineException e) { throw new HalRelationCacheConfigurationException("Unable to find setter for property " + property, e); }
if (setter == null) { throw new HalRelationCacheConfigurationException("Unable to find setter for property " + property); } try { setter.invoke(cache, value); } catch (IllegalAccessException e) { throw new HalRelationCacheConfigurationException("Unable to access setter for property " + property); } catch (InvocationTargetException e) { throw new HalRelationCacheConfigurationException("Unable to invoke setter for property " + property); } } protected void registerCache(Class<?> halResourceClass, Cache cache) { Hal.getInstance().registerHalRelationCache(halResourceClass, cache); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\HalRelationCacheBootstrap.java
1
请在Spring Boot框架中完成以下Java代码
public class BatchPartCollectionResource { @Autowired protected RestResponseFactory restResponseFactory; @Autowired protected ManagementService managementService; @Autowired(required=false) protected BpmnRestApiInterceptor restApiInterceptor; @ApiOperation(value = "List batch parts", tags = { "Batches" }, nickname = "listBatchesPart") @ApiImplicitParams({ @ApiImplicitParam(name = "status", dataType = "string", value = "Only return batch parts for the given status", paramType = "query") }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the requested batch parts were returned."), @ApiResponse(code = 400, message = "Indicates an illegal value has been used in a url query parameter. Status description contains additional details about the error.") }) @GetMapping(value = "/management/batches/{batchId}/batch-parts", produces = "application/json") public List<BatchPartResponse> getBatches(@PathVariable String batchId, @ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams) { Batch batch = managementService.createBatchQuery().batchId(batchId).singleResult(); if (batch == null) { throw new FlowableObjectNotFoundException("No batch found for id " + batchId); }
if (restApiInterceptor != null) { restApiInterceptor.accessBatchPartInfoOfBatch(batch); } List<BatchPart> batchParts = null; if (allRequestParams.containsKey("status")) { batchParts = managementService.findBatchPartsByBatchIdAndStatus(batchId, allRequestParams.get("status")); } else { batchParts = managementService.findBatchPartsByBatchId(batchId); } return restResponseFactory.createBatchPartResponse(batchParts); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\BatchPartCollectionResource.java
2
请完成以下Java代码
public String getExecutable() { String os = System.getProperty("os.name").toLowerCase(); String dirPath = dir.getAbsolutePath(); String base = dirPath+FILESEPARATOR+script; if (exists(base)) { return base; } if (os.indexOf("windows")!=-1) { if (exists(base+".exe")) { return base+".exe"; } if (exists(base+".bat")) { return base+".bat"; } } if (os.indexOf("linux")!=-1 || os.indexOf("mac")!=-1) { if (exists(base+".sh")) { return base+".sh"; } } throw new BuildException("couldn't find executable for script "+base); } public boolean exists(String path) { File file = new File(path); return (file.exists()); } public void setDir(File dir) {
this.dir = dir; } public void setScript(String script) { this.script = script; } public void setMsg(String msg) { this.msg = msg; } public void setArgs(String args) { this.args = args; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ant\LaunchTask.java
1
请完成以下Java代码
public void setR_Request_ID (int R_Request_ID) { if (R_Request_ID < 1) set_Value (COLUMNNAME_R_Request_ID, null); else set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID)); } /** Get Aufgabe. @return Request from a Business Partner or Prospect */ @Override public int getR_Request_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Betreff. @param Subject Mail Betreff */ @Override public void setSubject (java.lang.String Subject) { set_Value (COLUMNNAME_Subject, Subject); } /** Get Betreff. @return Mail Betreff */ @Override public java.lang.String getSubject () { return (java.lang.String)get_Value(COLUMNNAME_Subject); }
@Override public org.compiere.model.I_AD_User getTo_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setTo_User(org.compiere.model.I_AD_User To_User) { set_ValueFromPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class, To_User); } /** Set To User. @param To_User_ID To User */ @Override public void setTo_User_ID (int To_User_ID) { if (To_User_ID < 1) set_Value (COLUMNNAME_To_User_ID, null); else set_Value (COLUMNNAME_To_User_ID, Integer.valueOf(To_User_ID)); } /** Get To User. @return To User */ @Override public int getTo_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_To_User_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_C_Mail.java
1
请完成以下Java代码
public void delete(String s) { } @Override public void delete(int i) { } @Override public Scriptable getPrototype() { return null; } @Override public void setPrototype(Scriptable scriptable) { } @Override public Scriptable getParentScope() { return null; } @Override
public void setParentScope(Scriptable scriptable) { } @Override public Object[] getIds() { return null; } @Override public Object getDefaultValue(Class<?> aClass) { return null; } @Override public boolean hasInstance(Scriptable scriptable) { return false; } }
repos\flowable-engine-main\modules\flowable-secure-javascript\src\main\java\org\flowable\scripting\secure\impl\SecureScriptScope.java
1
请完成以下Java代码
public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public boolean isHasExistingInstancesForUniqueCorrelation() { return hasExistingInstancesForUniqueCorrelation; }
public void setHasExistingInstancesForUniqueCorrelation(boolean hasExistingInstancesForUniqueCorrelation) { this.hasExistingInstancesForUniqueCorrelation = hasExistingInstancesForUniqueCorrelation; } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("eventSubscriptionId='" + eventSubscriptionId + "'") .add("subScopeId='" + subScopeId + "'") .add("scopeType='" + scopeType + "'") .add("scopeDefinitionId='" + scopeDefinitionId + "'") .add("hasExistingInstancesForUniqueCorrelation=" + hasExistingInstancesForUniqueCorrelation) .toString(); } }
repos\flowable-engine-main\modules\flowable-event-registry-api\src\main\java\org\flowable\eventregistry\api\EventConsumerInfo.java
1
请在Spring Boot框架中完成以下Java代码
public UserVO login(LoginUserRequest request) { return userRepository .findByEmail(request.email()) .filter(user -> passwordEncoder.matches(request.password(), user.getPassword())) .map(user -> { String token = bearerTokenSupplier.supply(user); return new UserVO(user.possessToken(token)); }) .orElseThrow(() -> new IllegalArgumentException("Invalid email or password.")); } @Transactional @Override public UserVO update(User user, UpdateUserRequest request) { String email = request.email(); if (!user.getEmail().equals(email) && userRepository.existsByEmail(email)) { throw new IllegalArgumentException("Email(`%s`) already exists.".formatted(email)); } String username = request.username(); if (!user.getUsername().equals(username) && userRepository.existsByUsername(username)) {
throw new IllegalArgumentException("Username(`%s`) already exists.".formatted(request.username())); } user.updateEmail(email); user.updateUsername(username); user.updatePassword(passwordEncoder, request.password()); user.updateBio(request.bio()); user.updateImage(request.image()); return new UserVO(user); } private User createNewUser(SignUpUserRequest request) { return User.builder() .email(request.email()) .username(request.username()) .password(passwordEncoder.encode(request.password())) .build(); } }
repos\realworld-spring-boot-native-master\src\main\java\com\softwaremill\realworld\application\user\service\UserApplicationService.java
2
请完成以下Java代码
public String getMsg(@NonNull final AdMessageKey adMessage, final List<Object> params) { if (params == null || params.isEmpty()) { return adMessage.toAD_Message(); } return adMessage.toAD_Message() + "_" + params; } @Override public Map<String, String> getMsgMap(final String adLanguage, final String prefix, final boolean removePrefix) { return ImmutableMap.of(); } @Override public String parseTranslation(final Properties ctx, final String message) { return message; } @Override public String parseTranslation(final String adLanguage, final String message) { return message; } @Override public String translate(final Properties ctx, final String text) { return text; } @Override public String translate(final String adLanguage, final String text) { return text; } @Override public String translate(final Properties ctx, final String text, final boolean isSOTrx) { return text; } @Override public ITranslatableString translatable(final String text) { return TranslatableStrings.constant(text); } @Override public ITranslatableString getTranslatableMsgText(@NonNull final AdMessageKey adMessage, final Object... msgParameters) { if (msgParameters == null || msgParameters.length == 0) { return TranslatableStrings.constant(adMessage.toAD_Message()); } else
{ return TranslatableStrings.constant(adMessage.toAD_Message() + " - " + Joiner.on(", ").useForNull("-").join(msgParameters)); } } @Override public void cacheReset() { // nothing } @Override public String getBaseLanguageMsg(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters) { return TranslatableStrings.adMessage(adMessage, msgParameters) .translate(Language.getBaseAD_Language()); } @Override public Optional<AdMessageId> getIdByAdMessage(@NonNull final AdMessageKey value) { return Optional.empty(); } @Override public boolean isMessageExists(final AdMessageKey adMessage) { return false; } @Override public Optional<AdMessageKey> getAdMessageKeyById(final AdMessageId adMessageId) { return Optional.empty(); } @Nullable @Override public String getErrorCode(final @NonNull AdMessageKey messageKey) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\PlainMsgBL.java
1
请完成以下Spring Boot application配置
server: port: 8081 person: lastName: zhangsan # 也可写成(松散语法) last-name:zhansang age: 18 boss: false birth: 2017/12/12 map: {k1: v1, k2 : 12} list: - lisi - zhaoliu dog:
name: 史努比 age: 2 email: xxxxxx cat: name: Tom age: 5 email: xxxxxx
repos\SpringBootLearning-master (1)\springboot-config\src\main\resources\application.yml
2
请完成以下Java代码
public abstract class AbstractWidgetTypeEntity<T extends BaseWidgetType> extends BaseVersionedEntity<T> { @Column(name = ModelConstants.WIDGET_TYPE_TENANT_ID_PROPERTY) private UUID tenantId; @Column(name = ModelConstants.WIDGET_TYPE_FQN_PROPERTY) private String fqn; @Column(name = ModelConstants.WIDGET_TYPE_NAME_PROPERTY) private String name; @Column(name = ModelConstants.WIDGET_TYPE_DEPRECATED_PROPERTY) private boolean deprecated; @Column(name = ModelConstants.WIDGET_TYPE_SCADA_PROPERTY) private boolean scada; public AbstractWidgetTypeEntity() { super(); } public AbstractWidgetTypeEntity(T widgetType) { super(widgetType); if (widgetType.getTenantId() != null) { this.tenantId = widgetType.getTenantId().getId(); } this.fqn = widgetType.getFqn(); this.name = widgetType.getName(); this.deprecated = widgetType.isDeprecated(); this.scada = widgetType.isScada(); } public AbstractWidgetTypeEntity(AbstractWidgetTypeEntity widgetTypeEntity) {
super(widgetTypeEntity); this.tenantId = widgetTypeEntity.getTenantId(); this.fqn = widgetTypeEntity.getFqn(); this.name = widgetTypeEntity.getName(); this.deprecated = widgetTypeEntity.isDeprecated(); this.scada = widgetTypeEntity.isScada(); } protected BaseWidgetType toBaseWidgetType() { BaseWidgetType widgetType = new BaseWidgetType(new WidgetTypeId(getUuid())); widgetType.setCreatedTime(createdTime); widgetType.setVersion(version); if (tenantId != null) { widgetType.setTenantId(TenantId.fromUUID(tenantId)); } widgetType.setFqn(fqn); widgetType.setName(name); widgetType.setDeprecated(deprecated); widgetType.setScada(scada); return widgetType; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\AbstractWidgetTypeEntity.java
1
请完成以下Java代码
public void print(final PrintStream out) { final boolean printStackTrace = true; // backward compatibility print(out, printStackTrace); } public void print(final PrintStream out, final boolean printStackTrace) { out.println("Error: " + getInnerMessage()); for (final Map.Entry<String, Object> param : getParameters().entrySet()) { final Object value = param.getValue(); if (value == null) { continue; } final String name = param.getKey(); if (value instanceof List<?>) { final List<?> list = (List<?>)value; if (list.isEmpty()) { continue; } out.println(name + ":"); for (final Object item : list) { out.println("\t" + item); } } else { out.println(name + ": " + value); } } if (printStackTrace) {
out.println("Stack trace: "); this.printStackTrace(out); } } public String toStringX() { final boolean printStackTrace = true; // backward compatibility return toStringX(printStackTrace); } public String toStringX(final boolean printStackTrace) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); print(out, printStackTrace); return baos.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\exception\ScriptException.java
1
请在Spring Boot框架中完成以下Java代码
public SAPGLJournal getByRecord(@NonNull final I_SAP_GLJournal record) { final SAPGLJournalId id = SAPGLJournalId.ofRepoId(record.getSAP_GLJournal_ID()); final SAPGLJournalLoaderAndSaver loader = new SAPGLJournalLoaderAndSaver(); loader.addToCacheAndAvoidSaving(record); return loader.getById(id); } public SeqNo getNextSeqNo(@NonNull final SAPGLJournalId glJournalId) { final SAPGLJournalLoaderAndSaver loader = new SAPGLJournalLoaderAndSaver(); return loader.getNextSeqNo(glJournalId); } public void updateWhileSaving( @NonNull final I_SAP_GLJournal record, @NonNull final Consumer<SAPGLJournal> consumer) { final SAPGLJournalId glJournalId = SAPGLJournalLoaderAndSaver.extractId(record); final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); loaderAndSaver.addToCacheAndAvoidSaving(record); loaderAndSaver.updateById(glJournalId, consumer); } public void updateById( @NonNull final SAPGLJournalId glJournalId, @NonNull final Consumer<SAPGLJournal> consumer) { final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); loaderAndSaver.updateById(glJournalId, consumer); } public <R> R updateById( @NonNull final SAPGLJournalId glJournalId, @NonNull final Function<SAPGLJournal, R> processor)
{ final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); return loaderAndSaver.updateById(glJournalId, processor); } public DocStatus getDocStatus(final SAPGLJournalId glJournalId) { final SAPGLJournalLoaderAndSaver loader = new SAPGLJournalLoaderAndSaver(); return loader.getDocStatus(glJournalId); } @NonNull public SAPGLJournal create( @NonNull final SAPGLJournalCreateRequest createRequest, @NonNull final SAPGLJournalCurrencyConverter currencyConverter) { final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); return loaderAndSaver.create(createRequest, currencyConverter); } public void save(@NonNull final SAPGLJournal sapglJournal) { final SAPGLJournalLoaderAndSaver loaderAndSaver = new SAPGLJournalLoaderAndSaver(); loaderAndSaver.save(sapglJournal); } public SAPGLJournalLineId acquireLineId(@NonNull final SAPGLJournalId sapGLJournalId) { final int lineRepoId = DB.getNextID(ClientId.METASFRESH.getRepoId(), I_SAP_GLJournalLine.Table_Name); return SAPGLJournalLineId.ofRepoId(sapGLJournalId, lineRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalRepository.java
2
请完成以下Java代码
public class CScrollPane extends JScrollPane { /** * */ private static final long serialVersionUID = -2941967111871448295L; /** * Adempiere ScollPane */ public CScrollPane () { this (null, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); } // CScollPane /** * Adempiere ScollPane * @param vsbPolicy vertical policy * @param hsbPolicy horizontal policy */ public CScrollPane (int vsbPolicy, int hsbPolicy) { this (null, vsbPolicy, hsbPolicy); } // CScollPane /** * Adempiere ScollPane * @param view view */ public CScrollPane (Component view) { this (view, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); } // CScollPane /** * Adempiere ScollPane * @param view view
* @param vsbPolicy vertical policy * @param hsbPolicy horizontal policy */ public CScrollPane (Component view, int vsbPolicy, int hsbPolicy) { super (view, vsbPolicy, hsbPolicy); setOpaque(false); getViewport().setOpaque(false); } // CScollPane /** * Set Background * @param bg AdempiereColor for Background, if null set standard background */ public void setBackgroundColor (MFColor bg) { if (bg == null) bg = MFColor.ofFlatColor(AdempierePLAF.getFormBackground()); putClientProperty(AdempiereLookAndFeel.BACKGROUND, bg); } // setBackground } // CScollPane
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CScrollPane.java
1
请完成以下Java代码
private void setRecordsToOpen(@NonNull final Set<BankStatementId> importedBankStatementIds) { getResult().setRecordToOpen(ProcessExecutionResult.RecordsToOpen.builder() .records(TableRecordReference.ofRecordIds(I_C_BankStatement.Table_Name, BankStatementId.toIntSet(importedBankStatementIds))) .targetTab(ProcessExecutionResult.RecordsToOpen.TargetTab.NEW_TAB) .target(importedBankStatementIds.size() == 1 ? ProcessExecutionResult.RecordsToOpen.OpenTarget.SingleDocument : ProcessExecutionResult.RecordsToOpen.OpenTarget.GridView) .build()); } private boolean isSelectedRecordProcessed(@NonNull final BankStatementImportFileId bankStatementImportFileId) { return bankStatementImportFileService.getById(bankStatementImportFileId) .isProcessed(); } private boolean isMissingAttachmentEntryForRecordId(@NonNull final BankStatementImportFileId bankStatementImportFileId) { return !getSingleAttachmentEntryId(bankStatementImportFileId).isPresent(); } @NonNull private Optional<AttachmentEntryId> getSingleAttachmentEntryId(@NonNull final BankStatementImportFileId bankStatementImportFileId) { final List<AttachmentEntry> attachments = attachmentEntryService .getByReferencedRecord(TableRecordReference.of(I_C_BankStatement_Import_File.Table_Name, bankStatementImportFileId)); if (attachments.isEmpty()) { return Optional.empty(); } if (attachments.size() != 1) {
throw new AdempiereException(MSG_MULTIPLE_ATTACHMENTS) .markAsUserValidationError(); } return Optional.of(attachments.get(0).getId()); } @NonNull private AttachmentEntryDataResource retrieveAttachmentResource(@NonNull final BankStatementImportFileId bankStatementImportFileId) { final AttachmentEntryId attachmentEntryId = getSingleAttachmentEntryId(bankStatementImportFileId) .orElseThrow(() -> new AdempiereException(MSG_NO_ATTACHMENT) .markAsUserValidationError()); return attachmentEntryService.retrieveDataResource(attachmentEntryId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\process\C_BankStatement_Import_File_Camt53_ImportAttachment.java
1
请在Spring Boot框架中完成以下Java代码
public ApiResponse<List<NursingHome>> getNewAndUpdatedNursingHomesWithHttpInfo(String albertaApiKey, String updatedAfter) throws ApiException { com.squareup.okhttp.Call call = getNewAndUpdatedNursingHomesValidateBeforeCall(albertaApiKey, updatedAfter, null, null); Type localVarReturnType = new TypeToken<List<NursingHome>>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Daten der neuen und geänderten Pflegeheime abrufen (asynchronously) * Szenario - das WaWi fragt bei Alberta nach, wie ob es neue oder geänderte Pflegeheime gibt * @param albertaApiKey (required) * @param updatedAfter 2021-02-21T09:30:00.000Z (im UTC-Format) (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getNewAndUpdatedNursingHomesAsync(String albertaApiKey, String updatedAfter, final ApiCallback<List<NursingHome>> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } };
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getNewAndUpdatedNursingHomesValidateBeforeCall(albertaApiKey, updatedAfter, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<List<NursingHome>>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\NursingHomeApi.java
2
请完成以下Java代码
private static class WorkplacesMap { private final ImmutableMap<WorkplaceId, Workplace> byId; @Getter private final ImmutableList<Workplace> allActive; WorkplacesMap(final List<Workplace> list) { this.byId = Maps.uniqueIndex(list, Workplace::getId); this.allActive = ImmutableList.copyOf(list); } @NonNull public Workplace getById(final WorkplaceId id) { final Workplace workplace = byId.get(id); if (workplace == null) { throw new AdempiereException("No workplace found for " + id); } return workplace; } public Collection<Workplace> getByIds(final Collection<WorkplaceId> ids)
{ if (ids.isEmpty()) { return ImmutableList.of(); } return ids.stream() .map(this::getById) .collect(ImmutableList.toImmutableList()); } public boolean isEmpty() { return byId.isEmpty(); } public SeqNo getNextSeqNo() { final Workplace workplace = getAllActive().stream().max(Comparator.comparing(v -> v.getSeqNo().toInt())).orElse(null); return workplace != null ? workplace.getSeqNo().next() : SeqNo.ofInt(10); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\WorkplaceRepository.java
1
请完成以下Spring Boot application配置
management: endpoints: # Actuator HTTP 配置项,对应 WebEndpointProperties 配置类 web: exposure: include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 spring: application: name: demo-application # 应用名 boot: admin: client: url: http
://127.0.0.1:8080 # Spring Boot Admin Server 地址 server: port: 18080 # 设置自定义 Server 端口,避免和 Spring Boot Admin Server 端口冲突。
repos\SpringBoot-Labs-master\lab-35\lab-35-admin-01-demo-application\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public LineBuilder endRef() { return parentbuilder.endRef(); } /** * Convenience method to end the current ref builder and start a new one. * * @return the new reference builder, <b>not</b> this instance. */ public RefBuilder newRef() { return endRef().ref(); } /** * Supposed to be called only by the parent builder. * * @param parent * @return */ /* package */ PartitionerConfigReference build(final PartitionerConfigLine parent) { final PartitionerConfigReference partitionerConfigReference = new PartitionerConfigReference(parent, referencingColumnName, referencedTableName, partitionBoundary); partitionerConfigReference.setDLM_Partition_Config_Reference_ID(DLM_Partition_Config_Reference_ID); return partitionerConfigReference; } @Override public int hashCode() { return new HashcodeBuilder() .append(referencedTableName) .append(referencingColumnName) .append(parentbuilder) .toHashcode();
}; /** * Note: it's important not to include {@link #getDLM_Partition_Config_Reference_ID()} in the result. * Check the implementation of {@link PartitionerConfigLine.LineBuilder#endRef()} for details. */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } final RefBuilder other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(referencedTableName, other.referencedTableName) .append(referencingColumnName, other.referencingColumnName) .append(parentbuilder, other.parentbuilder) .isEqual(); } @Override public String toString() { return "RefBuilder [referencingColumnName=" + referencingColumnName + ", referencedTableName=" + referencedTableName + ", partitionBoundary=" + partitionBoundary + ", DLM_Partition_Config_Reference_ID=" + DLM_Partition_Config_Reference_ID + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionerConfigReference.java
2
请在Spring Boot框架中完成以下Java代码
public Set<FlatrateTermId> retrieveMembershipSubscriptionIds( @NonNull final BPartnerId bpartnerId, @NonNull final Instant orgChangeDate, @NonNull final OrgId orgId) { return queryMembershipRunningSubscription(bpartnerId, orgChangeDate, orgId) .idsAsSet(FlatrateTermId::ofRepoId); } public IQuery<I_C_Flatrate_Term> queryMembershipRunningSubscription( @NonNull final BPartnerId bPartnerId, @NonNull final Instant orgChangeDate, @NonNull final OrgId orgId) { final IQuery<I_M_Product> membershipProductQuery = queryMembershipProducts(orgId); return queryBL.createQueryBuilder(I_C_Flatrate_Term.class) .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bPartnerId) .addInSubQueryFilter(I_C_Flatrate_Term.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, membershipProductQuery) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Quit.getCode()) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Voided.getCode()) .addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_EndDate, CompareQueryFilter.Operator.GREATER, orgChangeDate) .create(); } public IQuery<I_M_Product> queryMembershipProducts(@NonNull final OrgId orgId) { return queryBL.createQueryBuilder(I_M_Product.class) .addEqualsFilter(I_M_Product.COLUMNNAME_AD_Org_ID, orgId)
.addNotEqualsFilter(I_M_Product.COLUMNNAME_C_CompensationGroup_Schema_ID, null) .addNotEqualsFilter(I_M_Product.COLUMNNAME_C_CompensationGroup_Schema_Category_ID, null) .create(); } public ImmutableSet<OrderId> retrieveMembershipOrderIds( @NonNull final OrgId orgId, @NonNull final Instant orgChangeDate) { final IQuery<I_M_Product> membershipProductQuery = queryMembershipProducts(orgId); return queryBL.createQueryBuilder(I_C_Flatrate_Term.class) .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID, orgId) .addInSubQueryFilter(I_C_Flatrate_Term.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, membershipProductQuery) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Quit.getCode()) .addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Voided.getCode()) .addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_EndDate, CompareQueryFilter.Operator.GREATER, orgChangeDate) .andCollect(I_C_Flatrate_Term.COLUMNNAME_C_Order_Term_ID, I_C_Order.class) .addEqualsFilter(I_C_Order.COLUMNNAME_AD_Org_ID, orgId) .create() .idsAsSet(OrderId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\repository\MembershipContractRepository.java
2
请完成以下Java代码
public class DomXmlDataFormatReader extends TextBasedDataFormatReader { private static final DomXmlLogger LOG = DomXmlLogger.XML_DOM_LOGGER; private static final Pattern INPUT_MATCHING_PATTERN = Pattern.compile("\\A(\\s)*<"); protected DomXmlDataFormat dataFormat; public DomXmlDataFormatReader(DomXmlDataFormat dataFormat) { this.dataFormat = dataFormat; } public Element readInput(Reader input) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { LOG.parsingInput(); return documentBuilder.parse(new InputSource(input)).getDocumentElement(); } catch (SAXException e) { throw LOG.unableToParseInput(e); } catch (IOException e) { throw LOG.unableToParseInput(e); }
} /** * @return the DocumentBuilder used by this reader */ protected DocumentBuilder getDocumentBuilder() { try { DocumentBuilder docBuilder = dataFormat.getDocumentBuilderFactory().newDocumentBuilder(); LOG.createdDocumentBuilder(); return docBuilder; } catch (ParserConfigurationException e) { throw LOG.unableToCreateParser(e); } } protected Pattern getInputDetectionPattern() { return INPUT_MATCHING_PATTERN; } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\format\DomXmlDataFormatReader.java
1
请在Spring Boot框架中完成以下Java代码
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { HttpServletRequest request = ((FilterInvocation) object).getHttpRequest(); String url, method; AntPathRequestMatcher matcher; for (GrantedAuthority ga : authentication.getAuthorities()) { if (ga instanceof MyGrantedAuthority) { MyGrantedAuthority urlGrantedAuthority = (MyGrantedAuthority) ga; url = urlGrantedAuthority.getPermissionUrl(); method = urlGrantedAuthority.getMethod(); matcher = new AntPathRequestMatcher(url); if (matcher.matches(request)) { //当权限表权限的method为ALL时表示拥有此路径的所有请求方式权利。 if (method.equals(request.getMethod()) || "ALL".equals(method)) { return; } } } else if (ga.getAuthority().equals("ROLE_ANONYMOUS")) {//未登录只允许访问 login 页面 matcher = new AntPathRequestMatcher("/login"); if (matcher.matches(request)) { return;
} } } throw new AccessDeniedException("no right"); } @Override public boolean supports(ConfigAttribute attribute) { return true; } @Override public boolean supports(Class<?> clazz) { return true; } }
repos\springBoot-master\springboot-springSecurity3\src\main\java\com\us\example\service\MyAccessDecisionManager.java
2
请完成以下Java代码
public final class ColoredNumberComparable implements Comparable<ColoredNumberComparable> { private int value; private String color; public ColoredNumberComparable(int value, String color) { this.value = value; this.color = color; } @Override public int compareTo(ColoredNumberComparable o) { // (both numbers are red) or (both numbers are not red) if ((this.color.equals("red") && o.color.equals("red")) || (!this.color.equals("red") && !o.color.equals("red"))) { return Integer.compare(this.value, o.value); } // only the first number is red else if (this.color.equals("red")) { return -1; } // only the second number is red else { return 1; }
} public int getValue() { return value; } public void setValue(int value) { this.value = value; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
repos\tutorials-master\core-java-modules\core-java-collections\src\main\java\com\baeldung\collections\priorityqueue\ColoredNumberComparable.java
1
请在Spring Boot框架中完成以下Java代码
private static class CostElementIdAndAcctSchemaId { @NonNull CostElementId costTypeId; @NonNull AcctSchemaId acctSchemaId; } private static class CostElementAccountsMap { private final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map; public CostElementAccountsMap( @NonNull final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map) { this.map = map; }
public CostElementAccounts getAccounts( @NonNull final CostElementId costElementId, @NonNull final AcctSchemaId acctSchemaId) { final CostElementAccounts accounts = map.get(CostElementIdAndAcctSchemaId.of(costElementId, acctSchemaId)); if (accounts == null) { throw new AdempiereException("No accounts found for " + costElementId + " and " + acctSchemaId); } return accounts; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\CostElementAccountsRepository.java
2