instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
protected void checkHistoryEnabled() { if (!isHistoryEnabled) { throw LOG.disabledHistoryException(); } } public boolean isHistoryEnabled() { return isHistoryEnabled; } public boolean isHistoryLevelFullEnabled() { return isHistoryLevelFullEnabled; } protected static boolean isPerformUpdate(Set<String> entities, Class<?> entityClass) {
return entities == null || entities.isEmpty() || entities.contains(entityClass.getName()); } protected static boolean isPerformUpdateOnly(Set<String> entities, Class<?> entityClass) { return entities != null && entities.size() == 1 && entities.contains(entityClass.getName()); } protected static void addOperation(DbOperation operation, Map<Class<? extends DbEntity>, DbOperation> operations) { operations.put(operation.getEntityType(), operation); } protected static void addOperation(Collection<DbOperation> newOperations, Map<Class<? extends DbEntity>, DbOperation> operations) { newOperations.forEach(operation -> operations.put(operation.getEntityType(), operation)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\AbstractHistoricManager.java
1
请在Spring Boot框架中完成以下Java代码
KotlinJpaGradleBuildCustomizer kotlinJpaGradleBuildCustomizerGroovyDsl(InitializrMetadata metadata, KotlinProjectSettings settings, ProjectDescription projectDescription) { return new KotlinJpaGradleBuildCustomizer(metadata, settings, projectDescription, '\''); } @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) KotlinJpaMavenBuildCustomizer kotlinJpaMavenBuildCustomizer(InitializrMetadata metadata, ProjectDescription projectDescription) { return new KotlinJpaMavenBuildCustomizer(metadata, projectDescription); } @Bean @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_KOTLIN) KotlinGradleBuildCustomizer kotlinBuildCustomizerKotlinDsl(KotlinProjectSettings kotlinProjectSettings) { return new KotlinGradleBuildCustomizer(kotlinProjectSettings, '\"'); } @Bean @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY) KotlinGradleBuildCustomizer kotlinBuildCustomizerGroovyDsl(KotlinProjectSettings kotlinProjectSettings) { return new KotlinGradleBuildCustomizer(kotlinProjectSettings, '\''); } /** * Configuration for Kotlin projects using Spring Boot 2.0 and later. */ @Configuration @ConditionalOnPlatformVersion("2.0.0.M1") static class SpringBoot2AndLaterKotlinProjectGenerationConfiguration { @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) KotlinMavenBuildCustomizer kotlinBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) { return new KotlinMavenBuildCustomizer(kotlinProjectSettings); } @Bean
MainCompilationUnitCustomizer<KotlinTypeDeclaration, KotlinCompilationUnit> mainFunctionContributor( ProjectDescription description) { return (compilationUnit) -> compilationUnit.addTopLevelFunction(KotlinFunctionDeclaration.function("main") .parameters(Parameter.of("args", "Array<String>")) .body(CodeBlock.ofStatement("$T<$L>(*args)", "org.springframework.boot.runApplication", description.getApplicationName()))); } } /** * Kotlin source code contributions for projects using war packaging. */ @Configuration @ConditionalOnPackaging(WarPackaging.ID) static class WarPackagingConfiguration { @Bean ServletInitializerCustomizer<KotlinTypeDeclaration> javaServletInitializerCustomizer( ProjectDescription description) { return (typeDeclaration) -> { KotlinFunctionDeclaration configure = KotlinFunctionDeclaration.function("configure") .modifiers(KotlinModifier.OVERRIDE) .returning("org.springframework.boot.builder.SpringApplicationBuilder") .parameters( Parameter.of("application", "org.springframework.boot.builder.SpringApplicationBuilder")) .body(CodeBlock.ofStatement("return application.sources($L::class.java)", description.getApplicationName())); typeDeclaration.addFunctionDeclaration(configure); }; } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\KotlinProjectGenerationDefaultContributorsConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public Pharmacy timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pharmacy pharmacy = (Pharmacy) o; return Objects.equals(this._id, pharmacy._id) && Objects.equals(this.name, pharmacy.name) && Objects.equals(this.address, pharmacy.address) && Objects.equals(this.postalCode, pharmacy.postalCode) && Objects.equals(this.city, pharmacy.city) && Objects.equals(this.phone, pharmacy.phone) && Objects.equals(this.fax, pharmacy.fax) && Objects.equals(this.email, pharmacy.email) && Objects.equals(this.website, pharmacy.website) && Objects.equals(this.timestamp, pharmacy.timestamp); }
@Override public int hashCode() { return Objects.hash(_id, name, address, postalCode, city, phone, fax, email, website, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Pharmacy {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" fax: ").append(toIndentedString(fax)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" website: ").append(toIndentedString(website)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Pharmacy.java
2
请在Spring Boot框架中完成以下Java代码
public String showTodos(ModelMap model) { String name = getLoggedInUserName(model); model.put("todos", todoService.getTodosByUser(name)); // model.put("todos", service.retrieveTodos(name)); return "list-todos"; } private String getLoggedInUserName(ModelMap model) { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } return principal.toString(); } @RequestMapping(value = "/add-todo", method = RequestMethod.GET) public String showAddTodoPage(ModelMap model) { model.addAttribute("todo", new Todo()); return "todo"; } @RequestMapping(value = "/delete-todo", method = RequestMethod.GET) public String deleteTodo(@RequestParam long id) { todoService.deleteTodo(id); // service.deleteTodo(id); return "redirect:/list-todos"; } @RequestMapping(value = "/update-todo", method = RequestMethod.GET)
public String showUpdateTodoPage(@RequestParam long id, ModelMap model) { Todo todo = todoService.getTodoById(id).get(); model.put("todo", todo); return "todo"; } @RequestMapping(value = "/update-todo", method = RequestMethod.POST) public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } todo.setUserName(getLoggedInUserName(model)); todoService.updateTodo(todo); return "redirect:/list-todos"; } @RequestMapping(value = "/add-todo", method = RequestMethod.POST) public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } todo.setUserName(getLoggedInUserName(model)); todoService.saveTodo(todo); return "redirect:/list-todos"; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\0.ProjectToDoinDB\src\main\java\spring\hibernate\controller\TodoController.java
2
请完成以下Java代码
public void setPricingSystemSurchargeAmt (java.math.BigDecimal PricingSystemSurchargeAmt) { set_Value (COLUMNNAME_PricingSystemSurchargeAmt, PricingSystemSurchargeAmt); } /** Get Preisaufschlag. @return Aufschlag auf den Preis, der aus dem Preissystem resultieren würde */ @Override public java.math.BigDecimal getPricingSystemSurchargeAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PricingSystemSurchargeAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false;
} /** Set Produktschlüssel. @param ProductValue Schlüssel des Produktes */ @Override public void setProductValue (java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } /** Get Produktschlüssel. @return Schlüssel des Produktes */ @Override public java.lang.String getProductValue () { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_DiscountSchema.java
1
请完成以下Java代码
public static InitializrMetadataBuilder fromInitializrProperties(InitializrProperties configuration) { return new InitializrMetadataBuilder(configuration).withInitializrProperties(configuration); } /** * Create an empty builder instance with a default {@link InitializrConfiguration}. * @return a new {@link InitializrMetadataBuilder} instance */ public static InitializrMetadataBuilder create() { return new InitializrMetadataBuilder(new InitializrConfiguration()); } private static class InitializerPropertiesCustomizer implements InitializrMetadataCustomizer { private final InitializrProperties properties; InitializerPropertiesCustomizer(InitializrProperties properties) { this.properties = properties; } @Override public void customize(InitializrMetadata metadata) { metadata.getDependencies().merge(this.properties.getDependencies()); metadata.getTypes().merge(this.properties.getTypes()); metadata.getBootVersions().merge(this.properties.getBootVersions()); metadata.getPackagings().merge(this.properties.getPackagings()); metadata.getJavaVersions().merge(this.properties.getJavaVersions()); metadata.getLanguages().merge(this.properties.getLanguages()); metadata.getConfigurationFileFormats().merge(this.properties.getConfigurationFileFormats()); this.properties.getGroupId().apply(metadata.getGroupId()); this.properties.getArtifactId().apply(metadata.getArtifactId()); this.properties.getVersion().apply(metadata.getVersion()); this.properties.getName().apply(metadata.getName()); this.properties.getDescription().apply(metadata.getDescription()); this.properties.getPackageName().apply(metadata.getPackageName()); } } private static class ResourceInitializrMetadataCustomizer implements InitializrMetadataCustomizer {
private static final Log logger = LogFactory.getLog(ResourceInitializrMetadataCustomizer.class); private static final Charset UTF_8 = StandardCharsets.UTF_8; private final Resource resource; ResourceInitializrMetadataCustomizer(Resource resource) { this.resource = resource; } @Override public void customize(InitializrMetadata metadata) { logger.info("Loading initializr metadata from " + this.resource); try (InputStream in = this.resource.getInputStream()) { String content = StreamUtils.copyToString(in, UTF_8); ObjectMapper objectMapper = new ObjectMapper(); InitializrMetadata anotherMetadata = objectMapper.readValue(content, InitializrMetadata.class); metadata.merge(anotherMetadata); } catch (Exception ex) { throw new IllegalStateException("Cannot merge", ex); } } } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\InitializrMetadataBuilder.java
1
请完成以下Java代码
public BigDecimal getApprovalAmt() { return handler.getApprovalAmt(model); } @Override public int getAD_Client_ID() { return model.getAD_Client_ID(); } @Override public int getAD_Org_ID() { return model.getAD_Org_ID(); } @Override public String getDocAction() { return model.getDocAction(); } @Override public boolean save() { InterfaceWrapperHelper.save(model); return true; } @Override public Properties getCtx() { return InterfaceWrapperHelper.getCtx(model); } @Override public int get_ID() { return InterfaceWrapperHelper.getId(model); } @Override
public int get_Table_ID() { return InterfaceWrapperHelper.getModelTableId(model); } @Override public String get_TrxName() { return InterfaceWrapperHelper.getTrxName(model); } @Override public void set_TrxName(final String trxName) { InterfaceWrapperHelper.setTrxName(model, trxName); } @Override public boolean isActive() { return model.isActive(); } @Override public Object getModel() { return getDocumentModel(); } @Override public Object getDocumentModel() { return model; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocumentWrapper.java
1
请完成以下Java代码
public List<String> getIds() { return ids; } public Date getRemovalTime() { return removalTime; } public Mode getMode() { return mode; } public boolean isHierarchical() { return isHierarchical; }
public boolean isUpdateInChunks() { return updateInChunks; } public Integer getChunkSize() { return chunkSize; } public static enum Mode { CALCULATED_REMOVAL_TIME, ABSOLUTE_REMOVAL_TIME, CLEARED_REMOVAL_TIME; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricProcessInstancesBuilderImpl.java
1
请完成以下Java代码
public void releasePickingSlotsIfPossible(@NonNull final Collection<PickingSlotId> pickingSlotIds) { // tolerate empty if (pickingSlotIds.isEmpty()) { return; } pickingSlotIds.forEach(this::releasePickingSlotIfPossible); } @Override public List<I_M_HU> retrieveAvailableSourceHUs(@NonNull final PickingHUsQuery query) { final SourceHUsService sourceHuService = SourceHUsService.get(); return RetrieveAvailableHUsToPick.retrieveAvailableHUsToPick(query, sourceHuService::retrieveParentHusThatAreSourceHUs); } @Override @NonNull public List<I_M_HU> retrieveAvailableHUsToPick(@NonNull final PickingHUsQuery query) { return RetrieveAvailableHUsToPick.retrieveAvailableHUsToPick(query, RetrieveAvailableHUsToPickFilters::retrieveFullTreeAndExcludePickingHUs); } @Override public ImmutableList<HuId> retrieveAvailableHUIdsToPick(@NonNull final PickingHUsQuery query) { return retrieveAvailableHUsToPick(query) .stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableList.toImmutableList()); }
@Override public ImmutableList<HuId> retrieveAvailableHUIdsToPickForShipmentSchedule(@NonNull final RetrieveAvailableHUIdsToPickRequest request) { final I_M_ShipmentSchedule schedule = loadOutOfTrx(request.getScheduleId(), I_M_ShipmentSchedule.class); final PickingHUsQuery query = PickingHUsQuery .builder() .onlyTopLevelHUs(request.isOnlyTopLevel()) .shipmentSchedule(schedule) .onlyIfAttributesMatchWithShipmentSchedules(request.isConsiderAttributes()) .build(); return retrieveAvailableHUIdsToPick(query); } public boolean clearPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, final boolean removeQueuedHUsFromSlot) { final I_M_PickingSlot slot = pickingSlotDAO.getById(pickingSlotId, I_M_PickingSlot.class); if (removeQueuedHUsFromSlot) { huPickingSlotDAO.retrieveAllHUs(slot) .stream() .map(hu -> HuId.ofRepoId(hu.getM_HU_ID())) .forEach(queuedHU -> removeFromPickingSlotQueue(slot, queuedHU)); } return huPickingSlotDAO.isEmpty(slot); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\impl\HUPickingSlotBL.java
1
请完成以下Java代码
public void setM_ShipmentSchedule_ID (int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID)); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setPlannedQty (java.math.BigDecimal PlannedQty) { set_Value (COLUMNNAME_PlannedQty, PlannedQty); } @Override public java.math.BigDecimal getPlannedQty() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; }
@Override public void setM_InOutLine_ID (final int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_Value (COLUMNNAME_M_InOutLine_ID, null); else set_Value (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID); } @Override public int getM_InOutLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Demand_Detail.java
1
请完成以下Java代码
public class UserValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return User.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { User user = (User) target; if (StringUtils.isEmpty(user.getName())) { errors.rejectValue("name", "name.required"); } if (StringUtils.isEmpty(user.getEmail())) { errors.rejectValue("email", "email.required"); } // Add more validation rules as needed } public void validate(Object target, Errors errors, Object... validationHints) { User user = (User) target; if (validationHints.length > 0) { if (validationHints[0] == "create") { if (StringUtils.isEmpty(user.getName())) { errors.rejectValue("name", "name.required","Name cannot be empty"); } if (StringUtils.isEmpty(user.getEmail())) {
errors.rejectValue("email", "email.required" , "Invalid email format"); } if (user.getAge() < 18 || user.getAge() > 65) { errors.rejectValue("age", "user.age.outOfRange", new Object[]{18, 65}, "Age must be between 18 and 65"); } } else if (validationHints[0] == "update") { // Perform update-specific validation if (StringUtils.isEmpty(user.getName()) && StringUtils.isEmpty(user.getEmail())) { errors.rejectValue("name", "name.or.email.required", "Name or email cannot be empty"); } } } else { // Perform default validation if (StringUtils.isEmpty(user.getName())) { errors.rejectValue("name", "name.required"); } if (StringUtils.isEmpty(user.getEmail())) { errors.rejectValue("email", "email.required"); } } } }
repos\tutorials-master\spring-boot-modules\spring-boot-validation\src\main\java\com\baeldung\springvalidator\UserValidator.java
1
请完成以下Java代码
public class ReimbursementType { @XmlElement(required = true) protected EsrAddressType debitor; @XmlElement(required = true) protected BalanceType balance; protected Esr9Type esr9; protected EsrRedType esrRed; protected EsrQRType esrQR; /** * Gets the value of the debitor property. * * @return * possible object is * {@link EsrAddressType } * */ public EsrAddressType getDebitor() { return debitor; } /** * Sets the value of the debitor property. * * @param value * allowed object is * {@link EsrAddressType } * */ public void setDebitor(EsrAddressType value) { this.debitor = value; } /** * Gets the value of the balance property. * * @return * possible object is * {@link BalanceType } * */ public BalanceType getBalance() { return balance; } /** * Sets the value of the balance property. * * @param value * allowed object is * {@link BalanceType } * */ public void setBalance(BalanceType value) { this.balance = value; } /** * Gets the value of the esr9 property. * * @return * possible object is * {@link Esr9Type } * */ public Esr9Type getEsr9() { return esr9; } /** * Sets the value of the esr9 property. *
* @param value * allowed object is * {@link Esr9Type } * */ public void setEsr9(Esr9Type value) { this.esr9 = value; } /** * Gets the value of the esrRed property. * * @return * possible object is * {@link EsrRedType } * */ public EsrRedType getEsrRed() { return esrRed; } /** * Sets the value of the esrRed property. * * @param value * allowed object is * {@link EsrRedType } * */ public void setEsrRed(EsrRedType value) { this.esrRed = value; } /** * Gets the value of the esrQR property. * * @return * possible object is * {@link EsrQRType } * */ public EsrQRType getEsrQR() { return esrQR; } /** * Sets the value of the esrQR property. * * @param value * allowed object is * {@link EsrQRType } * */ public void setEsrQR(EsrQRType value) { this.esrQR = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\response\ReimbursementType.java
1
请完成以下Java代码
public void setUseProjectionForInterfaces(boolean useProjectionForInterfaces) { if (useProjectionForInterfaces) { if (!ClassUtils.isPresent("org.springframework.data.projection.ProjectionFactory", getClassLoader())) { throw new IllegalStateException("'spring-data-commons' is required to use Projection Interfaces"); } this.projectingConverter = new JacksonProjectingMessageConverter((JsonMapper) this.objectMapper); } } protected boolean isUseProjectionForInterfaces() { return this.projectingConverter != null; } @Override protected Object convertContent(Message message, @Nullable Object conversionHint, MessageProperties properties, @Nullable String encoding) throws IOException { Object content = null;
JavaType inferredType = getJavaTypeMapper().getInferredType(properties); if (inferredType != null && this.projectingConverter != null && inferredType.isInterface() && !inferredType.getRawClass().getPackage().getName().startsWith("java.util")) { // List etc content = this.projectingConverter.convert(message, inferredType.getRawClass()); properties.setProjectionUsed(true); } if (content == null) { return super.convertContent(message, conversionHint, properties, encoding); } else { return content; } } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\JacksonJsonMessageConverter.java
1
请完成以下Java代码
public void run() { int ret = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registryUpdate(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue(), new Date()); if (ret < 1) { XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registrySave(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue(), new Date()); // fresh freshGroupRegistryInfo(registryParam); } } }); return ReturnT.SUCCESS; } public ReturnT<String> registryRemove(RegistryParam registryParam) { // valid if (!StringUtils.hasText(registryParam.getRegistryGroup()) || !StringUtils.hasText(registryParam.getRegistryKey()) || !StringUtils.hasText(registryParam.getRegistryValue())) { return new ReturnT<String>(ReturnT.FAIL_CODE, "Illegal Argument."); } // async execute registryOrRemoveThreadPool.execute(new Runnable() { @Override public void run() { int ret = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registryDelete(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue()); if (ret > 0) {
// fresh freshGroupRegistryInfo(registryParam); } } }); return ReturnT.SUCCESS; } private void freshGroupRegistryInfo(RegistryParam registryParam){ // Under consideration, prevent affecting core tables } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\thread\JobRegistryHelper.java
1
请完成以下Java代码
public BigDecimal getQtyEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered); if (bd == null) return Env.ZERO; return bd; } /** Set Tax Amount. @param TaxAmt Tax Amount for a document */ public void setTaxAmt (BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } /** Get Tax Amount. @return Tax Amount for a document */ public BigDecimal getTaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt); if (bd == null) return Env.ZERO; return bd; } public I_C_ElementValue getUser1() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser1_ID(), get_TrxName()); } /** Set User List 1. @param User1_ID User defined list element #1 */ public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get User List 1. @return User defined list element #1 */ public int getUser1_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ElementValue getUser2() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser2_ID(), get_TrxName()); } /** Set User List 2. @param User2_ID User defined list element #2 */ public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get User List 2. @return User defined list element #2 */ public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_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_InvoiceBatchLine.java
1
请完成以下Java代码
public void setDirection (String Direction) { set_Value (COLUMNNAME_Direction, Direction); } /** Get Richtung. @return Richtung */ public String getDirection () { return (String)get_Value(COLUMNNAME_Direction); } /** Set Konnektor-Typ. @param ImpEx_ConnectorType_ID Konnektor-Typ */ public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID) { if (ImpEx_ConnectorType_ID < 1) set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, null); else set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID)); } /** Get Konnektor-Typ. @return Konnektor-Typ */ public int getImpEx_ConnectorType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_ConnectorType.java
1
请完成以下Java代码
public String getDeserializationAllowedClasses() { return deserializationAllowedClasses; } public ProcessEngineConfiguration setDeserializationAllowedClasses(String deserializationAllowedClasses) { this.deserializationAllowedClasses = deserializationAllowedClasses; return this; } public String getDeserializationAllowedPackages() { return deserializationAllowedPackages; } public ProcessEngineConfiguration setDeserializationAllowedPackages(String deserializationAllowedPackages) { this.deserializationAllowedPackages = deserializationAllowedPackages; return this; } public DeserializationTypeValidator getDeserializationTypeValidator() { return deserializationTypeValidator; } public ProcessEngineConfiguration setDeserializationTypeValidator(DeserializationTypeValidator deserializationTypeValidator) { this.deserializationTypeValidator = deserializationTypeValidator; return this; } public boolean isDeserializationTypeValidationEnabled() { return deserializationTypeValidationEnabled; }
public ProcessEngineConfiguration setDeserializationTypeValidationEnabled(boolean deserializationTypeValidationEnabled) { this.deserializationTypeValidationEnabled = deserializationTypeValidationEnabled; return this; } public String getInstallationId() { return installationId; } public ProcessEngineConfiguration setInstallationId(String installationId) { this.installationId = installationId; return this; } public boolean isSkipOutputMappingOnCanceledActivities() { return skipOutputMappingOnCanceledActivities; } public void setSkipOutputMappingOnCanceledActivities(boolean skipOutputMappingOnCanceledActivities) { this.skipOutputMappingOnCanceledActivities = skipOutputMappingOnCanceledActivities; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\ProcessEngineConfiguration.java
1
请完成以下Java代码
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 DocumentFilterList getFilters() { return filters; } @Override public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.EMPTY; } @Override public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { // TODO Auto-generated method stub return null; } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { throw new UnsupportedOperationException(); } @Override public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamByIds(rowIds); } @Override public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO Auto-generated method stub } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return additionalRelatedProcessDescriptors; } /** * @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}. */ @NonNull public ShipmentScheduleId getCurrentShipmentScheduleId() { return currentShipmentScheduleId; } @Override public void invalidateAll() { rows.invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java
1
请完成以下Java代码
private LotNumberQuarantine getQuarantineLotNoOrNull(final I_M_InOutLine inOutLine) { final ProductId productId = ProductId.ofRepoId(inOutLine.getM_Product_ID()); final I_M_AttributeSetInstance receiptLineASI = inOutLine.getM_AttributeSetInstance(); if (receiptLineASI == null) { // if it has no attributes set it means it has no lot number set either. return null; } final String lotNumberAttributeValue = lotNoBL.getLotNumberAttributeValueOrNull(receiptLineASI); if (Check.isEmpty(lotNumberAttributeValue)) { // if the attribute is not present or set it automatically means the lotno is not to quarantine, either return null; } return lotNumberQuarantineRepository.getByProductIdAndLot(productId, lotNumberAttributeValue);
} private boolean isCreateDDOrder(@NonNull final I_M_InOutLine inOutLine) { final List<I_M_ReceiptSchedule> rsForInOutLine = receiptScheduleDAO.retrieveRsForInOutLine(inOutLine); for (final I_M_ReceiptSchedule resceiptSchedule : rsForInOutLine) { final boolean createDistributionOrder = X_M_ReceiptSchedule.ONMATERIALRECEIPTWITHDESTWAREHOUSE_CreateDistributionOrder .equals(resceiptSchedule.getOnMaterialReceiptWithDestWarehouse()); if (createDistributionOrder) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\DistributeAndMoveReceiptCreator.java
1
请在Spring Boot框架中完成以下Java代码
public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; } @Bean JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager; } final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", env.getProperty("hibernate.globally_quoted_identifiers")); return hibernateProperties; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\boot\config\H2JpaConfig.java
2
请完成以下Java代码
public String[] getSourceArgs() { return this.args; } @Override public Set<String> getOptionNames() { String[] names = this.source.getPropertyNames(); return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(names))); } @Override public boolean containsOption(String name) { return this.source.containsProperty(name); } @Override public @Nullable List<String> getOptionValues(String name) { List<String> values = this.source.getOptionValues(name); return (values != null) ? Collections.unmodifiableList(values) : null; } @Override
public List<String> getNonOptionArgs() { return this.source.getNonOptionArgs(); } private static class Source extends SimpleCommandLinePropertySource { Source(String[] args) { super(args); } @Override public List<String> getNonOptionArgs() { return super.getNonOptionArgs(); } @Override public @Nullable List<String> getOptionValues(String name) { return super.getOptionValues(name); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\DefaultApplicationArguments.java
1
请完成以下Java代码
public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set File Name. @param FileName Name of the local file or URL */ @Override public void setFileName (java.lang.String FileName) { set_Value (COLUMNNAME_FileName, FileName); } /** Get File Name. @return Name of the local file or URL */ @Override public java.lang.String getFileName () { return (java.lang.String)get_Value(COLUMNNAME_FileName); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** * Type AD_Reference_ID=540751 * Reference name: AD_AttachmentEntry_Type */ public static final int TYPE_AD_Reference_ID=540751; /** Data = D */ public static final String TYPE_Data = "D"; /** URL = U */ public static final String TYPE_URL = "U"; /** Set Art. @param Type Art */ @Override
public void setType (java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ @Override public void setURL (java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ @Override public java.lang.String getURL () { return (java.lang.String)get_Value(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AttachmentEntry_ReferencedRecord_v.java
1
请完成以下Java代码
private void deleteInvoiceCandidateCorr(@NonNull final I_C_Flatrate_DataEntry dataEntry) { final InvoiceCandidateId invoiceCandId = InvoiceCandidateId.ofRepoIdOrNull(dataEntry.getC_Invoice_Candidate_Corr_ID()); if (invoiceCandId != null) { final I_C_Invoice_Candidate icCorr = invoiceCandDAO.getById(invoiceCandId); if (icCorr != null) { dataEntry.setC_Invoice_Candidate_Corr_ID(0); InterfaceWrapperHelper.delete(icCorr); } } } private void afterReactivate(final I_C_Flatrate_DataEntry dataEntry) {
if (X_C_Flatrate_DataEntry.TYPE_Invoicing_PeriodBased.equals(dataEntry.getType())) { final IFlatrateDAO flatrateDB = Services.get(IFlatrateDAO.class); final List<I_C_Invoice_Clearing_Alloc> allocLines = flatrateDB.retrieveClearingAllocs(dataEntry); for (final I_C_Invoice_Clearing_Alloc alloc : allocLines) { final I_C_Invoice_Candidate candToClear = alloc.getC_Invoice_Cand_ToClear(); candToClear.setQtyInvoiced(BigDecimal.ZERO); InterfaceWrapperHelper.save(candToClear); alloc.setC_Invoice_Candidate_ID(0); InterfaceWrapperHelper.save(alloc); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Flatrate_DataEntry.java
1
请在Spring Boot框架中完成以下Java代码
private void getTreeModelList(List<TreeModel> treeList,List<SysPermission> metaList,TreeModel temp) { for (SysPermission permission : metaList) { String tempPid = permission.getParentId(); TreeModel tree = new TreeModel(permission.getId(), tempPid, permission.getName(),permission.getRuleFlag(), permission.isLeaf()); if(temp==null && oConvertUtils.isEmpty(tempPid)) { treeList.add(tree); if(!tree.getIsLeaf()) { getTreeModelList(treeList, metaList, tree); } }else if(temp!=null && tempPid!=null && tempPid.equals(temp.getKey())){ temp.getChildren().add(tree); if(!tree.getIsLeaf()) { getTreeModelList(treeList, metaList, tree); } } } } /** * 分页获取全部角色列表(包含每个角色的数量) * @return */ @RequestMapping(value = "/queryPageRoleCount", method = RequestMethod.GET) public Result<IPage<SysUserRoleCountVo>> queryPageRoleCount(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) { Result<IPage<SysUserRoleCountVo>> result = new Result<>(); LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<SysRole>(); //------------------------------------------------------------------------------------------------ //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】 if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL){ query.eq(SysRole::getTenantId, oConvertUtils.getInt(TenantContext.getTenant(), 0)); } //------------------------------------------------------------------------------------------------ Page<SysRole> page = new Page<>(pageNo, pageSize); IPage<SysRole> pageList = sysRoleService.page(page, query); List<SysRole> records = pageList.getRecords(); IPage<SysUserRoleCountVo> sysRoleCountPage = new PageDTO<>(); List<SysUserRoleCountVo> sysCountVoList = new ArrayList<>(); //循环角色数据获取每个角色下面对应的角色数量
for (SysRole role:records) { LambdaQueryWrapper<SysUserRole> countQuery = new LambdaQueryWrapper<>(); countQuery.eq(SysUserRole::getRoleId,role.getId()); long count = sysUserRoleService.count(countQuery); SysUserRoleCountVo countVo = new SysUserRoleCountVo(); BeanUtils.copyProperties(role,countVo); countVo.setCount(count); sysCountVoList.add(countVo); } sysRoleCountPage.setRecords(sysCountVoList); sysRoleCountPage.setTotal(pageList.getTotal()); sysRoleCountPage.setSize(pageList.getSize()); result.setSuccess(true); result.setResult(sysRoleCountPage); return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysRoleController.java
2
请完成以下Java代码
public static LockedExternalTaskDto fromLockedExternalTask(LockedExternalTask task) { LockedExternalTaskDto dto = new LockedExternalTaskDto(); dto.activityId = task.getActivityId(); dto.activityInstanceId = task.getActivityInstanceId(); dto.errorMessage = task.getErrorMessage(); dto.errorDetails = task.getErrorDetails(); dto.executionId = task.getExecutionId(); dto.id = task.getId(); dto.lockExpirationTime = task.getLockExpirationTime(); dto.createTime = task.getCreateTime(); dto.processDefinitionId = task.getProcessDefinitionId(); dto.processDefinitionKey = task.getProcessDefinitionKey(); dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag(); dto.processInstanceId = task.getProcessInstanceId(); dto.retries = task.getRetries(); dto.topicName = task.getTopicName(); dto.workerId = task.getWorkerId(); dto.tenantId = task.getTenantId(); dto.variables = VariableValueDto.fromMap(task.getVariables()); dto.priority = task.getPriority(); dto.businessKey = task.getBusinessKey(); dto.extensionProperties = task.getExtensionProperties(); return dto; } public static List<LockedExternalTaskDto> fromLockedExternalTasks(List<LockedExternalTask> tasks) { List<LockedExternalTaskDto> dtos = new ArrayList<>(); for (LockedExternalTask task : tasks) { dtos.add(LockedExternalTaskDto.fromLockedExternalTask(task)); }
return dtos; } @Override public String toString() { return "LockedExternalTaskDto [activityId=" + activityId + ", activityInstanceId=" + activityInstanceId + ", errorMessage=" + errorMessage + ", errorDetails=" + errorDetails + ", executionId=" + executionId + ", id=" + id + ", lockExpirationTime=" + lockExpirationTime + ", createTime=" + createTime + ", processDefinitionId=" + processDefinitionId + ", processDefinitionKey=" + processDefinitionKey + ", processDefinitionVersionTag=" + processDefinitionVersionTag + ", processInstanceId=" + processInstanceId + ", retries=" + retries + ", suspended=" + suspended + ", workerId=" + workerId + ", topicName=" + topicName + ", tenantId=" + tenantId + ", variables=" + variables + ", priority=" + priority + ", businessKey=" + businessKey + "]"; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\LockedExternalTaskDto.java
1
请在Spring Boot框架中完成以下Java代码
public java.sql.Timestamp getBookedDate() { return get_ValueAsTimestamp(COLUMNNAME_BookedDate); } @Override public void setBookedSeconds (final @Nullable BigDecimal BookedSeconds) { set_Value (COLUMNNAME_BookedSeconds, BookedSeconds); } @Override public BigDecimal getBookedSeconds() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_BookedSeconds); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setComments (final @Nullable java.lang.String Comments) { set_Value (COLUMNNAME_Comments, Comments); } @Override public java.lang.String getComments() { return get_ValueAsString(COLUMNNAME_Comments); } @Override public void setHoursAndMinutes (final java.lang.String HoursAndMinutes) { set_Value (COLUMNNAME_HoursAndMinutes, HoursAndMinutes); } @Override public java.lang.String getHoursAndMinutes() { return get_ValueAsString(COLUMNNAME_HoursAndMinutes); } @Override
public de.metas.serviceprovider.model.I_S_Issue getS_Issue() { return get_ValueAsPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class); } @Override public void setS_Issue(final de.metas.serviceprovider.model.I_S_Issue S_Issue) { set_ValueFromPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Issue); } @Override public void setS_Issue_ID (final int S_Issue_ID) { if (S_Issue_ID < 1) set_Value (COLUMNNAME_S_Issue_ID, null); else set_Value (COLUMNNAME_S_Issue_ID, S_Issue_ID); } @Override public int getS_Issue_ID() { return get_ValueAsInt(COLUMNNAME_S_Issue_ID); } @Override public void setS_TimeBooking_ID (final int S_TimeBooking_ID) { if (S_TimeBooking_ID < 1) set_ValueNoCheck (COLUMNNAME_S_TimeBooking_ID, null); else set_ValueNoCheck (COLUMNNAME_S_TimeBooking_ID, S_TimeBooking_ID); } @Override public int getS_TimeBooking_ID() { return get_ValueAsInt(COLUMNNAME_S_TimeBooking_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_TimeBooking.java
2
请完成以下Java代码
public I_AD_User getDefaultContractUserInChargeOrNull(final Properties ctx) { final int userInChangeId = getDefaultContractUserInCharge_ID(ctx); if (userInChangeId <= 0) { return null; } final I_AD_User userInCharge = InterfaceWrapperHelper.create(ctx, userInChangeId, I_AD_User.class, ITrx.TRXNAME_None); return userInCharge; } @Override public boolean hasPriceOrQty(final I_C_Flatrate_DataEntry dataEntry) {
if (dataEntry == null) { return false; } final boolean hasPrice = !InterfaceWrapperHelper.isNull(dataEntry, I_C_Flatrate_DataEntry.COLUMNNAME_FlatrateAmtPerUOM) && dataEntry.getFlatrateAmtPerUOM().signum() >= 0; final boolean hasQty = !InterfaceWrapperHelper.isNull(dataEntry, I_C_Flatrate_DataEntry.COLUMNNAME_Qty_Planned) && dataEntry.getQty_Planned().signum() >= 0; return hasPrice || hasQty; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\PMMContractsBL.java
1
请完成以下Java代码
private GrantedAuthority getGrantedAuthority(String attribute) { if (isConvertAttributeToLowerCase()) { attribute = attribute.toLowerCase(Locale.ROOT); } else if (isConvertAttributeToUpperCase()) { attribute = attribute.toUpperCase(Locale.ROOT); } if (isAddPrefixIfAlreadyExisting() || !attribute.startsWith(getAttributePrefix())) { return new SimpleGrantedAuthority(getAttributePrefix() + attribute); } else { return new SimpleGrantedAuthority(attribute); } } private boolean isConvertAttributeToLowerCase() { return this.convertAttributeToLowerCase; } public void setConvertAttributeToLowerCase(boolean b) { this.convertAttributeToLowerCase = b; } private boolean isConvertAttributeToUpperCase() {
return this.convertAttributeToUpperCase; } public void setConvertAttributeToUpperCase(boolean b) { this.convertAttributeToUpperCase = b; } private String getAttributePrefix() { return (this.attributePrefix != null) ? this.attributePrefix : ""; } public void setAttributePrefix(String string) { this.attributePrefix = string; } private boolean isAddPrefixIfAlreadyExisting() { return this.addPrefixIfAlreadyExisting; } public void setAddPrefixIfAlreadyExisting(boolean b) { this.addPrefixIfAlreadyExisting = b; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\SimpleAttributes2GrantedAuthoritiesMapper.java
1
请完成以下Java代码
public class ScriptInfo extends BaseElement { protected String language; protected String resultVariable; protected String script; /** * The script language */ public String getLanguage() { return language; } /** * The script language */ public void setLanguage(String language) { this.language = language; } /** * The name of the result variable where the * script return value is written to. */ public String getResultVariable() { return resultVariable; } /** * @see #getResultVariable */ public void setResultVariable(String resultVariable) { this.resultVariable = resultVariable;
} /** * The actual script payload in the provided language. */ public String getScript() { return script; } /** * Set the script payload in the provided language. */ public void setScript(String script) { this.script = script; } @Override public ScriptInfo clone() { ScriptInfo clone = new ScriptInfo(); clone.setLanguage(this.language); clone.setScript(this.script); clone.setResultVariable(this.resultVariable); return clone; } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ScriptInfo.java
1
请完成以下Java代码
public TbResourceId getId() { return super.getId(); } @Schema(description = "Timestamp of the resource creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY) @Override public long getCreatedTime() { return super.getCreatedTime(); } @Override @JsonProperty(access = JsonProperty.Access.READ_ONLY) public String getName() { return title; } @JsonProperty(access = JsonProperty.Access.READ_ONLY) public String getLink() { String scope = (tenantId != null && tenantId.isSysTenantId()) ? "system" : "tenant"; // tenantId is null in case of export to git if (resourceType == ResourceType.IMAGE) { return "/api/images/" + scope + "/" + resourceKey; } else { return "/api/resource/" + resourceType.name().toLowerCase() + "/" + scope + "/" + resourceKey; } } @JsonProperty(access = JsonProperty.Access.READ_ONLY) public String getPublicLink() { if (resourceType == ResourceType.IMAGE && isPublic) { return "/api/images/public/" + getPublicResourceKey(); } return null; }
@JsonIgnore public String getSearchText() { return title; } @SneakyThrows public <T> T getDescriptor(Class<T> type) { return descriptor != null ? mapper.treeToValue(descriptor, type) : null; } public <T> void updateDescriptor(Class<T> type, UnaryOperator<T> updater) { T descriptor = getDescriptor(type); descriptor = updater.apply(descriptor); setDescriptorValue(descriptor); } @JsonIgnore public void setDescriptorValue(Object value) { this.descriptor = value != null ? mapper.valueToTree(value) : null; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\TbResourceInfo.java
1
请在Spring Boot框架中完成以下Java代码
class OrderRepositoryImpl implements OrderRepositoryCustom { private final MongoOperations operations; private double taxRate = 0.19; /** * The implementation uses the MongoDB aggregation framework support Spring Data provides as well as SpEL expressions * to define arithmetical expressions. Note how we work with property names only and don't have to mitigate the nested * {@code $_id} fields MongoDB usually requires. * * @see example.springdata.mongodb.aggregation.OrderRepositoryCustom#getInvoiceFor(example.springdata.mongodb.aggregation.Order) */ @Override public Invoice getInvoiceFor(Order order) { var results = operations.aggregate(newAggregation(Order.class, // match(where("id").is(order.getId())), //
unwind("items"), // project("id", "customerId", "items") // .andExpression("'$items.price' * '$items.quantity'").as("lineTotal"), // group("id") // .sum("lineTotal").as("netAmount") // .addToSet("items").as("items"), // project("id", "items", "netAmount") // .and("orderId").previousOperation() // .andExpression("netAmount * [0]", taxRate).as("taxAmount") // .andExpression("netAmount * (1 + [0])", taxRate).as("totalAmount") // ), Invoice.class); return results.getUniqueMappedResult(); } }
repos\spring-data-examples-main\mongodb\aggregation\src\main\java\example\springdata\mongodb\aggregation\OrderRepositoryImpl.java
2
请在Spring Boot框架中完成以下Java代码
static class Jackson2StrategyConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ ObjectMapper.class, CBORFactory.class }) static class Jackson2CborStrategyConfiguration { private static final MediaType[] SUPPORTED_TYPES = { MediaType.APPLICATION_CBOR }; @Bean @Order(0) @ConditionalOnBean(org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.class) RSocketStrategiesCustomizer jackson2CborRSocketStrategyCustomizer( org.springframework.http.converter.json.Jackson2ObjectMapperBuilder builder) { return (strategy) -> { ObjectMapper objectMapper = builder.createXmlMapper(false) .factory(new com.fasterxml.jackson.dataformat.cbor.CBORFactory()) .build(); strategy.decoder( new org.springframework.http.codec.cbor.Jackson2CborDecoder(objectMapper, SUPPORTED_TYPES)); strategy.encoder( new org.springframework.http.codec.cbor.Jackson2CborEncoder(objectMapper, SUPPORTED_TYPES)); }; } } @ConditionalOnClass(ObjectMapper.class) static class Jackson2JsonStrategyConfiguration { private static final MediaType[] SUPPORTED_TYPES = { MediaType.APPLICATION_JSON, new MediaType("application", "*+json") }; @Bean @Order(1) @ConditionalOnBean(ObjectMapper.class) RSocketStrategiesCustomizer jackson2JsonRSocketStrategyCustomizer(ObjectMapper objectMapper) { return (strategy) -> { strategy.decoder( new org.springframework.http.codec.json.Jackson2JsonDecoder(objectMapper, SUPPORTED_TYPES)); strategy.encoder( new org.springframework.http.codec.json.Jackson2JsonEncoder(objectMapper, SUPPORTED_TYPES));
}; } } } static class NoJacksonOrJackson2Preferred extends AnyNestedCondition { NoJacksonOrJackson2Preferred() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper") static class NoJackson { } @ConditionalOnProperty(name = "spring.rsocket.preferred-mapper", havingValue = "jackson2") static class Jackson2Preferred { } } }
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketStrategiesAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public List<Map<String, String>> select() { List<Map<String, String>> results = new ArrayList<>(); try { Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); statement.executeQuery("SELECT * FROM student"); connection.commit(); } catch (Exception e) { throw new IllegalStateException(e); } return results; } @RequestMapping("/rollback") public List<Map<String, String>> rollback() { List<Map<String, String>> results = new ArrayList<>(); try (Connection connection = dataSource.getConnection()) { connection.rollback();
} catch (Exception e) { throw new IllegalStateException(e); } return results; } @RequestMapping("/query-error") public void error() { try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.execute("SELECT UNDEFINED()"); } catch (Exception ignored) { } } }
repos\tutorials-master\spring-boot-modules\spring-boot-3-observation\src\main\java\com\baeldung\p6spy\controllers\JDBCController.java
2
请完成以下Java代码
public CreateMatchInvoicePlan createMatchInvoice(@NonNull final CreateMatchInvoiceRequest request) { return createMatchInvoiceCommand(request).execute(); } public CreateMatchInvoicePlan createMatchInvoiceSimulation(@NonNull final CreateMatchInvoiceRequest request) { return createMatchInvoiceCommand(request).createPlan(); } private CreateMatchInvoiceCommand createMatchInvoiceCommand(final @NonNull CreateMatchInvoiceRequest request) { return CreateMatchInvoiceCommand.builder() .orderCostService(this) .matchInvoiceService(matchInvoiceService) .invoiceBL(invoiceBL) .inoutBL(inoutBL) .moneyService(moneyService) .request(request) .build(); } public Money getInvoiceLineOpenAmt(InvoiceAndLineId invoiceAndLineId) { final I_C_InvoiceLine invoiceLine = invoiceBL.getLineById(invoiceAndLineId); return getInvoiceLineOpenAmt(invoiceLine); } public Money getInvoiceLineOpenAmt(I_C_InvoiceLine invoiceLine) { final InvoiceId invoiceId = InvoiceId.ofRepoId(invoiceLine.getC_Invoice_ID()); final I_C_Invoice invoice = invoiceBL.getById(invoiceId); Money openAmt = Money.of(invoiceLine.getLineNetAmt(), CurrencyId.ofRepoId(invoice.getC_Currency_ID())); final Money matchedAmt = matchInvoiceService.getCostAmountMatched(InvoiceAndLineId.ofRepoId(invoiceId, invoiceLine.getC_InvoiceLine_ID())).orElse(null); if (matchedAmt != null) { openAmt = openAmt.subtract(matchedAmt); } return openAmt; } public void cloneAllByOrderId( @NonNull final OrderId orderId, @NonNull final OrderCostCloneMapper mapper) { final List<OrderCost> originalOrderCosts = orderCostRepository.getByOrderId(orderId);
final ImmutableList<OrderCost> clonedOrderCosts = originalOrderCosts.stream() .map(originalOrderCost -> originalOrderCost.copy(mapper)) .collect(ImmutableList.toImmutableList()); orderCostRepository.saveAll(clonedOrderCosts); } public void updateOrderCostsOnOrderLineChanged(final OrderCostDetailOrderLinePart orderLineInfo) { orderCostRepository.changeByOrderLineId( orderLineInfo.getOrderLineId(), orderCost -> { orderCost.updateOrderLineInfoIfApplies(orderLineInfo, moneyService::getStdPrecision, uomConversionBL); updateCreatedOrderLineIfAny(orderCost); }); } private void updateCreatedOrderLineIfAny(@NonNull final OrderCost orderCost) { if (orderCost.getCreatedOrderLineId() == null) { return; } CreateOrUpdateOrderLineFromOrderCostCommand.builder() .orderBL(orderBL) .moneyService(moneyService) .orderCost(orderCost) .build() .execute(); } public void deleteByCreatedOrderLineId(@NonNull final OrderAndLineId createdOrderLineId) { orderCostRepository.deleteByCreatedOrderLineId(createdOrderLineId); } public boolean isCostGeneratedOrderLine(@NonNull final OrderLineId orderLineId) { return orderCostRepository.hasCostsByCreatedOrderLineIds(ImmutableSet.of(orderLineId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostService.java
1
请完成以下Java代码
public int getIMP_RequestHandlerType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_IMP_RequestHandlerType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\requesthandler\model\X_IMP_RequestHandler.java
1
请完成以下Java代码
public int successfullyAttacked(int incomingDamage, String damageType) throws Exception { // do things if (incomingDamage < 0) { throw new IllegalArgumentException ("Cannot cause negative damage"); } return 0; } public String getHeroName() { return heroName; } public void setHeroName(String heroName) { this.heroName = heroName; } public String getUniquePower() { return uniquePower; } public void setUniquePower(String uniquePower) { this.uniquePower = uniquePower; }
public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } public int getDefense() { return defense; } public void setDefense(int defense) { this.defense = defense; } }
repos\tutorials-master\core-java-modules\core-java-documentation\src\main\java\com\baeldung\javadoc\SuperHero.java
1
请完成以下Java代码
protected boolean commitNative(final boolean throwException) throws SQLException { // // Check if we can commit String commitDetailMsg = null; final TrxStatus trxStatusCurrent = getTrxStatus(); if (trxStatusCurrent == TrxStatus.NEW) { // it's OK to just do nothing commitDetailMsg = "empty"; } else { if (getPlainTrxManager().isFailCommitIfTrxNotStarted()) { assertActive("Transaction shall be started before"); } } // Clear all savepoints activeSavepoints.clear(); setTrxStatus(TrxStatus.COMMIT, commitDetailMsg); return true; } @Override protected boolean closeNative() { // Assume that at this point the transaction is no longer active because it was never active or because it was commit/rollback first. assertNotActive("Transaction shall not be active at this point"); if (!activeSavepoints.isEmpty()) { throw new TrxException("Inconsistent transaction state: We were asked for close() but we still have active savepoints" + "\n Trx: " + this + "\n Active savepoints: " + activeSavepoints); } setTrxStatus(TrxStatus.CLOSED); return true; } protected final void assertActive(final String errmsg) { assertActive(true, errmsg); } public List<ITrxSavepoint> getActiveSavepoints() { return ImmutableList.copyOf(activeSavepoints); } protected final void assertNotActive(final String errmsg) { assertActive(false, errmsg); } protected void assertActive(final boolean activeExpected, final String errmsg) { final boolean activeActual = isActive(); if (activeActual != activeExpected) { final String errmsgToUse = "Inconsistent transaction state: " + errmsg;
throw new TrxException(errmsgToUse + "\n Expected active: " + activeExpected + "\n Actual active: " + activeActual + "\n Trx: " + this); } } private TrxStatus getTrxStatus() { return trxStatus; } private void setTrxStatus(final TrxStatus trxStatus) { final String detailMsg = null; setTrxStatus(trxStatus, detailMsg); } private void setTrxStatus(final TrxStatus trxStatus, @Nullable final String detailMsg) { final TrxStatus trxStatusOld = this.trxStatus; this.trxStatus = trxStatus; // Log it if (debugLog != null) { final StringBuilder msg = new StringBuilder(); msg.append(trxStatusOld).append("->").append(trxStatus); if (!Check.isEmpty(detailMsg, true)) { msg.append(" (").append(detailMsg).append(")"); } logTrxAction(msg.toString()); } } private void logTrxAction(final String message) { if (debugLog == null) { return; } debugLog.add(message); logger.info("{}: trx action: {}", getTrxName(), message); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\PlainTrx.java
1
请完成以下Java代码
public void broadcastToChildren(TbActorId parent, TbActorMsg msg) { broadcastToChildren(parent, msg, false); } @Override public void broadcastToChildren(TbActorId parent, TbActorMsg msg, boolean highPriority) { broadcastToChildren(parent, id -> true, msg, highPriority); } @Override public void broadcastToChildren(TbActorId parent, Predicate<TbActorId> childFilter, TbActorMsg msg) { broadcastToChildren(parent, childFilter, msg, false); } private void broadcastToChildren(TbActorId parent, Predicate<TbActorId> childFilter, TbActorMsg msg, boolean highPriority) { Set<TbActorId> children = parentChildMap.get(parent); if (children != null) { children.stream().filter(childFilter).forEach(id -> { try { tell(id, msg, highPriority); } catch (TbActorNotRegisteredException e) { log.warn("Actor is missing for {}", id); } }); } } @Override public List<TbActorId> filterChildren(TbActorId parent, Predicate<TbActorId> childFilter) { Set<TbActorId> children = parentChildMap.get(parent); if (children != null) { return children.stream().filter(childFilter).collect(Collectors.toList()); } else { return Collections.emptyList(); } } @Override public void stop(TbActorRef actorRef) { stop(actorRef.getActorId()); } @Override public void stop(TbActorId actorId) { Set<TbActorId> children = parentChildMap.remove(actorId); if (children != null) {
for (TbActorId child : children) { stop(child); } } parentChildMap.values().forEach(parentChildren -> parentChildren.remove(actorId)); TbActorMailbox mailbox = actors.remove(actorId); if (mailbox != null) { mailbox.destroy(null); } } @Override public void stop() { dispatchers.values().forEach(dispatcher -> { dispatcher.getExecutor().shutdown(); try { dispatcher.getExecutor().awaitTermination(3, TimeUnit.SECONDS); } catch (InterruptedException e) { log.warn("[{}] Failed to stop dispatcher", dispatcher.getDispatcherId(), e); } }); if (scheduler != null) { scheduler.shutdownNow(); } actors.clear(); } }
repos\thingsboard-master\common\actor\src\main\java\org\thingsboard\server\actors\DefaultTbActorSystem.java
1
请在Spring Boot框架中完成以下Java代码
public class ParametersDAO extends AbstractParametersDAO { @Override public IParameterPO newParameterPO(final Object parent, String parameterTable) { final Properties ctx = InterfaceWrapperHelper.getCtx(parent); final String trxName = InterfaceWrapperHelper.getTrxName(parent); final PO po = new GenericPO(parameterTable, ctx, 0, trxName); final IParameterPO paramPO = InterfaceWrapperHelper.create(po, IParameterPO.class); final int recordId = InterfaceWrapperHelper.getId(parent); final String tableName = InterfaceWrapperHelper.getModelTableName(parent); final String parentLinkColumnName = tableName + "_ID"; InterfaceWrapperHelper.setValue(paramPO, parentLinkColumnName, recordId); return paramPO; } @Override @Cached public List<IParameterPO> retrieveParamPOs( final @CacheCtx Properties ctx, final String parentTable, final int parentId, final String parameterTable,
final @CacheIgnore String trxName) { final String wc = parentTable + "_ID=?"; final int[] ids = new Query(ctx, parameterTable, wc, trxName) .setParameters(parentId) .getIDs(); final List<IParameterPO> result = new ArrayList<IParameterPO>(); for (final int id : ids) { final GenericPO po = new GenericPO(parameterTable, ctx, id, trxName); final IParameterPO paramPO = InterfaceWrapperHelper.create(po, IParameterPO.class); result.add(paramPO); } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\ParametersDAO.java
2
请在Spring Boot框架中完成以下Java代码
public String readJsonString() { try { String json = "{\"name\":\"mrbird\",\"age\":26}"; JsonNode node = this.mapper.readTree(json); String name = node.get("name").asText(); int age = node.get("age").asInt(); return name + " " + age; } catch (Exception e) { e.printStackTrace(); } return null; } @RequestMapping("readjsonasobject") @ResponseBody public String readJsonAsObject() { try { String json = "{\"userName\":\"mrbird\"}"; User user = mapper.readValue(json, User.class); String name = user.getUserName(); return name; } catch (Exception e) { e.printStackTrace(); } return null; } @RequestMapping("formatobjecttojsonstring") @ResponseBody public String formatObjectToJsonString() { try { User user = new User(); user.setUserName("mrbird"); user.setAge(26); user.setPassword("123456");
user.setBirthday(new Date()); String jsonStr = mapper.writeValueAsString(user); return jsonStr; } catch (Exception e) { e.printStackTrace(); } return null; } @RequestMapping("updateuser") @ResponseBody public int updateUser(@RequestBody List<User> list) { return list.size(); } @RequestMapping("customize") @ResponseBody public String customize() throws JsonParseException, JsonMappingException, IOException { String jsonStr = "[{\"userName\":\"mrbird\",\"age\":26},{\"userName\":\"scott\",\"age\":27}]"; JavaType type = mapper.getTypeFactory().constructParametricType(List.class, User.class); List<User> list = mapper.readValue(jsonStr, type); String msg = ""; for (User user : list) { msg += user.getUserName(); } return msg; } }
repos\SpringAll-master\18.Spring-Boot-Jackson\src\main\java\com\example\controller\TestJsonController.java
2
请完成以下Java代码
public String getByteArrayValueId() { return byteArrayField.getByteArrayId(); } public void setByteArrayValueId(String byteArrayId) { byteArrayField.setByteArrayId(byteArrayId); } @Override public byte[] getByteArrayValue() { return byteArrayField.getByteArrayValue(); } @Override public void setByteArrayValue(byte[] bytes) { byteArrayField.setByteArrayValue(bytes); } public void setValue(TypedValue typedValue) { typedValueField.setValue(typedValue); } public String getSerializerName() { return typedValueField.getSerializerName(); } public void setSerializerName(String serializerName) { typedValueField.setSerializerName(serializerName); } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId;
} public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public void delete() { byteArrayField.deleteByteArrayValue(); Context .getCommandContext() .getDbEntityManager() .delete(this); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInputInstanceEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class MoveDeadLetterJobToExecutableJobCmd implements Command<Job>, Serializable { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LoggerFactory.getLogger(MoveDeadLetterJobToExecutableJobCmd.class); protected JobServiceConfiguration jobServiceConfiguration; protected String jobId; protected int retries; public MoveDeadLetterJobToExecutableJobCmd(String jobId, int retries, JobServiceConfiguration jobServiceConfiguration) { this.jobId = jobId; this.retries = retries; this.jobServiceConfiguration = jobServiceConfiguration; } @Override public Job execute(CommandContext commandContext) { if (jobId == null) { throw new FlowableIllegalArgumentException("jobId and job is null"); }
DeadLetterJobEntity job = jobServiceConfiguration.getDeadLetterJobEntityManager().findById(jobId); if (job == null) { throw new JobNotFoundException(jobId); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Moving deadletter job to executable job table {}", job.getId()); } return jobServiceConfiguration.getJobManager().moveDeadLetterJobToExecutableJob(job, retries); } public String getJobId() { return jobId; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\MoveDeadLetterJobToExecutableJobCmd.java
2
请在Spring Boot框架中完成以下Java代码
public class ShipperType extends BusinessEntityType { @XmlElement(name = "ShipperExtension", namespace = "http://erpel.at/schemas/1p0/documents/ext") protected ShipperExtensionType shipperExtension; /** * Gets the value of the shipperExtension property. * * @return * possible object is * {@link ShipperExtensionType } * */ public ShipperExtensionType getShipperExtension() {
return shipperExtension; } /** * Sets the value of the shipperExtension property. * * @param value * allowed object is * {@link ShipperExtensionType } * */ public void setShipperExtension(ShipperExtensionType value) { this.shipperExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ShipperType.java
2
请在Spring Boot框架中完成以下Java代码
public DeviceMapping updated(OffsetDateTime updated) { this.updated = updated; return this; } /** * Der Zeitstempel der letzten Änderung * @return updated **/ @Schema(example = "2020-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getUpdated() { return updated; } public void setUpdated(OffsetDateTime updated) { this.updated = updated; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeviceMapping deviceMapping = (DeviceMapping) o; return Objects.equals(this._id, deviceMapping._id) && Objects.equals(this.serialNumber, deviceMapping.serialNumber) && Objects.equals(this.updated, deviceMapping.updated); } @Override public int hashCode() { return Objects.hash(_id, serialNumber, updated); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class DeviceMapping {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" serialNumber: ").append(toIndentedString(serialNumber)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceMapping.java
2
请完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean isFallbackToDefaultTenant() { return fallbackToDefaultTenant; } public void setFallbackToDefaultTenant(boolean fallbackToDefaultTenant) { this.fallbackToDefaultTenant = fallbackToDefaultTenant; } public boolean isForceDMN11() { return forceDMN11; } public void setForceDMN11(boolean forceDMN11) { this.forceDMN11 = forceDMN11; } public boolean isDisableHistory() { return disableHistory; }
public void setDisableHistory(boolean disableHistory) { this.disableHistory = disableHistory; } public DmnElement getDmnElement() { return dmnElement; } public void setDmnElement(DmnElement dmnElement) { this.dmnElement = dmnElement; } public DecisionExecutionAuditContainer getDecisionExecution() { return decisionExecution; } public void setDecisionExecution(DecisionExecutionAuditContainer decisionExecution) { this.decisionExecution = decisionExecution; } }
repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\ExecuteDecisionContext.java
1
请完成以下Java代码
public class Sentry extends CaseElement { public static final String TRIGGER_MODE_DEFAULT = "default"; public static final String TRIGGER_MODE_ON_EVENT = "onEvent"; protected String triggerMode; protected List<SentryOnPart> onParts = new ArrayList<>(); protected SentryIfPart sentryIfPart; public boolean isDefaultTriggerMode() { return triggerMode == null || TRIGGER_MODE_DEFAULT.equals(triggerMode); } public boolean isOnEventTriggerMode() { return TRIGGER_MODE_ON_EVENT.equals(triggerMode); } public String getTriggerMode() { return triggerMode; } public void setTriggerMode(String triggerMode) { this.triggerMode = triggerMode;
} public List<SentryOnPart> getOnParts() { return onParts; } public void setOnParts(List<SentryOnPart> onParts) { this.onParts = onParts; } public void addSentryOnPart(SentryOnPart sentryOnPart) { onParts.add(sentryOnPart); } public SentryIfPart getSentryIfPart() { return sentryIfPart; } public void setSentryIfPart(SentryIfPart sentryIfPart) { this.sentryIfPart = sentryIfPart; } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Sentry.java
1
请完成以下Java代码
public class CoreSynonymDictionaryEx { static CommonSynonymDictionaryEx dictionary; static { try { dictionary = CommonSynonymDictionaryEx.create(IOUtil.newInputStream(HanLP.Config.CoreSynonymDictionaryDictionaryPath)); } catch (Exception e) { logger.severe("载入核心同义词词典失败"); throw new IllegalArgumentException(e); } } public static Long[] get(String key) { return dictionary.get(key); } /** * 语义距离 * @param itemA * @param itemB * @return */ public static long distance(CommonSynonymDictionary.SynonymItem itemA, CommonSynonymDictionary.SynonymItem itemB) { return itemA.distance(itemB); } /** * 将分词结果转换为同义词列表 * @param sentence 句子 * @param withUndefinedItem 是否保留词典中没有的词语 * @return */ public static List<Long[]> convert(List<Term> sentence, boolean withUndefinedItem) { List<Long[]> synonymItemList = new ArrayList<Long[]>(sentence.size()); for (Term term : sentence) { // 除掉停用词 if (term.nature == null) continue; String nature = term.nature.toString(); char firstChar = nature.charAt(0); switch (firstChar) { case 'm': { if (!TextUtility.isAllChinese(term.word)) continue; }break; case 'w':
{ continue; } } // 停用词 if (CoreStopWordDictionary.contains(term.word)) continue; Long[] item = get(term.word); // logger.trace("{} {}", wordResult.word, Arrays.toString(item)); if (item == null) { if (withUndefinedItem) { item = new Long[]{Long.MAX_VALUE / 3}; synonymItemList.add(item); } } else { synonymItemList.add(item); } } return synonymItemList; } /** * 获取语义标签 * @return */ public static long[] getLexemeArray(List<CommonSynonymDictionary.SynonymItem> synonymItemList) { long[] array = new long[synonymItemList.size()]; int i = 0; for (CommonSynonymDictionary.SynonymItem item : synonymItemList) { array[i++] = item.entry.id; } return array; } public long distance(List<CommonSynonymDictionary.SynonymItem> synonymItemListA, List<CommonSynonymDictionary.SynonymItem> synonymItemListB) { return EditDistance.compute(synonymItemListA, synonymItemListB); } public long distance(long[] arrayA, long[] arrayB) { return EditDistance.compute(arrayA, arrayB); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CoreSynonymDictionaryEx.java
1
请完成以下Java代码
public boolean isAutoStartup() { return this.autoStartup; } public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; } @Override public void onMessage(Message message) { if (this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent(new BrokerEvent(this, message.getMessageProperties())); } else { if (logger.isWarnEnabled()) { logger.warn("No event publisher available for " + message + "; if the BrokerEventListener " + "is not defined as a bean, you must provide an ApplicationEventPublisher"); } } } @Override public void onCreate(@Nullable Connection connection) { this.bindingsFailedException = null; TopicExchange exchange = new TopicExchange("amq.rabbitmq.event");
try { this.admin.declareQueue(this.eventQueue); Arrays.stream(this.eventKeys).forEach(k -> { Binding binding = BindingBuilder.bind(this.eventQueue).to(exchange).with(k); this.admin.declareBinding(binding); }); } catch (Exception e) { logger.error("failed to declare event queue/bindings - is the plugin enabled?", e); this.bindingsFailedException = e; } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\core\BrokerEventListener.java
1
请完成以下Java代码
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { return loadDeferredContext(requestResponseHolder.getRequest()).get(); } @Override public DeferredSecurityContext loadDeferredContext(HttpServletRequest request) { Supplier<SecurityContext> supplier = () -> getContext(request); return new SupplierDeferredSecurityContext(supplier, this.securityContextHolderStrategy); } private SecurityContext getContext(HttpServletRequest request) { return (SecurityContext) request.getAttribute(this.requestAttributeName); } @Override public void saveContext(SecurityContext context, HttpServletRequest request,
@Nullable HttpServletResponse response) { request.setAttribute(this.requestAttributeName, context); } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\RequestAttributeSecurityContextRepository.java
1
请完成以下Java代码
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * PerformanceType AD_Reference_ID=540689 * Reference name: R_Request.PerformanceType */ public static final int PERFORMANCETYPE_AD_Reference_ID=540689; /** Liefer Performance = LP */ public static final String PERFORMANCETYPE_LieferPerformance = "LP"; /** Quality Performance = QP */ public static final String PERFORMANCETYPE_QualityPerformance = "QP"; /** Set PerformanceType. @param PerformanceType PerformanceType */ @Override public void setPerformanceType (java.lang.String PerformanceType) { set_Value (COLUMNNAME_PerformanceType, PerformanceType); } /** Get PerformanceType. @return PerformanceType */ @Override public java.lang.String getPerformanceType () { return (java.lang.String)get_Value(COLUMNNAME_PerformanceType);
} /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inout\model\X_M_QualityNote.java
1
请在Spring Boot框架中完成以下Java代码
public void setSubsidiaryRisk(String value) { this.subsidiaryRisk = value; } /** * Gets the value of the tunnelRestrictionCode property. * * @return * possible object is * {@link String } * */ public String getTunnelRestrictionCode() { return tunnelRestrictionCode; } /** * Sets the value of the tunnelRestrictionCode property. * * @param value * allowed object is * {@link String } * */ public void setTunnelRestrictionCode(String value) { this.tunnelRestrictionCode = value; } /** * Gets the value of the hazardousWeight property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getHazardousWeight() { return hazardousWeight; } /** * Sets the value of the hazardousWeight property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setHazardousWeight(BigDecimal value) { this.hazardousWeight = value; } /** * Gets the value of the netWeight property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getNetWeight() { return netWeight; } /** * Sets the value of the netWeight property.
* * @param value * allowed object is * {@link BigDecimal } * */ public void setNetWeight(BigDecimal value) { this.netWeight = value; } /** * Gets the value of the factor property. * */ public int getFactor() { return factor; } /** * Sets the value of the factor property. * */ public void setFactor(int value) { this.factor = value; } /** * Gets the value of the notOtherwiseSpecified property. * * @return * possible object is * {@link String } * */ public String getNotOtherwiseSpecified() { return notOtherwiseSpecified; } /** * Sets the value of the notOtherwiseSpecified property. * * @param value * allowed object is * {@link String } * */ public void setNotOtherwiseSpecified(String value) { this.notOtherwiseSpecified = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Hazardous.java
2
请在Spring Boot框架中完成以下Java代码
public class FlywayMigrationInitializer implements InitializingBean, Ordered { private final Flyway flyway; private final @Nullable FlywayMigrationStrategy migrationStrategy; private int order; /** * Create a new {@link FlywayMigrationInitializer} instance. * @param flyway the flyway instance */ public FlywayMigrationInitializer(Flyway flyway) { this(flyway, null); } /** * Create a new {@link FlywayMigrationInitializer} instance. * @param flyway the flyway instance * @param migrationStrategy the migration strategy or {@code null} */ public FlywayMigrationInitializer(Flyway flyway, @Nullable FlywayMigrationStrategy migrationStrategy) { Assert.notNull(flyway, "'flyway' must not be null"); this.flyway = flyway; this.migrationStrategy = migrationStrategy; }
@Override public void afterPropertiesSet() throws Exception { if (this.migrationStrategy != null) { this.migrationStrategy.migrate(this.flyway); } else { try { this.flyway.migrate(); } catch (NoSuchMethodError ex) { // Flyway < 7.0 this.flyway.getClass().getMethod("migrate").invoke(this.flyway); } } } @Override public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } }
repos\spring-boot-4.0.1\module\spring-boot-flyway\src\main\java\org\springframework\boot\flyway\autoconfigure\FlywayMigrationInitializer.java
2
请完成以下Java代码
public String getExternalId() { return externalId; } @Override public int getC_Async_Batch_ID() { return C_Async_Batch_ID; } public void setC_Async_Batch_ID(final int C_Async_Batch_ID) { this.C_Async_Batch_ID = C_Async_Batch_ID; } public String setExternalId(String externalId) { return this.externalId = externalId; } @Override public int getC_Incoterms_ID() { return C_Incoterms_ID; } public void setC_Incoterms_ID(final int C_Incoterms_ID)
{ this.C_Incoterms_ID = C_Incoterms_ID; } @Override public String getIncotermLocation() { return incotermLocation; } public void setIncotermLocation(final String incotermLocation) { this.incotermLocation = incotermLocation; } @Override public InputDataSourceId getAD_InputDataSource_ID() { return inputDataSourceId;} public void setAD_InputDataSource_ID(final InputDataSourceId inputDataSourceId){this.inputDataSourceId = inputDataSourceId;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceHeaderImpl.java
1
请完成以下Java代码
public void setMandateReference (final java.lang.String MandateReference) { set_Value (COLUMNNAME_MandateReference, MandateReference); } @Override public java.lang.String getMandateReference() { return get_ValueAsString(COLUMNNAME_MandateReference); } /** * MandateStatus AD_Reference_ID=541976 * Reference name: Mandat Status */ public static final int MANDATESTATUS_AD_Reference_ID=541976; /** FirstTime = F */ public static final String MANDATESTATUS_FirstTime = "F"; /** Recurring = R */
public static final String MANDATESTATUS_Recurring = "R"; /** LastTime = L */ public static final String MANDATESTATUS_LastTime = "L"; @Override public void setMandateStatus (final java.lang.String MandateStatus) { set_Value (COLUMNNAME_MandateStatus, MandateStatus); } @Override public java.lang.String getMandateStatus() { return get_ValueAsString(COLUMNNAME_MandateStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount_DirectDebitMandate.java
1
请完成以下Java代码
public void setDelegate(final MutableComboBoxModel delegateNew) { if (this.delegate == delegateNew) { // nothing changed return; } // Unregister listeners on old lookup final MutableComboBoxModel delegateOld = this.delegate; if (delegateOld != null) { for (ListDataListener l : listenerList.getListeners(ListDataListener.class)) { delegateOld.removeListDataListener(l); } } // // Setup new Lookup this.delegate = delegateNew; // Register listeners on new lookup if (this.delegate != null) { for (ListDataListener l : listenerList.getListeners(ListDataListener.class)) { this.delegate.addListDataListener(l); } } } @Override public void addListDataListener(final ListDataListener l) { listenerList.add(ListDataListener.class, l); if (delegate != null) { delegate.addListDataListener(l); } } @Override public void removeListDataListener(final ListDataListener l) { listenerList.remove(ListDataListener.class, l); if (delegate != null) { delegate.removeListDataListener(l); }
} @Override public int getSize() { return getDelegateToUse().getSize(); } @Override public Object getElementAt(int index) { return getDelegateToUse().getElementAt(index); } @Override public void setSelectedItem(Object anItem) { getDelegateToUse().setSelectedItem(anItem); } @Override public Object getSelectedItem() { return getDelegateToUse().getSelectedItem(); } @Override public void addElement(Object obj) { getDelegateToUse().addElement(obj); } @Override public void removeElement(Object obj) { getDelegateToUse().removeElement(obj); } @Override public void insertElementAt(Object obj, int index) { getDelegateToUse().insertElementAt(obj, index); } @Override public void removeElementAt(int index) { getDelegateToUse().removeElementAt(index); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\MutableComboBoxModelProxy.java
1
请完成以下Java代码
public Builder setPrintProcessId(final AdProcessId printProcessId) { _printProcessId = printProcessId; return this; } private AdProcessId getPrintProcessId() { return _printProcessId; } private boolean isCloneEnabled() { return isCloneEnabled(_tableName); } private static boolean isCloneEnabled(@Nullable final Optional<String> tableName) { if (tableName == null || !tableName.isPresent()) { return false; } return CopyRecordFactory.isEnabledForTableName(tableName.get()); }
public DocumentQueryOrderByList getDefaultOrderBys() { return getFieldBuilders() .stream() .filter(DocumentFieldDescriptor.Builder::isDefaultOrderBy) .sorted(Ordering.natural().onResultOf(DocumentFieldDescriptor.Builder::getDefaultOrderByPriority)) .map(field -> DocumentQueryOrderBy.byFieldName(field.getFieldName(), field.isDefaultOrderByAscending())) .collect(DocumentQueryOrderByList.toDocumentQueryOrderByList()); } public Builder queryIfNoFilters(final boolean queryIfNoFilters) { this.queryIfNoFilters = queryIfNoFilters; return this; } public Builder notFoundMessages(@Nullable final NotFoundMessages notFoundMessages) { this.notFoundMessages = notFoundMessages; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentEntityDescriptor.java
1
请完成以下Java代码
protected void checkForCreateTimeMisconfiguration() { if (isUseCreateTimeEnabled() && isOrderByCreateTimeEnabled()) { throw new SpringExternalTaskClientException( "Both \"useCreateTime\" and \"orderByCreateTime\" are enabled. Please use one or the other"); } } @Autowired(required = false) public void setRequestInterceptors(List<ClientRequestInterceptor> requestInterceptors) { if (requestInterceptors != null) { this.requestInterceptors.addAll(requestInterceptors); LOG.requestInterceptorsFound(this.requestInterceptors.size()); } } @Autowired(required = false) public void setClientBackoffStrategy(BackoffStrategy backoffStrategy) { this.backoffStrategy = backoffStrategy; LOG.backoffStrategyFound(); } @Override public Class<ExternalTaskClient> getObjectType() { return ExternalTaskClient.class; } @Override public boolean isSingleton() { return true; } @Override public void afterPropertiesSet() throws Exception { } public ClientConfiguration getClientConfiguration() { return clientConfiguration; } public void setClientConfiguration(ClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } public List<ClientRequestInterceptor> getRequestInterceptors() { return requestInterceptors; }
protected void close() { if (client != null) { client.stop(); } } @Autowired(required = false) protected void setPropertyConfigurer(PropertySourcesPlaceholderConfigurer configurer) { PropertySources appliedPropertySources = configurer.getAppliedPropertySources(); propertyResolver = new PropertySourcesPropertyResolver(appliedPropertySources); } protected String resolve(String property) { if (propertyResolver == null) { return property; } if (property != null) { return propertyResolver.resolvePlaceholders(property); } else { return null; } } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\ClientFactory.java
1
请完成以下Java代码
public Class<Date> getValueClass() { return java.util.Date.class; } @Override public String getExpressionString() { return EXPRESSION_STRING; } @Override public String getFormatedExpressionString() { return EXPRESSION_STRING; } @Override public Set<CtxName> getParameters() { return ImmutableSet.of(); } @Override public Date evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{ return de.metas.common.util.time.SystemTime.asDate(); } @Override public boolean isNoResult(final Object result) { return result == null; } @Override public boolean isNullExpression() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\SysDateDateExpression.java
1
请完成以下Java代码
public static class POInfoMap { private final ImmutableMap<AdTableId, POInfo> byTableId; private final ImmutableMap<String, POInfo> byTableNameUC; public POInfoMap(@NonNull final List<POInfo> poInfos) { byTableId = Maps.uniqueIndex(poInfos, POInfo::getAdTableId); byTableNameUC = Maps.uniqueIndex(poInfos, POInfo::getTableNameUC); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("size", byTableId.size()) .toString(); } @Nullable public POInfo getByTableIdOrNull(@NonNull final AdTableId tableId) { return byTableId.get(tableId); } @NonNull public POInfo getByTableId(@NonNull final AdTableId tableId) { final POInfo poInfo = getByTableIdOrNull(tableId); if (poInfo == null) { throw new AdempiereException("No POInfo found for " + tableId); } return poInfo; } @Nullable public POInfo getByTableNameOrNull(@NonNull final String tableName) { return byTableNameUC.get(tableName.toUpperCase());
} @NonNull public POInfo getByTableName(@NonNull final String tableName) { final POInfo poInfo = getByTableNameOrNull(tableName); if (poInfo == null) { throw new AdempiereException("No POInfo found for " + tableName); } return poInfo; } public Stream<POInfo> stream() {return byTableId.values().stream();} public int size() {return byTableId.size();} public ImmutableCollection<POInfo> toCollection() {return byTableId.values();} } } // POInfo
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POInfo.java
1
请完成以下Java代码
public String getHeader(String field) { Map<String, String> headers = getHeaders(); if (headers != null) { return headers.get(field); } else { return null; } } public Map<String, String> getHeaders() { return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_HEADERS); } public Q contentType(String contentType) { return header(HttpBaseRequest.HEADER_CONTENT_TYPE, contentType); } public String getContentType() { return getHeader(HttpBaseRequest.HEADER_CONTENT_TYPE); } @SuppressWarnings("unchecked") public Q payload(String payload) { setRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_PAYLOAD, payload); return (Q) this; } public String getPayload() { return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_PAYLOAD); } public Q get() { return method(HttpGet.METHOD_NAME); } public Q post() { return method(HttpPost.METHOD_NAME); } public Q put() { return method(HttpPut.METHOD_NAME); } public Q delete() { return method(HttpDelete.METHOD_NAME); } public Q patch() { return method(HttpPatch.METHOD_NAME); } public Q head() { return method(HttpHead.METHOD_NAME); } public Q options() { return method(HttpOptions.METHOD_NAME); } public Q trace() { return method(HttpTrace.METHOD_NAME); } public Map<String, Object> getConfigOptions() {
return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG); } public Object getConfigOption(String field) { Map<String, Object> config = getConfigOptions(); if (config != null) { return config.get(field); } return null; } @SuppressWarnings("unchecked") public Q configOption(String field, Object value) { if (field == null || field.isEmpty() || value == null) { LOG.ignoreConfig(field, value); } else { Map<String, Object> config = getConfigOptions(); if (config == null) { config = new HashMap<>(); setRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG, config); } config.put(field, value); } return (Q) this; } }
repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\AbstractHttpRequest.java
1
请完成以下Java代码
public Tag id(Long id) { this.id = id; return this; } /** * Get id * @return id **/ @ApiModelProperty(value = "") public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Tag name(String name) { this.name = name; return this; } /** * Get name * @return name **/ @ApiModelProperty(value = "") public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Tag tag = (Tag) o; return Objects.equals(this.id, tag.id) && Objects.equals(this.name, tag.name); } @Override public int hashCode() { return Objects.hash(id, name);
} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Tag {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).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\Tag.java
1
请完成以下Java代码
public class DeleteProcessPayload implements Payload { private String id; private String processInstanceId; private String reason; public DeleteProcessPayload() { this.id = UUID.randomUUID().toString(); } public DeleteProcessPayload(String processInstanceId, String reason) { this(); this.processInstanceId = processInstanceId; this.reason = reason; } @Override public String getId() { return id; } public String getProcessInstanceId() {
return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } }
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\DeleteProcessPayload.java
1
请在Spring Boot框架中完成以下Java代码
private Candidate createCandidate(final AttributesChangedEvent event, final CandidateType type) { final BigDecimal qty; final AttributesKeyWithASI attributes; if (CandidateType.ATTRIBUTES_CHANGED_FROM.equals(type)) { qty = event.getQty().negate(); attributes = event.getOldStorageAttributes(); } else if (CandidateType.ATTRIBUTES_CHANGED_TO.equals(type)) { qty = event.getQty(); attributes = event.getNewStorageAttributes(); } else { throw new AdempiereException("Invalid type: " + type); // really shall not happen } return Candidate.builderForEventDescriptor(event.getEventDescriptor()) .type(type) .materialDescriptor(MaterialDescriptor.builder()
.warehouseId(event.getWarehouseId()) .quantity(qty) .date(event.getDate()) .productDescriptor(toProductDescriptor(event.getProductId(), attributes)) .build()) .build(); } private static ProductDescriptor toProductDescriptor(final int productId, final AttributesKeyWithASI attributes) { return ProductDescriptor.forProductAndAttributes(productId, CoalesceUtil.coalesceNotNull(attributes.getAttributesKey(), AttributesKey.NONE), attributes.getAttributeSetInstanceId().getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\attributes\AttributesChangedEventHandler.java
2
请完成以下Java代码
public List<SingleQueryVariableValueCondition> getValueConditions() { return valueCondition.getDisjunctiveConditions(); } public String getName() { return name; } public QueryOperator getOperator() { if(operator != null) { return operator; } return QueryOperator.EQUALS; } public String getOperatorName() { return getOperator().toString(); } public Object getValue() { return value.getValue(); } public TypedValue getTypedValue() { return value; } public boolean isLocal() { return local; } public boolean isVariableNameIgnoreCase() { return variableNameIgnoreCase; } public void setVariableNameIgnoreCase(boolean variableNameIgnoreCase) {
this.variableNameIgnoreCase = variableNameIgnoreCase; } public boolean isVariableValueIgnoreCase() { return variableValueIgnoreCase; } public void setVariableValueIgnoreCase(boolean variableValueIgnoreCase) { this.variableValueIgnoreCase = variableValueIgnoreCase; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QueryVariableValue that = (QueryVariableValue) o; return local == that.local && variableNameIgnoreCase == that.variableNameIgnoreCase && variableValueIgnoreCase == that.variableValueIgnoreCase && name.equals(that.name) && value.equals(that.value) && operator == that.operator && Objects.equals(valueCondition, that.valueCondition); } @Override public int hashCode() { return Objects.hash(name, value, operator, local, valueCondition, variableNameIgnoreCase, variableValueIgnoreCase); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\QueryVariableValue.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_AD_PrintColor[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Print Color. @param AD_PrintColor_ID Color used for printing and display */ public void setAD_PrintColor_ID (int AD_PrintColor_ID) { if (AD_PrintColor_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_PrintColor_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_PrintColor_ID, Integer.valueOf(AD_PrintColor_ID)); } /** Get Print Color. @return Color used for printing and display */ public int getAD_PrintColor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validation code. @param Code Validation Code */ public void setCode (String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code. @return Validation Code */ public String getCode () { return (String)get_Value(COLUMNNAME_Code); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
} /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintColor.java
1
请完成以下Java代码
public String getHandelsregisternummer() { return handelsregisternummer; } /** * Sets the value of the handelsregisternummer property. * * @param value * allowed object is * {@link String } * */ public void setHandelsregisternummer(String value) { this.handelsregisternummer = value; } /** * Gets the value of the umsatzsteuerID property. * * @return * possible object is * {@link String } * */ public String getUmsatzsteuerID() { return umsatzsteuerID; } /** * Sets the value of the umsatzsteuerID property. * * @param value * allowed object is * {@link String } * */ public void setUmsatzsteuerID(String value) { this.umsatzsteuerID = value; } /** * Gets the value of the steuernummer property. * * @return * possible object is * {@link String } * */ public String getSteuernummer() { return steuernummer; } /** * Sets the value of the steuernummer property. * * @param value * allowed object is * {@link String } * */ public void setSteuernummer(String value) { this.steuernummer = value; } /** * Gets the value of the bankname property. * * @return * possible object is * {@link String } * */ public String getBankname() { return bankname; } /** * Sets the value of the bankname property. * * @param value * allowed object is * {@link String } * */ public void setBankname(String value) { this.bankname = value;
} /** * Gets the value of the bic property. * * @return * possible object is * {@link String } * */ public String getBIC() { return bic; } /** * Sets the value of the bic property. * * @param value * allowed object is * {@link String } * */ public void setBIC(String value) { this.bic = value; } /** * Gets the value of the iban property. * * @return * possible object is * {@link String } * */ public String getIBAN() { return iban; } /** * Sets the value of the iban property. * * @param value * allowed object is * {@link String } * */ public void setIBAN(String value) { this.iban = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnkuendigungType.java
1
请完成以下Java代码
public List<Object> next() { if (currentRow != null) { final List<Object> rowToReturn = currentRow; currentRow = null; return rowToReturn; } currentRow = retrieveNextOrNull(); if (currentRow == null) { throw new NoSuchElementException(); } return currentRow; } @Override public void remove() { throw new UnsupportedOperationException(); } private List<Object> readLine(ResultSet rs, List<String> sqlFields) throws SQLException { final List<Object> values = new ArrayList<Object>(); for (final String columnName : sqlFields) { final Object value = rs.getObject(columnName); values.add(value); } return values; } private Integer rowsCount = null; @Override public int size() { if (Check.isEmpty(sqlCount, true)) { throw new IllegalStateException("Counting is not supported"); } if (rowsCount == null) {
logger.info("SQL: {}", sqlCount); logger.info("SQL Params: {}", sqlParams); rowsCount = DB.getSQLValueEx(Trx.TRXNAME_None, sqlCount, sqlParams); logger.info("Rows Count: {}" + rowsCount); } return rowsCount; } public String getSqlSelect() { return sqlSelect; } public List<Object> getSqlParams() { if (sqlParams == null) { return Collections.emptyList(); } return sqlParams; } public String getSqlWhereClause() { return sqlWhereClause; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcExportDataSource.java
1
请完成以下Java代码
public class Book { private String name; private int releaseYear; private String isbn; @Override public String toString() { return "Book{" + "name='" + name + '\'' + ", releaseYear=" + releaseYear + ", isbn='" + isbn + '\'' + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public int getReleaseYear() { return releaseYear; } public void setReleaseYear(int releaseYear) { this.releaseYear = releaseYear; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Book(String name, int releaseYear, String isbn) { this.name = name; this.releaseYear = releaseYear; this.isbn = isbn; } }
repos\tutorials-master\core-java-modules\core-java-collections-conversions\src\main\java\com\baeldung\convertToMap\Book.java
1
请完成以下Java代码
public class DelegateExpressionTransactionDependentTaskListener implements TransactionDependentTaskListener { protected Expression expression; public DelegateExpressionTransactionDependentTaskListener(Expression expression) { this.expression = expression; } @Override public void notify( String processInstanceId, String executionId, Task task, Map<String, Object> executionVariables, Map<String, Object> customPropertiesMap ) { NoExecutionVariableScope scope = new NoExecutionVariableScope(); Object delegate = expression.getValue(scope); if (delegate instanceof TransactionDependentTaskListener) { ((TransactionDependentTaskListener) delegate).notify( processInstanceId, executionId, task, executionVariables, customPropertiesMap ); } else {
throw new ActivitiIllegalArgumentException( "Delegate expression " + expression + " did not resolve to an implementation of " + TransactionDependentTaskListener.class ); } } /** * returns the expression text for this task listener. Comes in handy if you want to check which listeners you already have. */ public String getExpressionText() { return expression.getExpressionText(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\DelegateExpressionTransactionDependentTaskListener.java
1
请在Spring Boot框架中完成以下Java代码
public class cartDao { @Autowired private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sf) { this.sessionFactory = sf; } @Transactional public Cart addCart(Cart cart) { this.sessionFactory.getCurrentSession().save(cart); return cart; } @Transactional public List<Cart> getCarts() { return this.sessionFactory.getCurrentSession().createQuery("from CART").list(); } // @Transactional // public List<Cart> getCartsByCustomerID(Integer customer_id) {
// String hql = "from CART where CART.customer_id = :customer_id"; // return this.sessionFactory.getCurrentSession() // .createQuery(hql, Cart.class) // .setParameter("customer_id", customer_id) // .list(); // } @Transactional public void updateCart(Cart cart) { this.sessionFactory.getCurrentSession().update(cart); } @Transactional public void deleteCart(Cart cart) { this.sessionFactory.getCurrentSession().delete(cart); } }
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\dao\cartDao.java
2
请在Spring Boot框架中完成以下Java代码
public HttpTracing httpTracing(Tracing tracing) { return HttpTracing.create(tracing); } /** * Creates server spans for http requests */ @Bean public Filter tracingFilter(HttpTracing httpTracing) { // 拦截请求,记录 HTTP 请求的链路信息 return TracingFilter.create(httpTracing); } // ==================== SpringMVC 相关 ==================== // @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class) 。因为 SpanCustomizingAsyncHandlerInterceptor 未提供 public 构造方法 // ==================== RabbitMQ 相关 ==================== @Bean public JmsTracing jmsTracing(Tracing tracing) { return JmsTracing.newBuilder(tracing) .remoteServiceName("demo-mq-activemq") // 远程 ActiveMQ 服务名,可自定义 .build(); }
@Bean public BeanPostProcessor activeMQBeanPostProcessor(JmsTracing jmsTracing) { return new BeanPostProcessor() { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { // 如果是 ConnectionFactory ,针对 ActiveMQ Producer 和 Consumer if (bean instanceof ConnectionFactory) { return jmsTracing.connectionFactory((ConnectionFactory) bean); } return bean; } }; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-activemq\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java
2
请完成以下Java代码
public void setM_Promotion_ID (int M_Promotion_ID) { if (M_Promotion_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, Integer.valueOf(M_Promotion_ID)); } /** Get Promotion. @return Promotion */ public int getM_Promotion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Promotion_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Promotion Line. @param M_PromotionLine_ID Promotion Line */ public void setM_PromotionLine_ID (int M_PromotionLine_ID) { if (M_PromotionLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PromotionLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionLine_ID, Integer.valueOf(M_PromotionLine_ID)); } /** Get Promotion Line. @return Promotion Line */ public int getM_PromotionLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionLine_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_M_PromotionLine.java
1
请完成以下Java代码
public String getId() { return this.id; } public Integer getVersion() { return this.version; } public String getSeparator() { return this.separator; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Qualifier qualifier = (Qualifier) o; return this.id.equals(qualifier.id) && Objects.equals(this.version, qualifier.version) && Objects.equals(this.separator, qualifier.separator); } @Override public int hashCode() { return Objects.hash(this.id, this.version, this.separator); } @Override public String toString() { return new StringJoiner(", ", Qualifier.class.getSimpleName() + "[", "]").add("id='" + this.id + "'") .add("version=" + this.version) .add("separator='" + this.separator + "'") .toString(); } } /** * Define the supported version format. */ public enum Format { /** * Original version format, i.e. {@code Major.Minor.Patch.Qualifier} using * {@code BUILD-SNAPSHOT} as the qualifier for snapshots and {@code RELEASE} for * GAs. */ V1, /** * SemVer-compliant format, i.e. {@code Major.Minor.Patch-Qualifier} using * {@code SNAPSHOT} as the qualifier for snapshots and no qualifier for GAs. */ V2 } private static final class VersionQualifierComparator implements Comparator<Qualifier> { static final String RELEASE = "RELEASE"; static final String BUILD_SNAPSHOT = "BUILD-SNAPSHOT"; static final String SNAPSHOT = "SNAPSHOT"; static final String MILESTONE = "M"; static final String RC = "RC";
static final List<String> KNOWN_QUALIFIERS = Arrays.asList(MILESTONE, RC, BUILD_SNAPSHOT, SNAPSHOT, RELEASE); @Override public int compare(Qualifier o1, Qualifier o2) { Qualifier first = (o1 != null) ? o1 : new Qualifier(RELEASE); Qualifier second = (o2 != null) ? o2 : new Qualifier(RELEASE); int qualifier = compareQualifier(first, second); return (qualifier != 0) ? qualifier : compareQualifierVersion(first, second); } private static int compareQualifierVersion(Qualifier first, Qualifier second) { Integer firstVersion = (first.getVersion() != null) ? first.getVersion() : 0; Integer secondVersion = (second.getVersion() != null) ? second.getVersion() : 0; return firstVersion.compareTo(secondVersion); } private static int compareQualifier(Qualifier first, Qualifier second) { int firstIndex = getQualifierIndex(first.getId()); int secondIndex = getQualifierIndex(second.getId()); // Unknown qualifier, alphabetic ordering if (firstIndex == -1 && secondIndex == -1) { return first.getId().compareTo(second.getId()); } else { return Integer.compare(firstIndex, secondIndex); } } private static int getQualifierIndex(String qualifier) { return (StringUtils.hasText(qualifier) ? KNOWN_QUALIFIERS.indexOf(qualifier) : 0); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\Version.java
1
请完成以下Java代码
public Builder setPublicField(final boolean publicField) { this.publicField = publicField; return this; } public boolean isPublicField() { return publicField; } private Builder setConsumed() { consumed = true; return this; } public boolean isConsumed() { return consumed; } public Builder setListNullItemCaption(@NonNull final ITranslatableString listNullItemCaption) { this.listNullItemCaption = listNullItemCaption; return this; } public Builder setEmptyFieldText(final ITranslatableString emptyFieldText) { this.emptyFieldText = emptyFieldText; return this; } public Builder trackField(final DocumentFieldDescriptor.Builder field) { documentFieldBuilder = field; return this; } public boolean isSpecialFieldToExcludeFromLayout() { return documentFieldBuilder != null && documentFieldBuilder.isSpecialFieldToExcludeFromLayout(); } public Builder setDevices(@NonNull final DeviceDescriptorsList devices) { this._devices = devices; return this;
} private DeviceDescriptorsList getDevices() { return _devices; } public Builder setSupportZoomInto(final boolean supportZoomInto) { this.supportZoomInto = supportZoomInto; return this; } private boolean isSupportZoomInto() { return supportZoomInto; } public Builder setForbidNewRecordCreation(final boolean forbidNewRecordCreation) { this.forbidNewRecordCreation = forbidNewRecordCreation; return this; } private boolean isForbidNewRecordCreation() { return forbidNewRecordCreation; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementFieldDescriptor.java
1
请完成以下Java代码
public Collection<MLocator> getData() { if (m_loader.isAlive()) { log.debug("Waiting for Loader"); try { m_loader.join(); } catch (InterruptedException ie) { log.error("Join interrupted - " + ie.getMessage()); } } return m_lookup.values(); } // getData /** * Return data as sorted ArrayList * * @param mandatory mandatory * @param onlyValidated only validated * @param onlyActive only active * @param temporary force load for temporary display * @return ArrayList of lookup values */ @Override public ArrayList<Object> getData(boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary) { // create list final Collection<MLocator> collection = getData(); final ArrayList<Object> list = new ArrayList<>(collection.size()); Iterator<MLocator> it = collection.iterator(); while (it.hasNext()) { final MLocator loc = it.next(); if (!isValid(loc)) // only valid warehouses { continue; } final NamePair locatorKNP = new KeyNamePair(loc.getM_Locator_ID(), loc.toString()); list.add(locatorKNP); } /** * Sort Data * MLocator l = new MLocator (m_ctx, 0); * if (!mandatory) * list.add (l); * Collections.sort (list, l); **/ return list; } // getArray /** * Refresh Values * * @return new size of lookup */ @Override public int refresh() { log.debug("start"); m_loader = new Loader(); m_loader.start();
try { m_loader.join(); } catch (InterruptedException ie) { } log.info("#" + m_lookup.size()); return m_lookup.size(); } // refresh @Override public String getTableName() { return I_M_Locator.Table_Name; } /** * Get underlying fully qualified Table.Column Name * * @return Table.ColumnName */ @Override public String getColumnName() { return "M_Locator.M_Locator_ID"; } // getColumnName @Override public String getColumnNameNotFQ() { return I_M_Locator.COLUMNNAME_M_Locator_ID; } } // MLocatorLookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLocatorLookup.java
1
请完成以下Java代码
public Set<ConvertiblePair> getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(String.class, Object[].class)); } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return targetType.getElementTypeDescriptor() == null || this.conversionService.canConvert(sourceType, targetType.getElementTypeDescriptor()); } @Override public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((String) source, sourceType, targetType); } private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) { Delimiter delimiter = targetType.getAnnotation(Delimiter.class); String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ",");
TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); Assert.state(elementDescriptor != null, "elementDescriptor is missing"); Object target = Array.newInstance(elementDescriptor.getType(), elements.length); for (int i = 0; i < elements.length; i++) { String sourceElement = elements[i]; Object targetElement = this.conversionService.convert(sourceElement.trim(), sourceType, elementDescriptor); Array.set(target, i, targetElement); } return target; } private String[] getElements(String source, String delimiter) { return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\DelimitedStringToArrayConverter.java
1
请完成以下Java代码
public class Customer { @Size(min = 5, max = 200) private String firstName; @Size(min = 5, max = 200) private String lastName; public Customer(@Size(min = 5, max = 200) @NotNull String firstName, @Size(min = 5, max = 200) @NotNull String lastName) { this.firstName = firstName; this.lastName = lastName; } public Customer() { } public String getFirstName() {
return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
repos\tutorials-master\javaxval\src\main\java\com\baeldung\javaxval\methodvalidation\model\Customer.java
1
请完成以下Java代码
public String getFruitByName(@PathParam("name") String name) { if (!"banana".equalsIgnoreCase(name)) { throw new IllegalArgumentException("Fruit not found: " + name); } return name; } @POST @Path("/create") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public void createFruit( @NotNull(message = "Fruit name must not be null") @FormParam("name") String name, @NotNull(message = "Fruit colour must not be null") @FormParam("colour") String colour) { Fruit fruit = new Fruit(name, colour); SimpleStorageService.storeFruit(fruit); } @PUT @Path("/update") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public void updateFruit(@SerialNumber @FormParam("serial") String serial) { Fruit fruit = new Fruit(); fruit.setSerial(serial); SimpleStorageService.storeFruit(fruit); } @POST @Path("/create") @Consumes(MediaType.APPLICATION_JSON) public void createFruit(@Valid Fruit fruit) {
SimpleStorageService.storeFruit(fruit); } @POST @Path("/created") @Consumes(MediaType.APPLICATION_JSON) public Response createNewFruit(@Valid Fruit fruit) { String result = "Fruit saved : " + fruit; return Response.status(Response.Status.CREATED.getStatusCode()) .entity(result) .build(); } @GET @Valid @Produces(MediaType.APPLICATION_JSON) @Path("/search/{name}") public Fruit findFruitByName(@PathParam("name") String name) { return SimpleStorageService.findByName(name); } @GET @Produces(MediaType.TEXT_HTML) @Path("/exception") @Valid public Fruit exception() { Fruit fruit = new Fruit(); fruit.setName("a"); fruit.setColour("b"); return fruit; } }
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\rest\FruitResource.java
1
请在Spring Boot框架中完成以下Java代码
public void initRepository(TenantId tenantId, RepositorySettings settings, boolean fetch) throws Exception { if (!settings.isLocalOnly()) { clearRepository(tenantId); } openOrCloneRepository(tenantId, settings, fetch); } @Override public RepositorySettings getRepositorySettings(TenantId tenantId) throws Exception { var gitRepository = repositories.get(tenantId); return gitRepository != null ? gitRepository.getSettings() : null; } @Override public void clearRepository(TenantId tenantId) throws IOException { GitRepository repository = repositories.remove(tenantId); if (repository != null) { log.debug("[{}] Clear tenant repository started.", tenantId); FileUtils.deleteDirectory(new File(repository.getDirectory())); log.debug("[{}] Clear tenant repository completed.", tenantId); } } private EntityVersion toVersion(GitRepository.Commit commit) { return new EntityVersion(commit.getTimestamp(), commit.getId(), commit.getMessage(), this.getAuthor(commit)); } private String getAuthor(GitRepository.Commit commit) { String author = String.format("<%s>", commit.getAuthorEmail());
if (StringUtils.isNotBlank(commit.getAuthorName())) { author = String.format("%s %s", commit.getAuthorName(), author); } return author; } public static EntityId fromRelativePath(String path) { EntityType entityType = EntityType.valueOf(StringUtils.substringBefore(path, "/").toUpperCase()); String entityId = StringUtils.substringBetween(path, "/", ".json"); return EntityIdFactory.getByTypeAndUuid(entityType, entityId); } private GitRepository openOrCloneRepository(TenantId tenantId, RepositorySettings settings, boolean fetch) throws Exception { log.debug("[{}] Init tenant repository started.", tenantId); Path repositoryDirectory = Path.of(repositoriesFolder, settings.isLocalOnly() ? "local_" + settings.getRepositoryUri() : tenantId.getId().toString()); GitRepository repository = GitRepository.openOrClone(repositoryDirectory, settings, fetch); repositories.put(tenantId, repository); log.debug("[{}] Init tenant repository completed.", tenantId); return repository; } }
repos\thingsboard-master\common\version-control\src\main\java\org\thingsboard\server\service\sync\vc\DefaultGitRepositoryService.java
2
请在Spring Boot框架中完成以下Java代码
public Filter tracingFilter(HttpTracing httpTracing) { // 拦截请求,记录 HTTP 请求的链路信息 return TracingFilter.create(httpTracing); } // ==================== SpringMVC 相关 ==================== // @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class) 。因为 SpanCustomizingAsyncHandlerInterceptor 未提供 public 构造方法 // ==================== RabbitMQ 相关 ==================== @Bean public JmsTracing jmsTracing(Tracing tracing) { return JmsTracing.newBuilder(tracing) .remoteServiceName("demo-mq-activemq") // 远程 ActiveMQ 服务名,可自定义 .build(); } @Bean public BeanPostProcessor activeMQBeanPostProcessor(JmsTracing jmsTracing) { return new BeanPostProcessor() { @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { // 如果是 ConnectionFactory ,针对 ActiveMQ Producer 和 Consumer if (bean instanceof ConnectionFactory) { return jmsTracing.connectionFactory((ConnectionFactory) bean); } return bean; } }; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-activemq\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java
2
请完成以下Java代码
public BigDecimal getDiscountAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DiscountAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Invoice Amt. @param InvoiceAmt Invoice Amt */ public void setInvoiceAmt (BigDecimal InvoiceAmt) { set_Value (COLUMNNAME_InvoiceAmt, InvoiceAmt); } /** Get Invoice Amt. @return Invoice Amt */ public BigDecimal getInvoiceAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_InvoiceAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Over/Under Payment. @param OverUnderAmt Over-Payment (unallocated) or Under-Payment (partial payment) Amount */ public void setOverUnderAmt (BigDecimal OverUnderAmt) { set_Value (COLUMNNAME_OverUnderAmt, OverUnderAmt); } /** Get Over/Under Payment. @return Over-Payment (unallocated) or Under-Payment (partial payment) Amount */ public BigDecimal getOverUnderAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OverUnderAmt); if (bd == null) return Env.ZERO; return bd; }
/** Set Remaining Amt. @param RemainingAmt Remaining Amount */ public void setRemainingAmt (BigDecimal RemainingAmt) { throw new IllegalArgumentException ("RemainingAmt is virtual column"); } /** Get Remaining Amt. @return Remaining Amount */ public BigDecimal getRemainingAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RemainingAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Write-off Amount. @param WriteOffAmt Amount to write-off */ public void setWriteOffAmt (BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Write-off Amount. @return Amount to write-off */ public BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentAllocate.java
1
请完成以下Java代码
public void setPOL(final org.compiere.model.I_C_Postal POL) { set_ValueFromPO(COLUMNNAME_POL_ID, org.compiere.model.I_C_Postal.class, POL); } @Override public void setPOL_ID (final int POL_ID) { if (POL_ID < 1) set_Value (COLUMNNAME_POL_ID, null); else set_Value (COLUMNNAME_POL_ID, POL_ID); } @Override public int getPOL_ID() { return get_ValueAsInt(COLUMNNAME_POL_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); } @Override public void setShipper_BPartner_ID (final int Shipper_BPartner_ID) { if (Shipper_BPartner_ID < 1) set_Value (COLUMNNAME_Shipper_BPartner_ID, null); else set_Value (COLUMNNAME_Shipper_BPartner_ID, Shipper_BPartner_ID); } @Override public int getShipper_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_BPartner_ID);
} @Override public void setShipper_Location_ID (final int Shipper_Location_ID) { if (Shipper_Location_ID < 1) set_Value (COLUMNNAME_Shipper_Location_ID, null); else set_Value (COLUMNNAME_Shipper_Location_ID, Shipper_Location_ID); } @Override public int getShipper_Location_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_Location_ID); } @Override public void setTrackingID (final @Nullable java.lang.String TrackingID) { set_Value (COLUMNNAME_TrackingID, TrackingID); } @Override public java.lang.String getTrackingID() { return get_ValueAsString(COLUMNNAME_TrackingID); } @Override public void setVesselName (final @Nullable java.lang.String VesselName) { set_Value (COLUMNNAME_VesselName, VesselName); } @Override public java.lang.String getVesselName() { return get_ValueAsString(COLUMNNAME_VesselName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShipperTransportation.java
1
请完成以下Java代码
public FeelException unableToEvaluateExpressionAsNotInputIsSet(String simpleUnaryTests, FeelMissingVariableException e) { return new FeelException(exceptionMessage( "017", "Unable to evaluate expression '{}' as no input is set. Maybe the inputExpression is missing or empty.", simpleUnaryTests), e ); } public FeelMethodInvocationException invalidDateAndTimeFormat(String dateTimeString, Throwable cause) { return new FeelMethodInvocationException(exceptionMessage( "018", "Invalid date and time format in '{}'", dateTimeString), cause, "date and time", dateTimeString ); }
public FeelMethodInvocationException unableToInvokeMethod(String simpleUnaryTests, FeelMethodInvocationException cause) { String method = cause.getMethod(); String[] parameters = cause.getParameters(); return new FeelMethodInvocationException(exceptionMessage( "019", "Unable to invoke method '{}' with parameters '{}' in expression '{}'", method, parameters, simpleUnaryTests), cause.getCause(), method, parameters ); } public FeelSyntaxException invalidListExpression(String feelExpression) { String description = "List expression can not have empty elements"; return syntaxException("020", feelExpression, description); } }
repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\FeelEngineLogger.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public Instant getCreatedOn() { return createdOn; } public void setCreatedOn(Instant createdOn) { this.createdOn = createdOn; }
public Instant getModifiedOn() { return modifiedOn; } public void setModifiedOn(Instant modifiedOn) { this.modifiedOn = modifiedOn; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\ebean\model\BaseModel.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; }
public void setAge(int age) { this.age = age; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public List<Phone> getPhones() { return phones; } public void setPhones(List<Phone> phones) { this.phones = phones; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\joins\model\Employee.java
1
请完成以下Java代码
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; }
public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } }
repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\cassandra\java\client\domain\Book.java
1
请完成以下Java代码
public final class HUIdsFilterHelper { static final String FILTER_ID = "huIds"; private static final String FILTER_PARAM_Data = "$data"; public static final transient HUIdsSqlDocumentFilterConverter SQL_DOCUMENT_FILTER_CONVERTER = new HUIdsSqlDocumentFilterConverter(); public static Optional<DocumentFilter> findExisting(@Nullable final DocumentFilterList filters) { return filters != null && !filters.isEmpty() ? filters.getFilterById(FILTER_ID) : Optional.empty(); } /** * @param huIds huIds may be empty, but not null. Empty means that <b>no</b> HU will be matched. */ public static DocumentFilter createFilter(@NonNull final Collection<HuId> huIds) { final HUIdsFilterData filterData = HUIdsFilterData.ofHUIds(huIds); return DocumentFilter.singleParameterFilter(FILTER_ID, FILTER_PARAM_Data, Operator.EQUAL, filterData); } public static DocumentFilter createFilter(@NonNull final IHUQueryBuilder huQuery) { final HUIdsFilterData filterData = HUIdsFilterData.ofHUQuery(huQuery); return DocumentFilter.singleParameterFilter(FILTER_ID, FILTER_PARAM_Data, Operator.EQUAL, filterData); } public static DocumentFilter createFilter(@NonNull final HUIdsFilterData filterData) { return DocumentFilter.singleParameterFilter(FILTER_ID, FILTER_PARAM_Data, Operator.EQUAL, filterData); } static HUIdsFilterData extractFilterData(@NonNull final DocumentFilter huIdsFilter)
{ if (isNotHUIdsFilter(huIdsFilter)) { throw new AdempiereException("Not an HUIds filter: " + huIdsFilter); } final HUIdsFilterData huIdsFilterData = (HUIdsFilterData)huIdsFilter.getParameter(FILTER_PARAM_Data).getValue(); if (huIdsFilterData == null) { throw new AdempiereException("No " + HUIdsFilterData.class + " found for " + huIdsFilter); } return huIdsFilterData; } public static Optional<HUIdsFilterData> extractFilterData(@Nullable final DocumentFilterList filters) { return findExisting(filters).map(HUIdsFilterHelper::extractFilterData); } public static boolean isNotHUIdsFilter(final DocumentFilter filter) { return !FILTER_ID.equals(filter.getFilterId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterHelper.java
1
请在Spring Boot框架中完成以下Java代码
public PPOrderCreateRequest getPPOrderCreateRequest() { return ppOrderCreateRequestBuilder.build(allocatedQty); } private boolean isFullCapacityReached() { return !isInfiniteCapacity() && capacityPerProductionCycle.compareTo(allocatedQty) <= 0; } private void allocateQuantity(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate, @NonNull final Quantity quantityToAllocate) { allocatedQty = allocatedQty.add(quantityToAllocate); final PPOrderCandidateId ppOrderCandidateId = PPOrderCandidateId.ofRepoId(ppOrderCandidateToAllocate.getPpOrderCandidate().getPP_Order_Candidate_ID()); ppOrderCand2AllocatedQty.put(ppOrderCandidateId, quantityToAllocate); }
@NonNull private Quantity getQtyToAllocate(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate) { if (isInfiniteCapacity()) { return ppOrderCandidateToAllocate.getOpenQty(); } final Quantity remainingCapacity = capacityPerProductionCycle.subtract(allocatedQty); return ppOrderCandidateToAllocate.getOpenQty().min(remainingCapacity); } private boolean isInfiniteCapacity() { return capacityPerProductionCycle.signum() == 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\service\produce\PPOrderAllocator.java
2
请完成以下Java代码
private void deleteDataForExecution(ExecutionEntity executionEntity, String deleteReason) { deleteExecutionEntity(executionEntity, deleteReason); if (deleteReason != null && deleteReason.startsWith(DeleteReason.TERMINATE_END_EVENT)) { deleteChildExecutions(executionEntity, deleteReason); } deleteUserTask(executionEntity, deleteReason); } private void cancelDataForExecution(ExecutionEntity executionEntity, String deleteReason) { boolean isActive = executionEntity.isActive(); deleteExecutionEntity(executionEntity, deleteReason); cancelUserTask(executionEntity, deleteReason); if ( isActive && executionEntity.getCurrentFlowElement() != null && !(executionEntity.getCurrentFlowElement() instanceof UserTask) && !(executionEntity.getCurrentFlowElement() instanceof SequenceFlow) ) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createActivityCancelledEvent(executionEntity, deleteReason) ); } } // OTHER METHODS @Override public void updateProcessInstanceLockTime(String processInstanceId) { Date expirationTime = getClock().getCurrentTime(); int lockMillis = getAsyncExecutor().getAsyncJobLockTimeInMillis(); GregorianCalendar lockCal = new GregorianCalendar(); lockCal.setTime(expirationTime); lockCal.add(Calendar.MILLISECOND, lockMillis); Date lockDate = lockCal.getTime();
executionDataManager.updateProcessInstanceLockTime(processInstanceId, lockDate, expirationTime); } @Override public void clearProcessInstanceLockTime(String processInstanceId) { executionDataManager.clearProcessInstanceLockTime(processInstanceId); } @Override public String updateProcessInstanceBusinessKey(ExecutionEntity executionEntity, String businessKey) { if (executionEntity.isProcessInstanceType() && businessKey != null) { executionEntity.setBusinessKey(businessKey); getHistoryManager().updateProcessBusinessKeyInHistory(executionEntity); if (getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, executionEntity) ); } return businessKey; } return null; } public ExecutionDataManager getExecutionDataManager() { return executionDataManager; } public void setExecutionDataManager(ExecutionDataManager executionDataManager) { this.executionDataManager = executionDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityManagerImpl.java
1
请完成以下Java代码
public OAuth2AccessTokenResponse convert(Map<String, Object> source) { String accessToken = getParameterValue(source, OAuth2ParameterNames.ACCESS_TOKEN); OAuth2AccessToken.TokenType accessTokenType = getAccessTokenType(source); long expiresIn = getExpiresIn(source); Set<String> scopes = getScopes(source); String refreshToken = getParameterValue(source, OAuth2ParameterNames.REFRESH_TOKEN); Map<String, Object> additionalParameters = new LinkedHashMap<>(); for (Map.Entry<String, Object> entry : source.entrySet()) { if (!TOKEN_RESPONSE_PARAMETER_NAMES.contains(entry.getKey())) { additionalParameters.put(entry.getKey(), entry.getValue()); } } // @formatter:off return OAuth2AccessTokenResponse.withToken(accessToken) .tokenType(accessTokenType) .expiresIn(expiresIn) .scopes(scopes) .refreshToken(refreshToken) .additionalParameters(additionalParameters) .build(); // @formatter:on } private static OAuth2AccessToken.TokenType getAccessTokenType(Map<String, Object> tokenResponseParameters) { if (OAuth2AccessToken.TokenType.BEARER.getValue() .equalsIgnoreCase(getParameterValue(tokenResponseParameters, OAuth2ParameterNames.TOKEN_TYPE))) { return OAuth2AccessToken.TokenType.BEARER; } else if (OAuth2AccessToken.TokenType.DPOP.getValue() .equalsIgnoreCase(getParameterValue(tokenResponseParameters, OAuth2ParameterNames.TOKEN_TYPE))) { return OAuth2AccessToken.TokenType.DPOP; } return null; } private static long getExpiresIn(Map<String, Object> tokenResponseParameters) { return getParameterValue(tokenResponseParameters, OAuth2ParameterNames.EXPIRES_IN, 0L); } private static Set<String> getScopes(Map<String, Object> tokenResponseParameters) { if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) { String scope = getParameterValue(tokenResponseParameters, OAuth2ParameterNames.SCOPE); return new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " "))); } return Collections.emptySet(); }
private static String getParameterValue(Map<String, Object> tokenResponseParameters, String parameterName) { Object obj = tokenResponseParameters.get(parameterName); return (obj != null) ? obj.toString() : null; } private static long getParameterValue(Map<String, Object> tokenResponseParameters, String parameterName, long defaultValue) { long parameterValue = defaultValue; Object obj = tokenResponseParameters.get(parameterName); if (obj != null) { // Final classes Long and Integer do not need to be coerced if (obj.getClass() == Long.class) { parameterValue = (Long) obj; } else if (obj.getClass() == Integer.class) { parameterValue = (Integer) obj; } else { // Attempt to coerce to a long (typically from a String) try { parameterValue = Long.parseLong(obj.toString()); } catch (NumberFormatException ignored) { } } } return parameterValue; } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\DefaultMapOAuth2AccessTokenResponseConverter.java
1
请完成以下Java代码
public String toString() {return getAsString();} @JsonValue public String getAsString() {return value;} public ExplainedOptional<EAN13> toEAN13() { ExplainedOptional<EAN13> ean13Holder = this.ean13Holder; if (ean13Holder == null) { ean13Holder = this.ean13Holder = EAN13.ofString(value); } return ean13Holder; } public boolean isMatching(final @NonNull EAN13ProductCode expectedProductCode) { final EAN13 ean13 = toEAN13().orElse(null); return ean13 != null && ean13.isMatching(expectedProductCode); } public boolean productCodeEndsWith(final @NonNull EAN13ProductCode expectedProductCode) { final EAN13 ean13 = toEAN13().orElse(null);
return ean13 != null && ean13.productCodeEndsWith(expectedProductCode); } /** * @return true if fixed code (e.g. not a variable weight EAN13 etc) */ public boolean isFixed() { final EAN13 ean13 = toEAN13().orElse(null); return ean13 == null || ean13.isFixed(); } /** * @return true if fixed code (e.g. not a variable weight EAN13 etc) */ public boolean isVariable() { final EAN13 ean13 = toEAN13().orElse(null); return ean13 == null || ean13.isVariableWeight(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GTIN.java
1
请完成以下Java代码
public void setId(long id) { this.id = id; } public long getId(){ return id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getActive() { return active; } public void setActive(int active) { this.active = active; }
public List<String> getRoleList() { if(this.roles.length() > 0) { return Arrays.asList(this.roles.split(",")); } return new ArrayList<>(); } public void setRoles(String roles) { this.roles = roles; } public List<String> getPermissionList() { if(this.permissions.length() > 0) { return Arrays.asList(this.permissions.split(",")); } return new ArrayList<>(); } public void setPermissions(String permissions) { this.permissions = permissions; } }
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\10.SpringCustomLogin\src\main\java\spring\custom\model\User.java
1
请完成以下Java代码
default boolean hasParameters() { return getParameterCount() > 0; } /** * Return the total number of parameters. * @return the total number of parameters */ int getParameterCount(); /** * Return if any of the contained parameters are * {@link OperationParameter#isMandatory() mandatory}. * @return if any parameters are mandatory */ default boolean hasMandatoryParameter() { return stream().anyMatch(OperationParameter::isMandatory); }
/** * Return the parameter at the specified index. * @param index the parameter index * @return the parameter */ OperationParameter get(int index); /** * Return a stream of the contained parameters. * @return a stream of the parameters */ Stream<OperationParameter> stream(); }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\invoke\OperationParameters.java
1
请完成以下Java代码
public M_HU_Snapshot_ProducerAndRestorer addModel(@NonNull final I_M_HU model) { _huIds.add(HuId.ofRepoId(model.getM_HU_ID())); return this; } @Override public final M_HU_Snapshot_ProducerAndRestorer addModels(final Collection<? extends I_M_HU> models) { models.forEach(this::addModel); return this; } /** * Gets currently enqueued models and it also clears the internal queue. * * @return enqueued models to be restored or snapshot-ed */ private final Set<HuId> getHUIdsAndClear() { final Set<HuId> modelIds = new HashSet<>(_huIds); _huIds.clear(); return modelIds; }
private final boolean hasModelsToSnapshot() { return !_huIds.isEmpty(); } @Override public ISnapshotRestorer<I_M_HU> addModelId(final int huId) { _huIds.add(HuId.ofRepoId(huId)); return this; } @Override public ISnapshotRestorer<I_M_HU> addModelIds(@NonNull final Collection<Integer> huRepoIds) { final ImmutableSet<HuId> huIds = huRepoIds .stream() .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); _huIds.addAll(huIds); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_Snapshot_ProducerAndRestorer.java
1
请完成以下Java代码
public class UserEntityLookup extends EntityLookupSupport<User> { private final @NonNull UserRepository repository; /* * (non-Javadoc) * @see org.springframework.data.rest.core.support.EntityLookup#getId(java.lang.Object) */ @Override public Object getResourceIdentifier(User entity) { return entity.getUsername(); } /* * (non-Javadoc) * @see org.springframework.data.rest.core.support.EntityLookup#lookupEntity(java.lang.Object)
*/ @Override public Optional<User> lookupEntity(Object id) { return repository.findByUsername(id.toString()); } /* * (non-Javadoc) * @see org.springframework.data.rest.core.support.EntityLookup#getLookupProperty() */ @Override public Optional<String> getLookupProperty() { return Optional.of("username"); } }
repos\spring-data-examples-main\rest\uri-customization\src\main\java\example\springdata\rest\uris\UserEntityLookup.java
1
请完成以下Java代码
public BlockingRetriesConfigurer backOff(BackOff backOff) { this.backOff = backOff; return this; } @Nullable BackOff getBackOff() { return this.backOff; } Class<? extends Exception>[] getRetryableExceptions() { return this.retryableExceptions; } } /** * Configure customizers for components instantiated by the retry topics feature. */ public static class CustomizersConfigurer { @Nullable private Consumer<DefaultErrorHandler> errorHandlerCustomizer; @Nullable private Consumer<ConcurrentMessageListenerContainer<?, ?>> listenerContainerCustomizer; @Nullable private Consumer<DeadLetterPublishingRecoverer> deadLetterPublishingRecovererCustomizer; /** * Customize the {@link CommonErrorHandler} instances that will be used for the * feature. * @param errorHandlerCustomizer the customizer. * @return the configurer. * @see DefaultErrorHandler */ @SuppressWarnings("unused") public CustomizersConfigurer customizeErrorHandler(Consumer<DefaultErrorHandler> errorHandlerCustomizer) { this.errorHandlerCustomizer = errorHandlerCustomizer; return this; }
/** * Customize the {@link ConcurrentMessageListenerContainer} instances created * for the retry and DLT consumers. * @param listenerContainerCustomizer the customizer. * @return the configurer. */ public CustomizersConfigurer customizeListenerContainer(Consumer<ConcurrentMessageListenerContainer<?, ?>> listenerContainerCustomizer) { this.listenerContainerCustomizer = listenerContainerCustomizer; return this; } /** * Customize the {@link DeadLetterPublishingRecoverer} that will be used to * forward the records to the retry topics and DLT. * @param dlprCustomizer the customizer. * @return the configurer. */ public CustomizersConfigurer customizeDeadLetterPublishingRecoverer(Consumer<DeadLetterPublishingRecoverer> dlprCustomizer) { this.deadLetterPublishingRecovererCustomizer = dlprCustomizer; return this; } @Nullable Consumer<DefaultErrorHandler> getErrorHandlerCustomizer() { return this.errorHandlerCustomizer; } @Nullable Consumer<ConcurrentMessageListenerContainer<?, ?>> getListenerContainerCustomizer() { return this.listenerContainerCustomizer; } @Nullable Consumer<DeadLetterPublishingRecoverer> getDeadLetterPublishingRecovererCustomizer() { return this.deadLetterPublishingRecovererCustomizer; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfigurationSupport.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Duration getStaleIfError() { return this.staleIfError; } public void setStaleIfError(@Nullable Duration staleIfError) { this.customized = true; this.staleIfError = staleIfError; } public @Nullable Duration getSMaxAge() { return this.sMaxAge; } public void setSMaxAge(@Nullable Duration sMaxAge) { this.customized = true; this.sMaxAge = sMaxAge; } public @Nullable CacheControl toHttpCacheControl() { PropertyMapper map = PropertyMapper.get(); CacheControl control = createCacheControl(); map.from(this::getMustRevalidate).whenTrue().toCall(control::mustRevalidate); map.from(this::getNoTransform).whenTrue().toCall(control::noTransform); map.from(this::getCachePublic).whenTrue().toCall(control::cachePublic); map.from(this::getCachePrivate).whenTrue().toCall(control::cachePrivate); map.from(this::getProxyRevalidate).whenTrue().toCall(control::proxyRevalidate); map.from(this::getStaleWhileRevalidate) .to((duration) -> control.staleWhileRevalidate(duration.getSeconds(), TimeUnit.SECONDS)); map.from(this::getStaleIfError) .to((duration) -> control.staleIfError(duration.getSeconds(), TimeUnit.SECONDS)); map.from(this::getSMaxAge) .to((duration) -> control.sMaxAge(duration.getSeconds(), TimeUnit.SECONDS)); // check if cacheControl remained untouched if (control.getHeaderValue() == null) { return null; } return control; }
private CacheControl createCacheControl() { if (Boolean.TRUE.equals(this.noStore)) { return CacheControl.noStore(); } if (Boolean.TRUE.equals(this.noCache)) { return CacheControl.noCache(); } if (this.maxAge != null) { return CacheControl.maxAge(this.maxAge.getSeconds(), TimeUnit.SECONDS); } return CacheControl.empty(); } private boolean hasBeenCustomized() { return this.customized; } } } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\WebProperties.java
2
请在Spring Boot框架中完成以下Java代码
public String getGroupType() { return groupType; } public void setGroupType(String groupType) { this.groupType = groupType; } public void customize(LDAPConfiguration configuration) { configuration.setUserIdAttribute(getUserId()); configuration.setUserFirstNameAttribute(getFirstName()); configuration.setUserLastNameAttribute(getLastName()); configuration.setUserEmailAttribute(getEmail()); configuration.setGroupIdAttribute(getGroupId()); configuration.setGroupNameAttribute(getGroupName()); configuration.setGroupTypeAttribute(getGroupType()); } } public static class Cache { /** * Allows to set the size of the {@link org.flowable.ldap.LDAPGroupCache}. This is an LRU cache that caches groups for users and thus avoids hitting * the LDAP system each time the groups of a user needs to be known. * <p> * The cache will not be instantiated if the value is less then zero. By default set to -1, so no caching is done. * <p> * Note that the group cache is instantiated on the {@link org.flowable.ldap.LDAPIdentityServiceImpl}. As such, if you have a custom implementation of * the {@link org.flowable.ldap.LDAPIdentityServiceImpl}, do not forget to add the group cache functionality. */ private int groupSize = -1; /** * Sets the expiration time of the {@link org.flowable.ldap.LDAPGroupCache} in milliseconds. When groups for a specific user are fetched, and if the * group cache exists (see {@link #groupSize}), the * groups will be stored in this cache for the time set in this property. ie. when the groups were fetched at 00:00 and the expiration time is 30 mins, any fetch of the groups for that user after * 00:30 will not come from the cache, but do a fetch again from the LDAP system. Likewise, everything group fetch for that user done between 00:00 - 00:30 will come from the cache. * <p> * By default set to one hour. */ //TODO once we move to Boot 2.0 we can use Duration as a parameter’
private long groupExpiration = Duration.of(1, ChronoUnit.HOURS).toMillis(); public int getGroupSize() { return groupSize; } public void setGroupSize(int groupSize) { this.groupSize = groupSize; } public long getGroupExpiration() { return groupExpiration; } public void setGroupExpiration(int groupExpiration) { this.groupExpiration = groupExpiration; } public void customize(LDAPConfiguration configuration) { configuration.setGroupCacheSize(getGroupSize()); configuration.setGroupCacheExpirationTime(getGroupExpiration()); } } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\ldap\FlowableLdapProperties.java
2
请完成以下Java代码
public void setFileName (final String FileName) { set_Value (COLUMNNAME_FileName, FileName); } @Override public String getFileName() { return get_ValueAsString(COLUMNNAME_FileName); } @Override public void setImported (final @Nullable java.sql.Timestamp Imported) { set_Value (COLUMNNAME_Imported, Imported); } @Override public java.sql.Timestamp getImported() { return get_ValueAsTimestamp(COLUMNNAME_Imported); } @Override public void setIsMatchAmounts (final boolean IsMatchAmounts) { set_Value (COLUMNNAME_IsMatchAmounts, IsMatchAmounts);
} @Override public boolean isMatchAmounts() { return get_ValueAsBoolean(COLUMNNAME_IsMatchAmounts); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\org\adempiere\banking\model\X_C_BankStatement_Import_File.java
1