instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public Integer getCount() { return this.query().getSize(); } public Integer getPageNumber() { return this.query().getNumber(); } public Long getTotal() { return this.query().getTotalElements(); } public Object getContent() { return this.query().getContent(); } } class SexType extends BasePaginationInfo implements Types { public SexType(String sexName, String emailName, Pageable pageable) { //String sexName, String emailName, super(sexName, emailName, pageable); } public Page<Persons> query() { return this.instance.findBySex( this.sex, this.pageable ); } public Integer getCount() { return this.query().getSize(); } public Integer getPageNumber() { return this.query().getNumber(); } public Long getTotal() { return this.query().getTotalElements(); } public Object getContent() { return this.query().getContent(); } } public class PaginationFormatting { private PaginationMultiTypeValuesHelper multiValue = new PaginationMultiTypeValuesHelper(); private Map<String, PaginationMultiTypeValuesHelper> results = new HashMap<>(); public Map<String, PaginationMultiTypeValuesHelper> filterQuery(String sex, String email, Pageable pageable) {
Types typeInstance; if (sex.length() == 0 && email.length() == 0) { typeInstance = new AllType(sex, email, pageable); } else if (sex.length() > 0 && email.length() > 0) { typeInstance = new SexEmailType(sex, email, pageable); } else { typeInstance = new SexType(sex, email, pageable); } this.multiValue.setCount(typeInstance.getCount()); this.multiValue.setPage(typeInstance.getPageNumber() + 1); this.multiValue.setResults(typeInstance.getContent()); this.multiValue.setTotal(typeInstance.getTotal()); this.results.put("data", this.multiValue); return results; } }
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\controller\pagination\PaginationFormatting.java
2
请完成以下Java代码
static void handleCarExceptionWithUnnamedVariables(Car<?> car) { try { someOperationThatFails(car); } catch (IllegalStateException | NumberFormatException _) { System.out.println("Got an illegal state exception for: " + car.name()); } catch (RuntimeException _) { System.out.println("Got a runtime exception!"); } } static void obtainTransactionAndUpdateCarWithNamedVariables(Car<?> car) { try (var transaction = new Transaction()) { updateCar(car); } } static void obtainTransactionAndUpdateCarWithUnnamedVariables(Car<?> car) { try (var _ = new Transaction()) { updateCar(car); } } static void updateCar(Car<?> car) {
// Some update logic System.out.println("Car updated!"); } static Map<String, List<Car<?>>> getCarsByFirstLetterWithNamedVariables(List<Car<?>> cars) { Map<String, List<Car<?>>> carMap = new HashMap<>(); cars.forEach(car -> carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car) ); return carMap; } static Map<String, List<Car<?>>> getCarsByFirstLetterWithUnnamedVariables(List<Car<?>> cars) { Map<String, List<Car<?>>> carMap = new HashMap<>(); cars.forEach(car -> carMap.computeIfAbsent(car.name().substring(0, 1), _ -> new ArrayList<>()).add(car) ); return carMap; } private static void someOperationThatFails(Car<?> car) { throw new IllegalStateException("Triggered exception for: " + car.name()); } }
repos\tutorials-master\core-java-modules\core-java-21\src\main\java\com\baeldung\unnamed\variables\UnnamedVariables.java
1
请在Spring Boot框架中完成以下Java代码
public DeleteProcessDefinitionsBuilderImpl cascade() { this.cascade = true; return this; } @Override public DeleteProcessDefinitionsBuilderImpl skipCustomListeners() { this.skipCustomListeners = true; return this; } @Override public DeleteProcessDefinitionsBuilderImpl skipIoMappings() { this.skipIoMappings = true; return this; } @Override public void delete() {
ensureOnlyOneNotNull(NullValueException.class, "'processDefinitionKey' or 'processDefinitionIds' cannot be null", processDefinitionKey, processDefinitionIds); Command<Void> command; if (processDefinitionKey != null) { command = new DeleteProcessDefinitionsByKeyCmd(processDefinitionKey, cascade, skipCustomListeners, skipIoMappings, tenantId, isTenantIdSet); } else if (processDefinitionIds != null && !processDefinitionIds.isEmpty()) { command = new DeleteProcessDefinitionsByIdsCmd(processDefinitionIds, cascade, skipCustomListeners, skipIoMappings); } else { return; } commandExecutor.execute(command); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DeleteProcessDefinitionsBuilderImpl.java
2
请完成以下Java代码
public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID) { delegate.setC_BPartner_Location_Value_ID(C_BPartner_Location_Value_ID); } @Override public int getAD_User_ID() { return delegate.getAD_User_ID(); } @Override public void setAD_User_ID(final int AD_User_ID) { delegate.setAD_User_ID(AD_User_ID); } @Override public String getBPartnerAddress() { return delegate.getBPartnerAddress(); } @Override public void setBPartnerAddress(final String address) { delegate.setBPartnerAddress(address); }
public void setFromOrderHeader(@NonNull final I_C_Order order) { final boolean useDropshiplocation = order.isDropShip() && order.isSOTrx(); final DocumentLocation orderLocation = useDropshiplocation ? OrderDocumentLocationAdapterFactory.deliveryLocationAdapter(order).toDocumentLocation() : OrderDocumentLocationAdapterFactory.locationAdapter(order).toDocumentLocation(); setFrom(orderLocation); } public void setLocationAndResetRenderedAddress(@NonNull final BPartnerLocationAndCaptureId from) { setC_BPartner_Location_ID(from != null ? from.getBPartnerLocationRepoId() : -1); setC_BPartner_Location_Value_ID(from != null ? from.getLocationCaptureRepoId() : -1); setBPartnerAddress(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderLineMainLocationAdapter.java
1
请在Spring Boot框架中完成以下Java代码
public DmnDeploymentBuilder disableSchemaValidation() { this.isDmn20XsdValidationEnabled = false; return this; } @Override public DmnDeploymentBuilder tenantId(String tenantId) { deployment.setTenantId(tenantId); return this; } @Override public DmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) { deployment.setParentDeploymentId(parentDeploymentId); return this; } @Override public DmnDeploymentBuilder enableDuplicateFiltering() { isDuplicateFilterEnabled = true; return this; }
@Override public DmnDeployment deploy() { return repositoryService.deploy(this); } // getters and setters // ////////////////////////////////////////////////////// public DmnDeploymentEntity getDeployment() { return deployment; } public boolean isDmnXsdValidationEnabled() { return isDmn20XsdValidationEnabled; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\repository\DmnDeploymentBuilderImpl.java
2
请在Spring Boot框架中完成以下Java代码
public Map<String, String> getProperties() { return this.properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } } static class DataSourceBeanCreationException extends BeanCreationException { private final DataSourceProperties properties; private final EmbeddedDatabaseConnection connection; DataSourceBeanCreationException(String message, DataSourceProperties properties, EmbeddedDatabaseConnection connection) {
super(message); this.properties = properties; this.connection = connection; } DataSourceProperties getProperties() { return this.properties; } EmbeddedDatabaseConnection getConnection() { return this.connection; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceProperties.java
2
请完成以下Java代码
public void setProducts (final @Nullable java.lang.String Products) { throw new IllegalArgumentException ("Products is virtual column"); } @Override public java.lang.String getProducts() { return get_ValueAsString(COLUMNNAME_Products); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public de.metas.handlingunits.model.I_M_HU getVHU() { return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class); }
@Override public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU) { set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU); } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_Value (COLUMNNAME_VHU_ID, null); else set_Value (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Assignment.java
1
请完成以下Java代码
public List<OrderCost> getByIds(@NonNull final Collection<OrderCostId> orderCostIds) { return newSession().getByIds(orderCostIds); } public void saveAll(final Collection<OrderCost> orderCostsList) { newSession().saveAll(orderCostsList); } public void save(final OrderCost orderCost) { newSession().save(orderCost); } public void changeByOrderLineId(@NonNull final OrderLineId orderLineId, @NonNull final Consumer<OrderCost> consumer) { newSession().changeByOrderLineId(orderLineId, consumer); } public void deleteDetails(@NonNull final OrderCostId orderCostId) { queryBL.createQueryBuilder(I_C_Order_Cost_Detail.class) .addEqualsFilter(I_C_Order_Cost_Detail.COLUMNNAME_C_Order_Cost_ID, orderCostId) .create() .delete(); } public boolean hasCostsByCreatedOrderLineIds(final ImmutableSet<OrderLineId> orderLineIds) { if (orderLineIds.isEmpty()) { return false; } return queryBL.createQueryBuilder(I_C_Order_Cost.class) .addInArrayFilter(I_C_Order_Cost.COLUMNNAME_Created_OrderLine_ID, orderLineIds) .create() .anyMatch();
} public void deleteByCreatedOrderLineId(@NonNull final OrderAndLineId createdOrderLineId) { final I_C_Order_Cost orderCostRecord = queryBL.createQueryBuilder(I_C_Order_Cost.class) .addEqualsFilter(I_C_Order_Cost.COLUMNNAME_C_Order_ID, createdOrderLineId.getOrderId()) .addEqualsFilter(I_C_Order_Cost.COLUMNNAME_Created_OrderLine_ID, createdOrderLineId.getOrderLineId()) .create() .firstOnly(); if (orderCostRecord == null) { return; } final OrderCostId orderCostId = OrderCostId.ofRepoId(orderCostRecord.getC_Order_Cost_ID()); deleteDetails(orderCostId); InterfaceWrapperHelper.delete(orderCostRecord, false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostRepository.java
1
请完成以下Java代码
public List<IDunnableSource> getSources(IDunningContext context) { final List<IDunnableSource> result = new ArrayList<IDunnableSource>(); result.addAll(dunnableSources.values()); return result; } private IDunnableSource createSource(Class<? extends IDunnableSource> sourceClass) { final IDunnableSource source; try { source = sourceClass.newInstance(); return source; } catch (Exception e) { throw new DunningException("Cannot create dunning source for " + sourceClass, e); } } @Override public void registerSource(Class<? extends IDunnableSource> clazz)
{ if (dunnableSources.containsKey(clazz)) { return; } final IDunnableSource source = createSource(clazz); dunnableSources.put(clazz, source); } @Override public String toString() { return "DefaultDunnableSourceFactory [dunnableSources=" + dunnableSources + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DefaultDunnableSourceFactory.java
1
请完成以下Java代码
public static DmnEngine getDmnEngine(String dmnEngineName) { if (!isInitialized()) { init(); } return dmnEngines.get(dmnEngineName); } /** * retries to initialize a dmn engine that previously failed. */ public static EngineInfo retry(String resourceUrl) { LOGGER.debug("retying initializing of resource {}", resourceUrl); try { return initDmnEngineFromResource(new URL(resourceUrl)); } catch (MalformedURLException e) { throw new FlowableException("invalid url: " + resourceUrl, e); } } /** * provides access to dmn engine to application clients in a managed server environment. */ public static Map<String, DmnEngine> getDmnEngines() { return dmnEngines; } /** * closes all dmn engines. This method should be called when the server shuts down. */ public static synchronized void destroy() { if (isInitialized()) { Map<String, DmnEngine> engines = new HashMap<>(dmnEngines); dmnEngines = new HashMap<>();
for (String dmnEngineName : engines.keySet()) { DmnEngine dmnEngine = engines.get(dmnEngineName); try { dmnEngine.close(); } catch (Exception e) { LOGGER.error("exception while closing {}", (dmnEngineName == null ? "the default dmn engine" : "dmn engine " + dmnEngineName), e); } } dmnEngineInfosByName.clear(); dmnEngineInfosByResourceUrl.clear(); dmnEngineInfos.clear(); setInitialized(false); } } public static boolean isInitialized() { return isInitialized; } public static void setInitialized(boolean isInitialized) { DmnEngines.isInitialized = isInitialized; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\DmnEngines.java
1
请在Spring Boot框架中完成以下Java代码
public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getDealPrice() { return dealPrice; } public void setDealPrice(double dealPrice) { this.dealPrice = dealPrice; } public double getOldPrice() { return oldPrice; } public void setOldPrice(double oldPrice) { this.oldPrice = oldPrice;
} public Date getDepartureDate() { return departureDate; } public void setDepartureDate(Date departureDate) { this.departureDate = departureDate; } public Date getArrivalDate() { return arrivalDate; } public void setArrivalDate(Date arrivalDate) { this.arrivalDate = arrivalDate; } @Override public String toString() { return "TravelDeal{" + "id=" + id + ", destination='" + destination + '\'' + ", description='" + description + '\'' + ", dealPrice=" + dealPrice + ", oldPrice=" + oldPrice + ", departureDate=" + departureDate + ", arrivalDate=" + arrivalDate + '}'; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-kubernetes\kubernetes-guide\travel-agency-service\src\main\java\com\baeldung\spring\cloud\kubernetes\travelagency\model\TravelDeal.java
2
请在Spring Boot框架中完成以下Java代码
private VersionedEntityInfo getVersionedEntityInfo(TransportProtos.VersionedEntityInfoProto proto) { return new VersionedEntityInfo(EntityIdFactory.getByTypeAndUuid(proto.getEntityType(), new UUID(proto.getEntityIdMSB(), proto.getEntityIdLSB()))); } private BranchInfo getBranchInfo(TransportProtos.BranchInfoProto proto) { return new BranchInfo(proto.getName(), proto.getIsDefault()); } @SuppressWarnings("rawtypes") @SneakyThrows private EntityExportData toData(String data) { return JacksonUtil.fromString(data, EntityExportData.class); } private static String getRelativePath(EntityType entityType, EntityId entityId) { String path = entityType.name().toLowerCase(); if (entityId != null) { path += "/" + entityId + ".json"; } return path; } private static PrepareMsg getCommitPrepareMsg(User user, VersionCreateRequest request) { return PrepareMsg.newBuilder().setCommitMsg(request.getVersionName()) .setBranchName(request.getBranch()).setAuthorName(getAuthorName(user)).setAuthorEmail(user.getEmail()).build(); } private static String getAuthorName(User user) { List<String> parts = new ArrayList<>(); if (StringUtils.isNotBlank(user.getFirstName())) { parts.add(user.getFirstName()); } if (StringUtils.isNotBlank(user.getLastName())) { parts.add(user.getLastName()); } if (parts.isEmpty()) { parts.add(user.getName()); } return String.join(" ", parts);
} private ToVersionControlServiceMsg.Builder newRequestProto(PendingGitRequest<?> request, RepositorySettings settings) { var tenantId = request.getTenantId(); var requestId = request.getRequestId(); var builder = ToVersionControlServiceMsg.newBuilder() .setNodeId(serviceInfoProvider.getServiceId()) .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setRequestIdMSB(requestId.getMostSignificantBits()) .setRequestIdLSB(requestId.getLeastSignificantBits()); RepositorySettings vcSettings = settings; if (vcSettings == null && request.requiresSettings()) { vcSettings = entitiesVersionControlService.getVersionControlSettings(tenantId); } if (vcSettings != null) { builder.setVcSettings(ProtoUtils.toProto(vcSettings)); } else if (request.requiresSettings()) { throw new RuntimeException("No entity version control settings provisioned!"); } return builder; } private CommitRequestMsg.Builder buildCommitRequest(CommitGitRequest commit) { return CommitRequestMsg.newBuilder().setTxId(commit.getTxId().toString()); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\DefaultGitVersionControlQueueService.java
2
请完成以下Java代码
public PageData<MobileAppBundleInfo> findInfosByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(mobileAppBundleRepository.findInfoByTenantId(tenantId.getId(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public MobileAppBundleInfo findInfoById(TenantId tenantId, MobileAppBundleId mobileAppBundleId) { return DaoUtil.getData(mobileAppBundleRepository.findInfoById(mobileAppBundleId.getId())); } @Override public List<MobileAppBundleOauth2Client> findOauth2ClientsByMobileAppBundleId(TenantId tenantId, MobileAppBundleId mobileAppBundleId) { return DaoUtil.convertDataList(mobileOauth2ProviderRepository.findAllByMobileAppBundleId(mobileAppBundleId.getId())); } @Override public void addOauth2Client(TenantId tenantId, MobileAppBundleOauth2Client mobileAppBundleOauth2Client) { mobileOauth2ProviderRepository.save(new MobileAppBundleOauth2ClientEntity(mobileAppBundleOauth2Client)); } @Override public void removeOauth2Client(TenantId tenantId, MobileAppBundleOauth2Client mobileAppBundleOauth2Client) {
mobileOauth2ProviderRepository.deleteById(new MobileAppOauth2ClientCompositeKey(mobileAppBundleOauth2Client.getMobileAppBundleId().getId(), mobileAppBundleOauth2Client.getOAuth2ClientId().getId())); } @Override public MobileAppBundle findByPkgNameAndPlatform(TenantId tenantId, String pkgName, PlatformType platform) { return DaoUtil.getData(mobileAppBundleRepository.findByPkgNameAndPlatformType(pkgName, platform)); } @Override public void deleteByTenantId(TenantId tenantId) { mobileAppBundleRepository.deleteByTenantId(tenantId.getId()); } @Override public EntityType getEntityType() { return EntityType.MOBILE_APP_BUNDLE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\mobile\JpaMobileAppBundleDao.java
1
请在Spring Boot框架中完成以下Java代码
public class OrdersController { private final OrdersService orders; @PostMapping("/orders/sell") public ResponseEntity<Order> postSellOrder(String symbol, BigDecimal quantity, BigDecimal price) { log.info("postSellOrder: symbol={},quantity={},price={}", symbol,quantity,price); Order order = orders.createOrder(OrderType.SELL, symbol, quantity, price); return ResponseEntity.status(HttpStatus.CREATED).body(order); } @PostMapping("/orders/buy") public ResponseEntity<Order> postBuyOrder(String symbol, BigDecimal quantity, BigDecimal price) { log.info("postBuyOrder: symbol={},quantity={},price={}", symbol,quantity,price); Order order = orders.createOrder(OrderType.BUY, symbol, quantity, price);
return ResponseEntity.status(HttpStatus.CREATED).body(order); } @GetMapping("/orders/{id}") public ResponseEntity<Order> getOrderById(@PathVariable Long id) { Optional<Order> o = orders.findById(id); if (!o.isPresent()) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(o.get()); } }
repos\tutorials-master\messaging-modules\postgres-notify\src\main\java\com\baeldung\messaging\postgresql\controller\OrdersController.java
2
请完成以下Java代码
public class FilterExample implements Predicate { private Pattern pattern; public FilterExample(String regexQuery) { if (regexQuery != null && !regexQuery.isEmpty()) { pattern = Pattern.compile(regexQuery); } } public boolean evaluate(RowSet rs) { try { if (!rs.isAfterLast()) { String name = rs.getString("name"); System.out.println(String.format( "Searching for pattern '%s' in %s", pattern.toString(), name)); Matcher matcher = pattern.matcher(name); return matcher.matches(); } else
return false; } catch (Exception e) { e.printStackTrace(); return false; } } public boolean evaluate(Object value, int column) throws SQLException { throw new UnsupportedOperationException("This operation is unsupported."); } public boolean evaluate(Object value, String columnName) throws SQLException { throw new UnsupportedOperationException("This operation is unsupported."); } }
repos\tutorials-master\persistence-modules\jdbc\src\main\java\com\baeldung\jdbcrowset\FilterExample.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setM_Product_Proxy_ID (final int M_Product_Proxy_ID) { if (M_Product_Proxy_ID < 1) set_Value (COLUMNNAME_M_Product_Proxy_ID, null); else set_Value (COLUMNNAME_M_Product_Proxy_ID, M_Product_Proxy_ID); } @Override public int getM_Product_Proxy_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Proxy_ID); } @Override public void setM_ProductGroup_ID (final int M_ProductGroup_ID) { if (M_ProductGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductGroup_ID, M_ProductGroup_ID); } @Override
public int getM_ProductGroup_ID() { return get_ValueAsInt(COLUMNNAME_M_ProductGroup_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_M_ProductGroup.java
1
请在Spring Boot框架中完成以下Java代码
public class RedisConfig { @Autowired RedisConnectionFactory factory; @Bean public ReactiveRedisTemplate<String, Employee> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) { Jackson2JsonRedisSerializer<Employee> serializer = new Jackson2JsonRedisSerializer<>(Employee.class); RedisSerializationContext.RedisSerializationContextBuilder<String, Employee> builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer()); RedisSerializationContext<String, Employee> context = builder.value(serializer) .build(); return new ReactiveRedisTemplate<>(factory, context); } @Bean public ReactiveKeyCommands keyCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) {
return reactiveRedisConnectionFactory.getReactiveConnection() .keyCommands(); } @Bean public ReactiveStringCommands stringCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) { return reactiveRedisConnectionFactory.getReactiveConnection() .stringCommands(); } @PreDestroy public void cleanRedis() { factory.getConnection().serverCommands() .flushDb(); } }
repos\tutorials-master\persistence-modules\spring-data-redis\src\main\java\com\baeldung\spring\data\reactive\redis\config\RedisConfig.java
2
请完成以下Java代码
public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setElapsedTimeMS (final BigDecimal ElapsedTimeMS) { set_Value (COLUMNNAME_ElapsedTimeMS, ElapsedTimeMS); } @Override public BigDecimal getElapsedTimeMS() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ElapsedTimeMS); return bd != null ? bd : BigDecimal.ZERO; } /** * EventType AD_Reference_ID=306 * Reference name: WF_EventType */ public static final int EVENTTYPE_AD_Reference_ID=306; /** Process Created = PC */ public static final String EVENTTYPE_ProcessCreated = "PC"; /** State Changed = SC */ public static final String EVENTTYPE_StateChanged = "SC"; /** Process Completed = PX */ public static final String EVENTTYPE_ProcessCompleted = "PX"; /** Trace = TR */ public static final String EVENTTYPE_Trace = "TR"; @Override public void setEventType (final java.lang.String EventType) { set_Value (COLUMNNAME_EventType, EventType); } @Override public java.lang.String getEventType() { return get_ValueAsString(COLUMNNAME_EventType); } @Override public void setNewValue (final java.lang.String NewValue) { set_Value (COLUMNNAME_NewValue, NewValue); } @Override public java.lang.String getNewValue() { return get_ValueAsString(COLUMNNAME_NewValue); } @Override public void setOldValue (final java.lang.String OldValue) { set_Value (COLUMNNAME_OldValue, OldValue); } @Override public java.lang.String getOldValue() { return get_ValueAsString(COLUMNNAME_OldValue); } @Override public void setRecord_ID (final int Record_ID) {
if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setTextMsg (final java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } @Override public java.lang.String getTextMsg() { return get_ValueAsString(COLUMNNAME_TextMsg); } /** * WFState AD_Reference_ID=305 * Reference name: WF_Instance State */ public static final int WFSTATE_AD_Reference_ID=305; /** NotStarted = ON */ public static final String WFSTATE_NotStarted = "ON"; /** Running = OR */ public static final String WFSTATE_Running = "OR"; /** Suspended = OS */ public static final String WFSTATE_Suspended = "OS"; /** Completed = CC */ public static final String WFSTATE_Completed = "CC"; /** Aborted = CA */ public static final String WFSTATE_Aborted = "CA"; /** Terminated = CT */ public static final String WFSTATE_Terminated = "CT"; @Override public void setWFState (final java.lang.String WFState) { set_Value (COLUMNNAME_WFState, WFState); } @Override public java.lang.String getWFState() { return get_ValueAsString(COLUMNNAME_WFState); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_EventAudit.java
1
请完成以下Java代码
public void setDiscountDate (final @Nullable java.sql.Timestamp DiscountDate) { set_Value (COLUMNNAME_DiscountDate, DiscountDate); } @Override public java.sql.Timestamp getDiscountDate() { return get_ValueAsTimestamp(COLUMNNAME_DiscountDate); } @Override public void setDiscountDays (final int DiscountDays) { set_Value (COLUMNNAME_DiscountDays, DiscountDays); } @Override public int getDiscountDays() { return get_ValueAsInt(COLUMNNAME_DiscountDays); } @Override public void setEDI_cctop_140_v_ID (final int EDI_cctop_140_v_ID) { if (EDI_cctop_140_v_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_cctop_140_v_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_cctop_140_v_ID, EDI_cctop_140_v_ID); } @Override public int getEDI_cctop_140_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_140_v_ID); } @Override public de.metas.esb.edi.model.I_EDI_cctop_invoic_v getEDI_cctop_invoic_v() { return get_ValueAsPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class); } @Override public void setEDI_cctop_invoic_v(final de.metas.esb.edi.model.I_EDI_cctop_invoic_v EDI_cctop_invoic_v) { set_ValueFromPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class, EDI_cctop_invoic_v); } @Override public void setEDI_cctop_invoic_v_ID (final int EDI_cctop_invoic_v_ID) { if (EDI_cctop_invoic_v_ID < 1) set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, null); else set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, EDI_cctop_invoic_v_ID); }
@Override public int getEDI_cctop_invoic_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_invoic_v_ID); } @Override public void setName (final @Nullable java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setRate (final @Nullable BigDecimal Rate) { set_Value (COLUMNNAME_Rate, Rate); } @Override public BigDecimal getRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_140_v.java
1
请完成以下Java代码
public MatchResult matcher(HttpServletRequest request) { for (RequestMatcher matcher : this.requestMatchers) { MatchResult result = matcher.matcher(request); if (result.isMatch()) { return result; } } return MatchResult.notMatch(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; }
OrRequestMatcher that = (OrRequestMatcher) o; return Objects.equals(this.requestMatchers, that.requestMatchers); } @Override public int hashCode() { return Objects.hash(this.requestMatchers); } @Override public String toString() { return "Or " + this.requestMatchers; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\matcher\OrRequestMatcher.java
1
请完成以下Java代码
public class UmsMemberRuleSetting implements Serializable { private Long id; @ApiModelProperty(value = "连续签到天数") private Integer continueSignDay; @ApiModelProperty(value = "连续签到赠送数量") private Integer continueSignPoint; @ApiModelProperty(value = "每消费多少元获取1个点") private BigDecimal consumePerPoint; @ApiModelProperty(value = "最低获取点数的订单金额") private BigDecimal lowOrderAmount; @ApiModelProperty(value = "每笔订单最高获取点数") private Integer maxPointPerOrder; @ApiModelProperty(value = "类型:0->积分规则;1->成长值规则") private Integer type; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getContinueSignDay() { return continueSignDay; } public void setContinueSignDay(Integer continueSignDay) { this.continueSignDay = continueSignDay; } public Integer getContinueSignPoint() { return continueSignPoint; } public void setContinueSignPoint(Integer continueSignPoint) { this.continueSignPoint = continueSignPoint; } public BigDecimal getConsumePerPoint() { return consumePerPoint; } public void setConsumePerPoint(BigDecimal consumePerPoint) { this.consumePerPoint = consumePerPoint; } public BigDecimal getLowOrderAmount() { return lowOrderAmount; } public void setLowOrderAmount(BigDecimal lowOrderAmount) { this.lowOrderAmount = lowOrderAmount; } public Integer getMaxPointPerOrder() { return maxPointPerOrder; }
public void setMaxPointPerOrder(Integer maxPointPerOrder) { this.maxPointPerOrder = maxPointPerOrder; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", continueSignDay=").append(continueSignDay); sb.append(", continueSignPoint=").append(continueSignPoint); sb.append(", consumePerPoint=").append(consumePerPoint); sb.append(", lowOrderAmount=").append(lowOrderAmount); sb.append(", maxPointPerOrder=").append(maxPointPerOrder); sb.append(", type=").append(type); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberRuleSetting.java
1
请在Spring Boot框架中完成以下Java代码
public InsuranceContractQuantity archived(Boolean archived) { this.archived = archived; return this; } /** * Maximalmenge nicht mehr gültig - archiviert * @return archived **/ @Schema(example = "false", description = "Maximalmenge nicht mehr gültig - archiviert") public Boolean isArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InsuranceContractQuantity insuranceContractQuantity = (InsuranceContractQuantity) o; return Objects.equals(this.pcn, insuranceContractQuantity.pcn) && Objects.equals(this.quantity, insuranceContractQuantity.quantity) && Objects.equals(this.unit, insuranceContractQuantity.unit) && Objects.equals(this.archived, insuranceContractQuantity.archived); } @Override public int hashCode() { return Objects.hash(pcn, quantity, unit, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractQuantity {\n");
sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).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\InsuranceContractQuantity.java
2
请完成以下Java代码
private I_M_ProductPrice buildNewProductPriceRecord(@NonNull final CreateProductPriceRequest request) { final I_M_ProductPrice record = InterfaceWrapperHelper.newInstance(I_M_ProductPrice.class); record.setAD_Org_ID(request.getOrgId().getRepoId()); record.setM_Product_ID(request.getProductId().getRepoId()); record.setM_PriceList_Version_ID(request.getPriceListVersionId().getRepoId()); record.setPriceLimit(request.getPriceLimit()); record.setPriceList(request.getPriceList()); record.setPriceStd(request.getPriceStd()); record.setC_UOM_ID(request.getUomId().getRepoId()); record.setC_TaxCategory_ID(request.getTaxCategoryId().getRepoId()); if (request.getIsActive() != null) { record.setIsActive(request.getIsActive()); } if (request.getSeqNo() != null) { record.setSeqNo(request.getSeqNo()); } return record; } @NonNull private I_M_ProductPrice toProductPriceRecord(@NonNull final ProductPrice request) { final I_M_ProductPrice record = getRecordById(request.getProductPriceId()); record.setAD_Org_ID(request.getOrgId().getRepoId()); record.setM_Product_ID(request.getProductId().getRepoId()); record.setM_PriceList_Version_ID(request.getPriceListVersionId().getRepoId()); record.setPriceLimit(request.getPriceLimit()); record.setPriceList(request.getPriceList()); record.setPriceStd(request.getPriceStd()); record.setC_UOM_ID(request.getUomId().getRepoId()); record.setC_TaxCategory_ID(request.getTaxCategoryId().getRepoId()); record.setSeqNo(request.getSeqNo());
record.setIsActive(request.getIsActive()); return record; } @NonNull private I_M_ProductPrice getRecordById(@NonNull final ProductPriceId productPriceId) { return queryBL .createQueryBuilder(I_M_ProductPrice.class) .addEqualsFilter(I_M_ProductPrice.COLUMNNAME_M_ProductPrice_ID, productPriceId.getRepoId()) .create() .firstOnlyNotNull(I_M_ProductPrice.class); } @NonNull public <T extends I_M_ProductPrice> T getRecordById(@NonNull final ProductPriceId productPriceId, @NonNull final Class<T> productPriceClass) { return InterfaceWrapperHelper.load(productPriceId, productPriceClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\productprice\ProductPriceRepository.java
1
请完成以下Java代码
private void updatePricing(final I_PMM_PurchaseCandidate candidate) { try { final IPMMPricingAware pricingAware = pmmPurchaseCandidateBL.asPMMPricingAware(candidate); pmmPricingBL.updatePricing(pricingAware); InterfaceWrapperHelper.save(candidate); countProcessed++; } catch (final Exception e) { countError++; log.warn("Error while processing {}. Ignored", candidate, e); addLog("Error on {}: {}", candidate, e.getLocalizedMessage()); } } private final Iterator<I_PMM_PurchaseCandidate> retrieveAndLock() { // // Create filter final ICompositeQueryFilter<I_PMM_PurchaseCandidate> filter = queryBL.createCompositeQueryFilter(I_PMM_PurchaseCandidate.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient(getCtx()) .addEqualsFilter(I_PMM_PurchaseCandidate.COLUMNNAME_Processed, false) .addFilter(lockManager.getNotLockedFilter(I_PMM_PurchaseCandidate.class)); if (p_DatePromisedFrom != null) { filter.addCompareFilter(I_PMM_PurchaseCandidate.COLUMN_DatePromised, Operator.GREATER_OR_EQUAL, p_DatePromisedFrom); } if (p_DatePromisedTo != null) { filter.addCompareFilter(I_PMM_PurchaseCandidate.COLUMN_DatePromised, Operator.LESS_OR_EQUAL, p_DatePromisedTo); } log.info("Filter: {}", filter); // // Lock final LockOwner lockOwner = LockOwner.newOwner(getClass().getSimpleName()); _lock = lockManager.lock() .setOwner(lockOwner) .setAutoCleanup(true) .setFailIfNothingLocked(false) .setRecordsByFilter(I_PMM_PurchaseCandidate.class, filter)
.acquire(); // // Retrieve candidates return queryBL.createQueryBuilder(I_PMM_PurchaseCandidate.class, getCtx(), ITrx.TRXNAME_ThreadInherited) .filter(lockManager.getLockedByFilter(I_PMM_PurchaseCandidate.class, _lock)) // .orderBy() .addColumn(I_PMM_PurchaseCandidate.COLUMN_PMM_PurchaseCandidate_ID) .endOrderBy() // .create() .iterate(I_PMM_PurchaseCandidate.class); } private void closeResources() { final ILock lock = _lock; if (lock != null) { try { lock.close(); _lock = null; } catch (final Exception e) { log.warn("Failed closing {}. Ignored.", lock); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\process\PMM_Purchase_Candidate_UpdatePricing.java
1
请完成以下Java代码
public Incoterms getById(@NotNull final IncotermsId id) { return getIncotermsMap().getById(id); } @NotNull public Incoterms getByValue(@NotNull final String value, @NotNull final OrgId orgId) { return getIncotermsMap().getByValue(value, orgId); } @NonNull private IncotermsMap getIncotermsMap() { return cache.getOrLoadNonNull(0, this::retrieveIncotermsMap); } @NotNull private IncotermsMap retrieveIncotermsMap() { final ImmutableList<Incoterms> incoterms = queryBL.createQueryBuilder(I_C_Incoterms.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(IncotermsRepository::ofRecord) .collect(ImmutableList.toImmutableList()); return new IncotermsRepository.IncotermsMap(incoterms); } private static Incoterms ofRecord(@NotNull final I_C_Incoterms record) { return Incoterms.builder() .id(IncotermsId.ofRepoId(record.getC_Incoterms_ID())) .name(record.getName()) .value(record.getValue()) .isDefault(record.isDefault()) .defaultLocation(record.getDefaultLocation()) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .build(); } private static final class IncotermsMap { private final ImmutableMap<IncotermsId, Incoterms> byId; private final ImmutableMap<OrgId, Incoterms> defaultByOrgId; private final ImmutableMap<ValueAndOrgId, Incoterms> byValueAndOrgId; IncotermsMap(final List<Incoterms> list) { this.byId = Maps.uniqueIndex(list, Incoterms::getId); this.defaultByOrgId = list.stream().filter(Incoterms::isDefault) .collect(ImmutableMap.toImmutableMap(Incoterms::getOrgId, incoterms->incoterms)); this.byValueAndOrgId = Maps.uniqueIndex(list, incoterm -> ValueAndOrgId.builder().value(incoterm.getValue()).orgId(incoterm.getOrgId()).build()); } @NonNull public Incoterms getById(@NonNull final IncotermsId id) { final Incoterms incoterms = byId.get(id); if (incoterms == null) { throw new AdempiereException("Incoterms not found by ID: " + id); } return incoterms;
} @Nullable public Incoterms getDefaultByOrgId(@NonNull final OrgId orgId) { return CoalesceUtil.coalesce(defaultByOrgId.get(orgId), defaultByOrgId.get(OrgId.ANY)); } @NonNull Incoterms getByValue(@NonNull final String value, @NonNull final OrgId orgId) { final Incoterms incoterms = CoalesceUtil.coalesce(byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(orgId).build()), byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(OrgId.ANY).build())); if (incoterms == null) { throw new AdempiereException("Incoterms not found by value: " + value + " and orgIds: " + orgId + " or " + OrgId.ANY); } return incoterms; } @Builder @Value private static class ValueAndOrgId { @NonNull String value; @NonNull OrgId orgId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\incoterms\IncotermsRepository.java
1
请完成以下Java代码
public String getCreateUserId() { return createUserId; } public Date getStartTime() { return startTime; } public Date getEndTime() { return endTime; } public Date getRemovalTime() { return removalTime; } public Date getExecutionStartTime() { return executionStartTime; } public void setExecutionStartTime(final Date executionStartTime) { this.executionStartTime = executionStartTime;
} public static HistoricBatchDto fromBatch(HistoricBatch historicBatch) { HistoricBatchDto dto = new HistoricBatchDto(); dto.id = historicBatch.getId(); dto.type = historicBatch.getType(); dto.totalJobs = historicBatch.getTotalJobs(); dto.batchJobsPerSeed = historicBatch.getBatchJobsPerSeed(); dto.invocationsPerBatchJob = historicBatch.getInvocationsPerBatchJob(); dto.seedJobDefinitionId = historicBatch.getSeedJobDefinitionId(); dto.monitorJobDefinitionId = historicBatch.getMonitorJobDefinitionId(); dto.batchJobDefinitionId = historicBatch.getBatchJobDefinitionId(); dto.tenantId = historicBatch.getTenantId(); dto.createUserId = historicBatch.getCreateUserId(); dto.startTime = historicBatch.getStartTime(); dto.endTime = historicBatch.getEndTime(); dto.removalTime = historicBatch.getRemovalTime(); dto.executionStartTime = historicBatch.getExecutionStartTime(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\HistoricBatchDto.java
1
请完成以下Java代码
public int hashCode() { int result = (this.parentAcl != null) ? this.parentAcl.hashCode() : 0; result = 31 * result + this.aclAuthorizationStrategy.hashCode(); result = 31 * result + ((this.permissionGrantingStrategy != null) ? this.permissionGrantingStrategy.hashCode() : 0); result = 31 * result + ((this.aces != null) ? this.aces.hashCode() : 0); result = 31 * result + this.objectIdentity.hashCode(); result = 31 * result + this.id.hashCode(); result = 31 * result + ((this.owner != null) ? this.owner.hashCode() : 0); result = 31 * result + ((this.loadedSids != null) ? this.loadedSids.hashCode() : 0); result = 31 * result + (this.entriesInheriting ? 1 : 0); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AclImpl["); sb.append("id: ").append(this.id).append("; "); sb.append("objectIdentity: ").append(this.objectIdentity).append("; "); sb.append("owner: ").append(this.owner).append("; "); int count = 0; for (AccessControlEntry ace : this.aces) { count++; if (count == 1) { sb.append("\n");
} sb.append(ace).append("\n"); } if (count == 0) { sb.append("no ACEs; "); } sb.append("inheriting: ").append(this.entriesInheriting).append("; "); sb.append("parent: ").append((this.parentAcl == null) ? "Null" : this.parentAcl.getObjectIdentity().toString()); sb.append("; "); sb.append("aclAuthorizationStrategy: ").append(this.aclAuthorizationStrategy).append("; "); sb.append("permissionGrantingStrategy: ").append(this.permissionGrantingStrategy); sb.append("]"); return sb.toString(); } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\AclImpl.java
1
请完成以下Java代码
protected void dispatchExecutionTimeOut(Job job, ExecutionEntity execution, CommandContext commandContext) { // subprocesses for (ExecutionEntity subExecution : execution.getExecutions()) { dispatchExecutionTimeOut(job, subExecution, commandContext); } // call activities ExecutionEntity subProcessInstance = commandContext.getExecutionEntityManager().findSubProcessInstanceBySuperExecutionId(execution.getId()); if (subProcessInstance != null) { dispatchExecutionTimeOut(job, subProcessInstance, commandContext); } // activity with timer boundary event ActivityImpl activity = execution.getActivity(); if (activity != null && activity.getActivityBehavior() != null) { dispatchActivityTimeOut(job, activity, execution, commandContext);
} } protected void dispatchActivityTimeOut(Job job, ActivityImpl activity, ExecutionEntity execution, CommandContext commandContext) { commandContext.getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createActivityCancelledEvent(activity.getId(), (String) activity.getProperties().get("name"), execution.getId(), execution.getProcessInstanceId(), execution.getProcessDefinitionId(), (String) activity.getProperties().get("type"), activity.getActivityBehavior().getClass().getCanonicalName(), job), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerExecuteNestedActivityJobHandler.java
1
请完成以下Java代码
public void setM_InOut_ID (int M_InOut_ID) { if (M_InOut_ID < 1) set_Value (COLUMNNAME_M_InOut_ID, null); else set_Value (COLUMNNAME_M_InOut_ID, Integer.valueOf(M_InOut_ID)); } /** Get Shipment/Receipt. @return Material Shipment Document */ public int getM_InOut_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOut_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_InOutLine getM_InOutLine() throws RuntimeException { return (I_M_InOutLine)MTable.get(getCtx(), I_M_InOutLine.Table_Name) .getPO(getM_InOutLine_ID(), get_TrxName()); } /** Set Shipment/Receipt Line. @param M_InOutLine_ID Line on Shipment or Receipt document */ public void setM_InOutLine_ID (int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_Value (COLUMNNAME_M_InOutLine_ID, null); else set_Value (COLUMNNAME_M_InOutLine_ID, Integer.valueOf(M_InOutLine_ID)); } /** Get Shipment/Receipt Line. @return Line on Shipment or Receipt document */ public int getM_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product.
@return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_LandedCost.java
1
请完成以下Java代码
public class AlarmUpdateRequest implements AlarmModificationRequest { @NotNull @Schema(description = "JSON object with Tenant Id", accessMode = Schema.AccessMode.READ_ONLY) private TenantId tenantId; @NotNull @Schema(description = "JSON object with the alarm Id. " + "Specify this field to update the alarm. " + "Referencing non-existing alarm Id will cause error. " + "Omit this field to create new alarm.") private AlarmId alarmId; @NotNull @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Alarm severity", example = "CRITICAL") private AlarmSeverity severity; @Schema(description = "Timestamp of the alarm start time, in milliseconds", example = "1634058704565") private long startTs; @Schema(description = "Timestamp of the alarm end time(last time update), in milliseconds", example = "1634111163522") private long endTs; @ToString.Exclude @NoXss @Schema(description = "JSON object with alarm details") private JsonNode details; @Valid
@Schema(description = "JSON object with propagation details") private AlarmPropagationInfo propagation; private UserId userId; public static AlarmUpdateRequest fromAlarm(Alarm a) { return fromAlarm(a, null); } public static AlarmUpdateRequest fromAlarm(Alarm a, UserId userId) { return AlarmUpdateRequest.builder() .tenantId(a.getTenantId()) .alarmId(a.getId()) .severity((a.getSeverity())) .startTs(a.getStartTs()) .endTs(a.getEndTs()) .details(a.getDetails()) .propagation(AlarmPropagationInfo.builder() .propagate(a.isPropagate()) .propagateToOwner(a.isPropagateToOwner()) .propagateToTenant(a.isPropagateToTenant()) .propagateRelationTypes(a.getPropagateRelationTypes()).build()) .userId(userId) .build(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\alarm\AlarmUpdateRequest.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getCloseNotifyFlushTimeout() { return closeNotifyFlushTimeout; } public void setCloseNotifyFlushTimeout(Duration closeNotifyFlushTimeout) { this.closeNotifyFlushTimeout = closeNotifyFlushTimeout; } public Duration getCloseNotifyReadTimeout() { return closeNotifyReadTimeout; } public void setCloseNotifyReadTimeout(Duration closeNotifyReadTimeout) { this.closeNotifyReadTimeout = closeNotifyReadTimeout; } public String getSslBundle() { return sslBundle; } public void setSslBundle(String sslBundle) { this.sslBundle = sslBundle; } @Override public String toString() { return new ToStringCreator(this).append("useInsecureTrustManager", useInsecureTrustManager) .append("trustedX509Certificates", trustedX509Certificates) .append("handshakeTimeout", handshakeTimeout) .append("closeNotifyFlushTimeout", closeNotifyFlushTimeout) .append("closeNotifyReadTimeout", closeNotifyReadTimeout) .toString(); } } public static class Websocket { /** Max frame payload length. */ private Integer maxFramePayloadLength; /** Proxy ping frames to downstream services, defaults to true. */ private boolean proxyPing = true; public Integer getMaxFramePayloadLength() {
return this.maxFramePayloadLength; } public void setMaxFramePayloadLength(Integer maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isProxyPing() { return proxyPing; } public void setProxyPing(boolean proxyPing) { this.proxyPing = proxyPing; } @Override public String toString() { return new ToStringCreator(this).append("maxFramePayloadLength", maxFramePayloadLength) .append("proxyPing", proxyPing) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class Recipe { @Id @Column(name = "cocktail") private String cocktail; @Column private String instructions; public Recipe() { } public Recipe(String cocktail, String instructions) { this.cocktail = cocktail; this.instructions = instructions; } public String getCocktail() { return cocktail; }
public String getInstructions() { return instructions; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Recipe recipe = (Recipe) o; return Objects.equals(cocktail, recipe.cocktail) && Objects.equals(instructions, recipe.instructions); } @Override public int hashCode() { return Objects.hash(cocktail, instructions); } }
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\unrelated\entities\Recipe.java
2
请完成以下Java代码
public int getDropShip_User_ID() { return get_ValueAsInt(COLUMNNAME_DropShip_User_ID); } @Override public void setEventDate (final @Nullable java.sql.Timestamp EventDate) { set_Value (COLUMNNAME_EventDate, EventDate); } @Override public java.sql.Timestamp getEventDate() { return get_ValueAsTimestamp(COLUMNNAME_EventDate); } /** * EventType AD_Reference_ID=540013 * Reference name: C_SubscriptionProgress EventType */ public static final int EVENTTYPE_AD_Reference_ID=540013; /** Delivery = DE */ public static final String EVENTTYPE_Delivery = "DE"; /** BeginOfPause = PB */ public static final String EVENTTYPE_BeginOfPause = "PB"; /** EndOfPause = PE */ public static final String EVENTTYPE_EndOfPause = "PE"; /** Quantity = QT */ public static final String EVENTTYPE_Quantity = "QT"; /** Price = P */ public static final String EVENTTYPE_Price = "P"; @Override public void setEventType (final java.lang.String EventType) { set_ValueNoCheck (COLUMNNAME_EventType, EventType); } @Override public java.lang.String getEventType() { return get_ValueAsString(COLUMNNAME_EventType); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_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 setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) {
set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } /** * Status AD_Reference_ID=540002 * Reference name: C_SubscriptionProgress Status */ public static final int STATUS_AD_Reference_ID=540002; /** Planned = P */ public static final String STATUS_Planned = "P"; /** Open = O */ public static final String STATUS_Open = "O"; /** Delivered = D */ public static final String STATUS_Delivered = "D"; /** InPicking = C */ public static final String STATUS_InPicking = "C"; /** Done = E */ public static final String STATUS_Done = "E"; /** Delayed = H */ public static final String STATUS_Delayed = "H"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscriptionProgress.java
1
请完成以下Java代码
public class AuthorizationDeniedEvent<T> extends AuthorizationEvent implements ResolvableTypeProvider { /** * @since 6.4 */ public AuthorizationDeniedEvent(Supplier<Authentication> authentication, T object, AuthorizationResult result) { super(authentication, object, result); } /** * Get the object to which access was requested * @return the object to which access was requested * @since 5.8 */ @Override @SuppressWarnings("unchecked")
public T getObject() { return (T) getSource(); } /** * Get {@link ResolvableType} of this class. * @return {@link ResolvableType} * @since 6.5 */ @Override public ResolvableType getResolvableType() { return ResolvableType.forClassWithGenerics(getClass(), ResolvableType.forInstance(getObject())); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\event\AuthorizationDeniedEvent.java
1
请在Spring Boot框架中完成以下Java代码
public ServerFlowConfig setMaxOccupyRatio(Double maxOccupyRatio) { this.maxOccupyRatio = maxOccupyRatio; return this; } public Integer getIntervalMs() { return intervalMs; } public ServerFlowConfig setIntervalMs(Integer intervalMs) { this.intervalMs = intervalMs; return this; } public Integer getSampleCount() { return sampleCount; } public ServerFlowConfig setSampleCount(Integer sampleCount) { this.sampleCount = sampleCount; return this; }
public Double getMaxAllowedQps() { return maxAllowedQps; } public ServerFlowConfig setMaxAllowedQps(Double maxAllowedQps) { this.maxAllowedQps = maxAllowedQps; return this; } @Override public String toString() { return "ServerFlowConfig{" + "namespace='" + namespace + '\'' + ", exceedCount=" + exceedCount + ", maxOccupyRatio=" + maxOccupyRatio + ", intervalMs=" + intervalMs + ", sampleCount=" + sampleCount + ", maxAllowedQps=" + maxAllowedQps + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\config\ServerFlowConfig.java
2
请完成以下Java代码
public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_Value (COLUMNNAME_PP_Order_ID, null); else set_Value (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setPP_Order_Weighting_Run_ID (final int PP_Order_Weighting_Run_ID) { if (PP_Order_Weighting_Run_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, PP_Order_Weighting_Run_ID); } @Override public int getPP_Order_Weighting_Run_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_Run_ID); } @Override public org.eevolution.model.I_PP_Weighting_Spec getPP_Weighting_Spec() { return get_ValueAsPO(COLUMNNAME_PP_Weighting_Spec_ID, org.eevolution.model.I_PP_Weighting_Spec.class); } @Override public void setPP_Weighting_Spec(final org.eevolution.model.I_PP_Weighting_Spec PP_Weighting_Spec) { set_ValueFromPO(COLUMNNAME_PP_Weighting_Spec_ID, org.eevolution.model.I_PP_Weighting_Spec.class, PP_Weighting_Spec); } @Override public void setPP_Weighting_Spec_ID (final int PP_Weighting_Spec_ID) { if (PP_Weighting_Spec_ID < 1) set_Value (COLUMNNAME_PP_Weighting_Spec_ID, null); else set_Value (COLUMNNAME_PP_Weighting_Spec_ID, PP_Weighting_Spec_ID); } @Override public int getPP_Weighting_Spec_ID() { return get_ValueAsInt(COLUMNNAME_PP_Weighting_Spec_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 setTargetWeight (final BigDecimal TargetWeight) { set_Value (COLUMNNAME_TargetWeight, TargetWeight); } @Override public BigDecimal getTargetWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TargetWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTolerance_Perc (final BigDecimal Tolerance_Perc) { set_Value (COLUMNNAME_Tolerance_Perc, Tolerance_Perc); } @Override public BigDecimal getTolerance_Perc() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Tolerance_Perc); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeightChecksRequired (final int WeightChecksRequired) { set_Value (COLUMNNAME_WeightChecksRequired, WeightChecksRequired); } @Override public int getWeightChecksRequired() { return get_ValueAsInt(COLUMNNAME_WeightChecksRequired); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Weighting_Run.java
1
请完成以下Java代码
public final void put(@NonNull final IView view) { views.put(view.getViewId(), DataEntryDetailsView.cast(view)); } @Nullable @Override public IView getByIdOrNull(final ViewId viewId) { return views.getIfPresent(viewId); } @Override public void closeById(final ViewId viewId, final ViewCloseAction closeAction) {
} @Override public Stream<IView> streamAllViews() { return Stream.empty(); } @Override public void invalidateView(final ViewId viewId) { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\view\DataEntryDedailsViewFactory.java
1
请完成以下Spring Boot application配置
spring: application: name: zipkin-server datasource: url: jdbc:mysql://127.0.0.1:3306/zipkin?useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.jdbc.Driver userna
me: root password: 123456 server: port: 9100 zipkin: storage: type: mysql
repos\SpringAll-master\43.Spring-Cloud-Sleuth\Zipkin-Server\src\main\resources\application.yml
2
请完成以下Java代码
public int getAD_Org_ID() { return orderLine.getAD_Org_ID(); } @Override public boolean isSOTrx() { final I_C_Order order = getOrder(); return order.isSOTrx(); } @Override public I_C_BPartner getC_BPartner() {
final I_C_Order order = getOrder(); return InterfaceWrapperHelper.create(Services.get(IOrderBL.class).getBPartnerOrNull(order), I_C_BPartner.class); } private I_C_Order getOrder() { final I_C_Order order = orderLine.getC_Order(); if (order == null) { throw new AdempiereException("Order not set for" + orderLine); } return order; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\OrderLineBPartnerAware.java
1
请完成以下Java代码
public String getDokumentID() { return dokumentID; } /** * Sets the value of the dokumentID property. * * @param value * allowed object is * {@link String } * */ public void setDokumentID(String value) { this.dokumentID = value; } /** * Gets the value of the abholzeitpunkt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getAbholzeitpunkt() { return abholzeitpunkt; } /** * Sets the value of the abholzeitpunkt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setAbholzeitpunkt(XMLGregorianCalendar value) { this.abholzeitpunkt = value; } /** * Gets the value of the tour property. * * @return * possible object is * {@link String } * */ public String getTour() { return tour; } /** * Sets the value of the tour property. * * @param value * allowed object is * {@link String } * */ public void setTour(String value) { this.tour = value; } /** * Gets the value of the retourenAnteilTyp property. * * @return * possible object is * {@link RetourenAnteilTypType }
* */ public RetourenAnteilTypType getRetourenAnteilTyp() { return retourenAnteilTyp; } /** * Sets the value of the retourenAnteilTyp property. * * @param value * allowed object is * {@link RetourenAnteilTypType } * */ public void setRetourenAnteilTyp(RetourenAnteilTypType value) { this.retourenAnteilTyp = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;extension base="{urn:msv3:v2}RetourePositionType"&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Position extends RetourePositionType { } } }
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\RetourenavisAnkuendigungAntwort.java
1
请完成以下Java代码
public class AuthorId implements Serializable { private static final long serialVersionUID = 1L; private String name; private Long authorId; public AuthorId() { } public AuthorId(String name, Long authorId) { this.name = name; this.authorId = authorId; } public String getName() { return name; } public Long getAuthorId() { return authorId; } @Override public int hashCode() { int hash = 3; hash = 23 * hash + Objects.hashCode(this.name); hash = (int) (23 * hash + this.authorId); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; }
if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AuthorId other = (AuthorId) obj; if (this.authorId != other.authorId) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } return true; } @Override public String toString() { return "AuthorId{" + "name=" + name + ", authorId=" + authorId + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeySeqIdClass\src\main\java\com\bookstore\entity\AuthorId.java
1
请完成以下Java代码
public static void main(String[] args) { var client = Client.getClient(); List<ChatMessage> history = new ArrayList<>(); history.add(SystemMessage.of( "You are a helpful travel assistant. Answer in at least 150 words." )); try (Scanner scanner = new Scanner(System.in)) { while (true) { System.out.print("\nYou: "); String input = scanner.nextLine(); if (input == null || input.isBlank()) { continue; } if ("exit".equalsIgnoreCase(input.trim())) { break; } history.add(UserMessage.of(input)); ChatRequest.ChatRequestBuilder chatRequestBuilder = ChatRequest.builder().model(Client.CHAT_MODEL); for (ChatMessage message : history) { chatRequestBuilder.message(message);
} ChatRequest chatRequest = chatRequestBuilder.build(); CompletableFuture<Stream<Chat>> chatStreamFuture = client.chatCompletions().createStream(chatRequest); Stream<Chat> chatStream = chatStreamFuture.join(); StringBuilder replyBuilder = new StringBuilder(); chatStream.forEach(chunk -> { String content = chunk.firstContent(); replyBuilder.append(content); System.out.print(content); }); String reply = replyBuilder.toString(); history.add(AssistantMessage.of(reply)); } } } }
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\simpleopenai\SwitchingToStreamingResponses.java
1
请完成以下Java代码
default Instant getExpiresAt() { return this.getClaimAsInstant(IdTokenClaimNames.EXP); } /** * Returns the time at which the ID Token was issued {@code (iat)}. * @return the time at which the ID Token was issued */ default Instant getIssuedAt() { return this.getClaimAsInstant(IdTokenClaimNames.IAT); } /** * Returns the time when the End-User authentication occurred {@code (auth_time)}. * @return the time when the End-User authentication occurred */ default Instant getAuthenticatedAt() { return this.getClaimAsInstant(IdTokenClaimNames.AUTH_TIME); } /** * Returns a {@code String} value {@code (nonce)} used to associate a Client session * with an ID Token, and to mitigate replay attacks. * @return the nonce used to associate a Client session with an ID Token */ default String getNonce() { return this.getClaimAsString(IdTokenClaimNames.NONCE); } /** * Returns the Authentication Context Class Reference {@code (acr)}. * @return the Authentication Context Class Reference */ default String getAuthenticationContextClass() { return this.getClaimAsString(IdTokenClaimNames.ACR); } /** * Returns the Authentication Methods References {@code (amr)}.
* @return the Authentication Methods References */ default List<String> getAuthenticationMethods() { return this.getClaimAsStringList(IdTokenClaimNames.AMR); } /** * Returns the Authorized party {@code (azp)} to which the ID Token was issued. * @return the Authorized party to which the ID Token was issued */ default String getAuthorizedParty() { return this.getClaimAsString(IdTokenClaimNames.AZP); } /** * Returns the Access Token hash value {@code (at_hash)}. * @return the Access Token hash value */ default String getAccessTokenHash() { return this.getClaimAsString(IdTokenClaimNames.AT_HASH); } /** * Returns the Authorization Code hash value {@code (c_hash)}. * @return the Authorization Code hash value */ default String getAuthorizationCodeHash() { return this.getClaimAsString(IdTokenClaimNames.C_HASH); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\IdTokenClaimAccessor.java
1
请完成以下Java代码
public void onCountryChanged(final I_C_Campaign_Price record) { final CountryId countryId = CountryId.ofRepoIdOrNull(record.getC_Country_ID()); if (countryId == null) { return; } updateCurrency(record, countryId); } private void updateCurrency(final I_C_Campaign_Price record, final CountryId countryId) { countriesRepo.getCountryCurrencyId(countryId).ifPresent(currencyId -> record.setC_Currency_ID(currencyId.getRepoId())); } @CalloutMethod(columnNames = I_C_Campaign_Price.COLUMNNAME_M_Product_ID, skipIfCopying = true) public void onProductChanged(final I_C_Campaign_Price record) { final ProductId productId = ProductId.ofRepoIdOrNull(record.getM_Product_ID()); if (productId == null) { return; }
final UomId stockUomId = productBL.getStockUOMId(productId); record.setC_UOM_ID(stockUomId.getRepoId()); updatePricingInfo(record); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Campaign_Price.COLUMNNAME_C_BPartner_ID, I_C_Campaign_Price.COLUMNNAME_C_BP_Group_ID, I_C_Campaign_Price.COLUMNNAME_M_PricingSystem_ID }) public void beforeSave(final I_C_Campaign_Price record) { if (record.getC_BPartner_ID() <= 0 && record.getC_BP_Group_ID() <= 0 && record.getM_PricingSystem_ID() <= 0) { throw new AdempiereException(ERR_MandatoryFields); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\campaign_price\callout\C_Campaign_Price.java
1
请在Spring Boot框架中完成以下Java代码
public class CandidateChangeService { private static final Logger logger = LogManager.getLogger(CandidateChangeService.class); private final ImmutableMap<CandidateType, CandidateHandler> type2handler; public CandidateChangeService(@NonNull final Collection<CandidateHandler> handlers) { type2handler = createMapOfHandlers(handlers); logger.info("Handlers: {}", type2handler); } public CandidateSaveResult onCandidateNewOrChange(@NonNull final Candidate candidate) { return onCandidateNewOrChange(candidate, OnNewOrChangeAdvise.DEFAULT); } /** * Persists the given candidate and decides if further events shall be fired. */ public CandidateSaveResult onCandidateNewOrChange( @NonNull final Candidate candidate, @NonNull final OnNewOrChangeAdvise advise) { candidate.validateNonStockCandidate(); final CandidateHandler candidateChangeHandler = getHandlerFor(candidate); return candidateChangeHandler.onCandidateNewOrChange(candidate, advise); } public void onCandidateDelete(@NonNull final Candidate candidate) { candidate.validateNonStockCandidate(); final CandidateHandler candidateChangeHandler = getHandlerFor(candidate); candidateChangeHandler.onCandidateDelete(candidate); } private CandidateHandler getHandlerFor(final Candidate candidate) {
final CandidateHandler candidateChangeHandler = type2handler.get(candidate.getType()); if (candidateChangeHandler == null) { throw new AdempiereException("The given candidate has an unsupported type") .appendParametersToMessage() .setParameter("type", candidate.getType()) .setParameter("candidate", candidate); } return candidateChangeHandler; } @VisibleForTesting static ImmutableMap<CandidateType, CandidateHandler> createMapOfHandlers(@NonNull final Collection<CandidateHandler> handlers) { final ImmutableMap.Builder<CandidateType, CandidateHandler> builder = ImmutableMap.builder(); for (final CandidateHandler handler : handlers) { if (handler.getHandeledTypes().isEmpty()) { logger.warn("Skip handler because no handled types provided: {}", handler); continue; } for (final CandidateType type : handler.getHandeledTypes()) { builder.put(type, handler); // builder already prohibits duplicate keys } } return builder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\candidatechange\CandidateChangeService.java
2
请在Spring Boot框架中完成以下Java代码
public String deleteBook(String id) throws BookNotFoundException { Long bookId = bookService.deleteById(id); if (1 == bookId) { return "Book deleted"; } else { throw new BookNotFoundException(id); } } @Get("/{id}") public Book findById(@PathVariable("id") String identifier) throws BookNotFoundException { Book book = bookService.findById(identifier); if (null == book) { throw new BookNotFoundException(identifier); } else { return book; } }
@Get("/published-after") public Flux<Book> findByYearGreaterThan(@QueryValue(value = "year") int year) { return bookService.findByYearGreaterThan(year); } @Error(exception = ConstraintViolationException.class) public MutableHttpResponse<String> onSavedFailed(ConstraintViolationException ex) { return HttpResponse.badRequest(ex.getConstraintViolations().stream() .map(cv -> cv.getPropertyPath() + " " + cv.getMessage()) .toList().toString()); } @Error(exception = BookNotFoundException.class) public HttpResponse<String> onSavedFailed(BookNotFoundException ex) { return HttpResponse.notFound(ex.getMessage()); } }
repos\tutorials-master\microservices-modules\micronaut-reactive\src\main\java\com\baeldung\micronautreactive\controller\BookController.java
2
请完成以下Java代码
public void setPointsSum_Forecasted (final BigDecimal PointsSum_Forecasted) { set_Value (COLUMNNAME_PointsSum_Forecasted, PointsSum_Forecasted); } @Override public BigDecimal getPointsSum_Forecasted() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Forecasted); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_Invoiceable (final BigDecimal PointsSum_Invoiceable) { set_ValueNoCheck (COLUMNNAME_PointsSum_Invoiceable, PointsSum_Invoiceable); } @Override public BigDecimal getPointsSum_Invoiceable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiceable); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_Invoiced (final BigDecimal PointsSum_Invoiced) { set_Value (COLUMNNAME_PointsSum_Invoiced, PointsSum_Invoiced); } @Override
public BigDecimal getPointsSum_Invoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_Settled (final BigDecimal PointsSum_Settled) { set_Value (COLUMNNAME_PointsSum_Settled, PointsSum_Settled); } @Override public BigDecimal getPointsSum_Settled() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Settled); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_ToSettle (final BigDecimal PointsSum_ToSettle) { set_Value (COLUMNNAME_PointsSum_ToSettle, PointsSum_ToSettle); } @Override public BigDecimal getPointsSum_ToSettle() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_ToSettle); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Share.java
1
请完成以下Java代码
public String getUOMSymbol() { return getUOM().getUOMSymbol(); } public I_C_UOM getUOM() { if (inventoryType.isPhysical()) { final Quantity qtyBook = getQtyBook(); final Quantity qtyCount = getQtyCount(); Quantity.assertSameUOM(qtyBook, qtyCount); return qtyBook.getUOM(); } else if (inventoryType.isInternalUse()) { return getQtyInternalUse().getUOM(); } else { throw new AdempiereException("Unknown inventory type: " + inventoryType); } } public Quantity getQtyInternalUse() { assertInternalUseInventory(); return qtyInternalUse; } public Quantity getQtyCount() { assertPhysicalInventory(); return qtyCount; } public Quantity getQtyBook() { assertPhysicalInventory(); return qtyBook; } public Quantity getQtyCountMinusBooked() { return getQtyCount().subtract(getQtyBook()); } /** * @param qtyCountToAdd needs to have the same UOM as this instance's current qtyCount. */ public InventoryLineHU withAddingQtyCount(@NonNull final Quantity qtyCountToAdd) { return withQtyCount(getQtyCount().add(qtyCountToAdd)); } public InventoryLineHU withZeroQtyCount() { return withQtyCount(getQtyCount().toZero()); } public InventoryLineHU withQtyCount(@NonNull final Quantity newQtyCount) { assertPhysicalInventory(); return toBuilder().qtyCount(newQtyCount).build();
} public static ImmutableSet<HuId> extractHuIds(@NonNull final Collection<InventoryLineHU> lineHUs) { return extractHuIds(lineHUs.stream()); } static ImmutableSet<HuId> extractHuIds(@NonNull final Stream<InventoryLineHU> lineHUs) { return lineHUs .map(InventoryLineHU::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } public InventoryLineHU convertQuantities(@NonNull final UnaryOperator<Quantity> qtyConverter) { return toBuilder() .qtyCount(qtyConverter.apply(getQtyCount())) .qtyBook(qtyConverter.apply(getQtyBook())) .build(); } public InventoryLineHU updatingFrom(@NonNull final InventoryLineCountRequest request) { return toBuilder().updatingFrom(request).build(); } public static InventoryLineHU of(@NonNull final InventoryLineCountRequest request) { return builder().updatingFrom(request).build(); } // // // // ------------------------------------------------------------------------- // // // @SuppressWarnings("unused") public static class InventoryLineHUBuilder { InventoryLineHUBuilder updatingFrom(@NonNull final InventoryLineCountRequest request) { return huId(request.getHuId()) .huQRCode(HuId.equals(this.huId, request.getHuId()) ? this.huQRCode : null) .qtyInternalUse(null) .qtyBook(request.getQtyBook()) .qtyCount(request.getQtyCount()) .isCounted(true) .asiId(request.getAsiId()) ; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLineHU.java
1
请完成以下Java代码
public void setExternallyUpdatedAt (final @Nullable java.sql.Timestamp ExternallyUpdatedAt) { set_Value (COLUMNNAME_ExternallyUpdatedAt, ExternallyUpdatedAt); } @Override public java.sql.Timestamp getExternallyUpdatedAt() { return get_ValueAsTimestamp(COLUMNNAME_ExternallyUpdatedAt); } @Override public void setIsPrivateSale (final boolean IsPrivateSale) { set_Value (COLUMNNAME_IsPrivateSale, IsPrivateSale); } @Override public boolean isPrivateSale() { return get_ValueAsBoolean(COLUMNNAME_IsPrivateSale); } @Override public void setIsRentalEquipment (final boolean IsRentalEquipment) { set_Value (COLUMNNAME_IsRentalEquipment, IsRentalEquipment); } @Override public boolean isRentalEquipment() { return get_ValueAsBoolean(COLUMNNAME_IsRentalEquipment); } @Override public void setSalesLineId (final @Nullable String SalesLineId) { set_Value (COLUMNNAME_SalesLineId, SalesLineId); } @Override public String getSalesLineId() { return get_ValueAsString(COLUMNNAME_SalesLineId); } @Override public void setTimePeriod (final @Nullable BigDecimal TimePeriod)
{ set_Value (COLUMNNAME_TimePeriod, TimePeriod); } @Override public BigDecimal getTimePeriod() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUnit (final @Nullable String Unit) { set_Value (COLUMNNAME_Unit, Unit); } @Override public String getUnit() { return get_ValueAsString(COLUMNNAME_Unit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_OrderedArticleLine.java
1
请在Spring Boot框架中完成以下Java代码
private static String genKey(Integer id) { return "user::" + id; } // ========== 使用专属的 ReactiveRedisTemplate 的方式 ========= @Autowired private ReactiveRedisTemplate<String, UserCacheObject> userRedisTemplate; /** * 获得指定用户编号的用户 * * @param id 用户编号 * @return 用户 */ @GetMapping("/v2/get") public Mono<UserCacheObject> getV2(@RequestParam("id") Integer id) { String key = genKeyV2(id); return userRedisTemplate.opsForValue().get(key); } /** * 设置指定用户的信息
* * @param user 用户 * @return 是否成功 */ @PostMapping("/v2/set") public Mono<Boolean> setV2(UserCacheObject user) { String key = genKeyV2(user.getId()); return userRedisTemplate.opsForValue().set(key, user); } private static String genKeyV2(Integer id) { return "user::v2::" + id; } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-redis\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java
2
请完成以下Java代码
private boolean sendEmailNow(UserId toUserId, EMail email) { final EMailSentStatus emailSentStatus = email.send(); // X_AD_UserMail um = new X_AD_UserMail(getCtx(), 0, null); um.setClientOrg(this); um.setAD_User_ID(toUserId.getRepoId()); um.setSubject(email.getSubject()); um.setMailText(email.getMessageCRLF()); if (emailSentStatus.isSentOK()) { um.setMessageID(emailSentStatus.getMessageId()); um.setIsDelivered(X_AD_UserMail.ISDELIVERED_Yes); } else { um.setMessageID(emailSentStatus.getSentMsg()); um.setIsDelivered(X_AD_UserMail.ISDELIVERED_No); } um.saveEx(); // if (emailSentStatus.isSentOK()) { log.info("Sent Email: {} to {}", email.getSubject(), toUserId); return true; } else { log.warn("Could NOT Send Email: {} to {}: {} ({})", email.getSubject(), toUserId, emailSentStatus.getSentMsg(), getName()); return false; } } // sendEmailNow /** * Create EMail from User * * @param to recipient * @param subject sunject
* @param message nessage * @return EMail * @deprecated please use {@link de.metas.email.MailService} instead, and extend it as required. */ @Deprecated public @Nullable EMail createEMail( final EMailAddress to, final String subject, final String message, final boolean html) { try { final MailService mailService = SpringContextHolder.instance.getBean(MailService.class); final Mailbox mailbox = mailService.findMailbox(MailboxQuery.ofClientId(ClientId.ofRepoId(getAD_Client_ID()))); final EMailRequest mailRequest = EMailRequest.builder() .mailbox(mailbox) .to(to) .subject(subject) .message(message) .html(html) .build(); return mailService.createEMail(mailRequest); } catch (final Exception ex) { log.error("Failed to create the email", ex); return null; } } // createEMail // metas end } // MClient
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MClient.java
1
请完成以下Java代码
public String getDefinitionName() { return eventPayloadDefinition.getName(); } @Override public String getDefinitionType() { return eventPayloadDefinition.getType(); } @Override public Object getValue() { return value; } public void setValue(Object value) { this.value = value; }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EventPayloadInstanceImpl that = (EventPayloadInstanceImpl) o; return Objects.equals(eventPayloadDefinition, that.eventPayloadDefinition) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(eventPayloadDefinition, value); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\runtime\EventPayloadInstanceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> getMessages(@RequestParam(value = "conversationId", required = true) String conversationId) { return chatService.getMessages(conversationId); } /** * 清空消息 * * @return * @author chenrui * @date 2025/2/25 11:42 */ @IgnoreAuth @GetMapping(value = "/messages/clear/{conversationId}") public Result<?> clearMessage(@PathVariable(value = "conversationId") String conversationId) { return chatService.clearMessage(conversationId); } /** * 继续接收消息 * * @param requestId * @return * @author chenrui * @date 2025/8/11 17:49 */ @IgnoreAuth @GetMapping(value = "/receive/{requestId}") public SseEmitter receiveByRequestId(@PathVariable(name = "requestId", required = true) String requestId) { return chatService.receiveByRequestId(requestId); } /** * 根据请求ID停止某个请求的处理 * * @param requestId 请求的唯一标识符,用于识别和停止特定的请求 * @return 返回一个Result对象,表示停止请求的结果 * @author chenrui * @date 2025/2/25 11:42 */ @IgnoreAuth @GetMapping(value = "/stop/{requestId}") public Result<?> stop(@PathVariable(name = "requestId", required = true) String requestId) { return chatService.stop(requestId); }
/** * 上传文件 * for [QQYUN-12135]AI聊天,上传图片提示非法token * * @param request * @param response * @return * @throws Exception * @author chenrui * @date 2025/4/25 11:04 */ @IgnoreAuth @PostMapping(value = "/upload") public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws Exception { String bizPath = "airag"; MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 获取上传文件对象 MultipartFile file = multipartRequest.getFile("file"); String savePath; if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) { savePath = CommonUtils.uploadLocal(file, bizPath, uploadpath); } else { savePath = CommonUtils.upload(file, bizPath, uploadType); } Result<?> result = new Result<>(); result.setMessage(savePath); result.setSuccess(true); return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\controller\AiragChatController.java
2
请在Spring Boot框架中完成以下Java代码
final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); if (env.getProperty("hibernate.hbm2ddl.auto") != null) { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); } if (env.getProperty("hibernate.dialect") != null) { hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); } if (env.getProperty("hibernate.show_sql") != null) { hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); } return hibernateProperties; } } @Configuration @Profile("h2") @PropertySource("classpath:persistence-h2.properties") class H2Config {
} @Configuration @Profile("hsqldb") @PropertySource("classpath:persistence-hsqldb.properties") class HsqldbConfig { } @Configuration @Profile("derby") @PropertySource("classpath:persistence-derby.properties") class DerbyConfig { } @Configuration @Profile("sqlite") @PropertySource("classpath:persistence-sqlite.properties") class SqliteConfig { }
repos\tutorials-master\persistence-modules\spring-data-rest\src\main\java\com\baeldung\books\config\DbConfig.java
2
请在Spring Boot框架中完成以下Java代码
public IPage<RoleVO> selectRolePage(IPage<RoleVO> page, RoleVO role) { return page.setRecords(baseMapper.selectRolePage(page, role)); } @Override public List<RoleVO> tree(String tenantId) { String userRole = SecureUtil.getUserRole(); String excludeRole = null; if (!CollectionUtil.contains(Func.toStrArray(userRole), RoleConstant.ADMIN)) { excludeRole = RoleConstant.ADMIN; } return ForestNodeMerger.merge(baseMapper.tree(tenantId, excludeRole)); } @Override public boolean grant(@NotEmpty List<Long> roleIds, @NotEmpty List<Long> menuIds, List<Long> dataScopeIds) { // 删除角色配置的菜单集合 roleMenuService.remove(Wrappers.<RoleMenu>update().lambda().in(RoleMenu::getRoleId, roleIds)); // 组装配置 List<RoleMenu> roleMenus = new ArrayList<>(); roleIds.forEach(roleId -> menuIds.forEach(menuId -> { RoleMenu roleMenu = new RoleMenu(); roleMenu.setRoleId(roleId); roleMenu.setMenuId(menuId); roleMenus.add(roleMenu); })); // 新增配置 roleMenuService.saveBatch(roleMenus); // 删除角色配置的数据权限集合 roleScopeService.remove(Wrappers.<RoleScope>update().lambda().in(RoleScope::getRoleId, roleIds)); // 组装配置 List<RoleScope> roleDataScopes = new ArrayList<>();
roleIds.forEach(roleId -> dataScopeIds.forEach(scopeId -> { RoleScope roleScope = new RoleScope(); roleScope.setRoleId(roleId); roleScope.setScopeId(scopeId); roleDataScopes.add(roleScope); })); // 新增配置 roleScopeService.saveBatch(roleDataScopes); return true; } @Override public String getRoleIds(String tenantId, String roleNames) { List<Role> roleList = baseMapper.selectList(Wrappers.<Role>query().lambda().eq(Role::getTenantId, tenantId).in(Role::getRoleName, Func.toStrList(roleNames))); if (roleList != null && roleList.size() > 0) { return roleList.stream().map(role -> Func.toStr(role.getId())).distinct().collect(Collectors.joining(",")); } return null; } @Override public List<String> getRoleNames(String roleIds) { return baseMapper.getRoleNames(Func.toLongArray(roleIds)); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\RoleServiceImpl.java
2
请完成以下Java代码
public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java " + Builder.class.getName() + " <expression string>"); System.exit(1); } PrintWriter out = new PrintWriter(System.out); Tree tree = null; try { tree = new Builder(Feature.METHOD_INVOCATIONS).build(args[0]); } catch (TreeBuilderException e) { System.out.println(e.getMessage()); System.exit(0); } NodePrinter.dump(out, tree.getRoot()); if (!tree.getFunctionNodes().iterator().hasNext() && !tree.getIdentifierNodes().iterator().hasNext()) { ELContext context = new ELContext() { @Override public VariableMapper getVariableMapper() { return null; } @Override public FunctionMapper getFunctionMapper() { return null;
} @Override public ELResolver getELResolver() { return null; } }; out.print(">> "); try { out.println(tree.getRoot().getValue(new Bindings(null, null), context, null)); } catch (ELException e) { out.println(e.getMessage()); } } out.flush(); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\Builder.java
1
请在Spring Boot框架中完成以下Java代码
public void execute() { trxManager.runInThreadInheritedTrx(this::execute0); } private void execute0() { orderPayScheduleService.deleteByOrderId(OrderId.ofRepoId(orderRecord.getC_Order_ID())); final OrderSchedulingContext context = orderPayScheduleService.extractContext(orderRecord); if (context == null) { return; // Nothing to schedule } if (!context.getPaymentTerm().isComplex() ) { return; // Nothing to schedule } final List<PaymentTermBreak> termBreaks = context.getPaymentTerm().getSortedBreaks(); final ImmutableList.Builder<OrderPayScheduleCreateRequest.Line> linesBuilder = ImmutableList.builder(); Money totalScheduledAmount = Money.zero(context.getGrandTotal().getCurrencyId()); for (int i = 0; i < termBreaks.size() - 1; i++) { final PaymentTermBreak termBreak = termBreaks.get(i); // Calculate amount by percent final Money lineDueAmount = context.getGrandTotal().multiply(termBreak.getPercent(), context.getPrecision()); final OrderPayScheduleCreateRequest.Line line = toOrderPayScheduleCreateRequestLine( context, termBreak, lineDueAmount ); linesBuilder.add(line); totalScheduledAmount = totalScheduledAmount.add(lineDueAmount); }
final PaymentTermBreak lastTermBreak = termBreaks.get(termBreaks.size() - 1); // Calculate the exact amount needed for the last line: Grand Total - accumulated total final Money lastLineDueAmount = context.getGrandTotal().subtract(totalScheduledAmount); final OrderPayScheduleCreateRequest.Line lastLine = toOrderPayScheduleCreateRequestLine( context, lastTermBreak, lastLineDueAmount ); linesBuilder.add(lastLine); final OrderPayScheduleCreateRequest request = OrderPayScheduleCreateRequest.builder() .orderId(context.getOrderId()) .lines(linesBuilder.build()) .build(); orderPayScheduleService.create(request); } private static OrderPayScheduleCreateRequest.Line toOrderPayScheduleCreateRequestLine( @NonNull final OrderSchedulingContext context, @NonNull final PaymentTermBreak termBreak, @NonNull final Money dueAmount) { final DueDateAndStatus result = context.computeDueDate(termBreak); return OrderPayScheduleCreateRequest.Line.builder() .dueDate(result.getDueDate()) .dueAmount(dueAmount) .paymentTermBreakId(termBreak.getId()) .referenceDateType(termBreak.getReferenceDateType()) .percent(termBreak.getPercent()) .orderPayScheduleStatus(result.getStatus()) .offsetDays(termBreak.getOffsetDays()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\service\OrderPayScheduleCreateCommand.java
2
请在Spring Boot框架中完成以下Java代码
public DistributionJob complete(@NonNull final DistributionJobId jobId, @NonNull final UserId callerId) { final DistributionJob job = getJobById(jobId); job.assertCanEdit(callerId); return complete(job); } public DistributionJob complete(@NonNull final DistributionJob job) { // just to make sure there is nothing reserved to this job distributionJobHUReservationService.releaseAllReservations(job); final DDOrderId ddOrderId = job.getDdOrderId(); ddOrderService.close(ddOrderId); ddOrderService.print(ddOrderId); return getJobById(ddOrderId); } public void abort(@NonNull final DistributionJob job) { abort().job(job).execute(); } private DistributionJobAbortCommand.DistributionJobAbortCommandBuilder abort() { return DistributionJobAbortCommand.builder() .ddOrderService(ddOrderService) .distributionJobHUReservationService(distributionJobHUReservationService); } public void abortAll(@NonNull final UserId responsibleId) { final List<DistributionJob> jobs = newLoader().loadByQuery(DistributionJobQueries.ddOrdersAssignedToUser(responsibleId)); if (jobs.isEmpty()) { return; } abort().jobs(jobs).execute(); } public JsonGetNextEligiblePickFromLineResponse getNextEligiblePickFromLine(@NonNull final JsonGetNextEligiblePickFromLineRequest request, @NonNull final UserId callerId) { final DistributionJobId jobId = DistributionJobId.ofWFProcessId(request.getWfProcessId()); final DistributionJob job = getJobById(jobId); job.assertCanEdit(callerId); final HUQRCode huQRCode = huService.resolveHUQRCode(request.getHuQRCode()); final ProductId productId;
if (request.getProductScannedCode() != null) { productId = productService.getProductIdByScannedProductCode(request.getProductScannedCode()); huService.assetHUContainsProduct(huQRCode, productId); } else { productId = huService.getSingleProductId(huQRCode); } final DistributionJobLineId nextEligiblePickFromLineId; if (request.getLineId() != null) { final DistributionJobLine line = job.getLineById(request.getLineId()); nextEligiblePickFromLineId = line.isEligibleForPicking() ? line.getId() : null; } else { nextEligiblePickFromLineId = job.getNextEligiblePickFromLineId(productId).orElse(null); } return JsonGetNextEligiblePickFromLineResponse.builder() .lineId(nextEligiblePickFromLineId) .build(); } public void printMaterialInTransitReport( @NonNull final UserId userId, @NonNull final String adLanguage) { @NonNull final LocatorId inTransitLocatorId = warehouseService.getTrolleyByUserId(userId) .map(LocatorQRCode::getLocatorId) .orElseThrow(() -> new AdempiereException("No trolley found for user: " + userId)); ddOrderMoveScheduleService.printMaterialInTransitReport(inTransitLocatorId, adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionRestService.java
2
请完成以下Java代码
public void subscribe(final IEventListener listener) { delegate().subscribe(listener); } @Override public void subscribe(final Consumer<Event> eventConsumer) { delegate().subscribe(eventConsumer); } @Override public <T> IEventListener subscribeOn(final Class<T> type, final Consumer<T> eventConsumer) { return delegate().subscribeOn(type, eventConsumer); } @Override public void unsubscribe(final IEventListener listener) { delegate().unsubscribe(listener); } @Override public void processEvent(final Event event) { try (final MDCCloseable ignored = EventMDC.putEvent(event)) { delegate().processEvent(event); } } @Override public void enqueueEvent(final Event event) { try (final MDCCloseable ignored = EventMDC.putEvent(event)) { delegate().enqueueEvent(event); } }
@Override public void enqueueObject(final Object obj) { delegate().enqueueObject(obj); } @Override public void enqueueObjectsCollection(@NonNull final Collection<?> objs) { delegate().enqueueObjectsCollection(objs); } @Override public boolean isDestroyed() { return delegate().isDestroyed(); } @Override public boolean isAsync() { return delegate().isAsync(); } @Override public EventBusStats getStats() { return delegate().getStats(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\ForwardingEventBus.java
1
请完成以下Java代码
public int removeAllByCreatedTimeBefore(long ts) { return notificationRequestRepository.deleteAllByCreatedTimeBefore(ts); } @Override public NotificationRequestInfo findInfoById(TenantId tenantId, NotificationRequestId id) { NotificationRequestInfoEntity info = notificationRequestRepository.findInfoById(id.getId()); return info != null ? info.toData() : null; } @Override public void removeByTenantId(TenantId tenantId) { notificationRequestRepository.deleteByTenantId(tenantId.getId()); }
@Override protected Class<NotificationRequestEntity> getEntityClass() { return NotificationRequestEntity.class; } @Override protected JpaRepository<NotificationRequestEntity, UUID> getRepository() { return notificationRequestRepository; } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_REQUEST; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationRequestDao.java
1
请完成以下Java代码
public int getC_DocType_Invoicing_Pool_ID() { return get_ValueAsInt(COLUMNNAME_C_DocType_Invoicing_Pool_ID); } @Override public void setIsOnDistinctICTypes (final boolean IsOnDistinctICTypes) { set_Value (COLUMNNAME_IsOnDistinctICTypes, IsOnDistinctICTypes); } @Override public boolean isOnDistinctICTypes() { return get_ValueAsBoolean(COLUMNNAME_IsOnDistinctICTypes); } @Override public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name);
} @Override public void setNegative_Amt_C_DocType_ID (final int Negative_Amt_C_DocType_ID) { if (Negative_Amt_C_DocType_ID < 1) set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, null); else set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, Negative_Amt_C_DocType_ID); } @Override public int getNegative_Amt_C_DocType_ID() { return get_ValueAsInt(COLUMNNAME_Negative_Amt_C_DocType_ID); } @Override public void setPositive_Amt_C_DocType_ID (final int Positive_Amt_C_DocType_ID) { if (Positive_Amt_C_DocType_ID < 1) set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, null); else set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, Positive_Amt_C_DocType_ID); } @Override public int getPositive_Amt_C_DocType_ID() { return get_ValueAsInt(COLUMNNAME_Positive_Amt_C_DocType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType_Invoicing_Pool.java
1
请完成以下Java代码
public <T> String debugAccept(final IQueryFilter<T> filter, final T model) { final StringBuilder sb = new StringBuilder(); sb.append("\n-------------------------------------------------------------------------------"); sb.append("\nModel: " + model); final List<IQueryFilter<T>> filters = extractAllFilters(filter); for (final IQueryFilter<T> f : filters) { final boolean accept = f.accept(model); sb.append("\nFilter(accept=" + accept + "): " + f); } sb.append("\n-------------------------------------------------------------------------------"); return sb.toString(); } private <T> List<IQueryFilter<T>> extractAllFilters(@Nullable final IQueryFilter<T> filter) { if (filter == null) { return Collections.emptyList(); } final List<IQueryFilter<T>> result = new ArrayList<>(); result.add(filter); if (filter instanceof ICompositeQueryFilter) { final ICompositeQueryFilter<T> compositeFilter = (ICompositeQueryFilter<T>)filter;
for (final IQueryFilter<T> f : compositeFilter.getFilters()) { final List<IQueryFilter<T>> resultLocal = extractAllFilters(f); result.addAll(resultLocal); } } return result; } @Override public <T> QueryResultPage<T> retrieveNextPage( @NonNull final Class<T> clazz, @NonNull final String next) { if (Adempiere.isUnitTestMode()) { return POJOQuery.getPage(clazz, next); } return SpringContextHolder.instance .getBean(PaginationService.class) .loadPage(clazz, next); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryBL.java
1
请完成以下Java代码
public boolean hasNature(Nature nature) { return getNatureFrequency(nature) > 0; } /** * 是否有以某个前缀开头的词性 * * @param prefix 词性前缀,比如u会查询是否有ude, uzhe等等 * @return */ public boolean hasNatureStartsWith(String prefix) { for (Nature n : nature) { if (n.startsWith(prefix)) return true; } return false; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < nature.length; ++i) { sb.append(nature[i]).append(' ').append(frequency[i]).append(' '); } return sb.toString(); } public void save(DataOutputStream out) throws IOException { out.writeInt(totalFrequency); out.writeInt(nature.length); for (int i = 0; i < nature.length; ++i) { out.writeInt(nature[i].ordinal()); out.writeInt(frequency[i]); }
} } /** * 获取词语的ID * * @param a 词语 * @return ID, 如果不存在, 则返回-1 */ public static int getWordID(String a) { return CoreDictionary.trie.exactMatchSearch(a); } /** * 热更新核心词典<br> * 集群环境(或其他IOAdapter)需要自行删除缓存文件 * * @return 是否成功 */ public static boolean reload() { String path = CoreDictionary.path; IOUtil.deleteFile(path + Predefine.BIN_EXT); return load(path); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CoreDictionary.java
1
请完成以下Spring Boot application配置
server: port: 8081 spring: application: name: spring-boot-mvc-client security: oauth2: client: provider: baeldung-keycloak: issuer-uri: http://localhost:8080/realms/baeldung-keycloak registration: keycloak: provider: baeldung-keycloak authorization-grant-type: authorization_code client-id: baeldung-keycloak-confidential client-secret: secret scope: openid logging: level: org: springframework: security: DEBU
G boot: INFO management: endpoint: health: probes: enabled: true endpoints: web: exposure: include: '*' health: livenessstate: enabled: true readinessstate: enabled: true
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak\spring-boot-mvc-client\src\main\resources\application.yml
2
请完成以下Java代码
public class MSalesRegion extends X_C_SalesRegion { /** * */ private static final long serialVersionUID = 8582026748675153489L; /** * Get SalesRegion from Cache * @param ctx context * @param C_SalesRegion_ID id * @return MSalesRegion */ public static MSalesRegion get (Properties ctx, int C_SalesRegion_ID) { Integer key = new Integer (C_SalesRegion_ID); MSalesRegion retValue = (MSalesRegion) s_cache.get (key); if (retValue != null) return retValue; retValue = new MSalesRegion (ctx, C_SalesRegion_ID, null); if (retValue.get_ID () != 0) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer,MSalesRegion> s_cache = new CCache<Integer,MSalesRegion>("C_SalesRegion", 10); /************************************************************************** * Default Constructor * @param ctx context * @param C_SalesRegion_ID id * @param trxName transaction */ public MSalesRegion (Properties ctx, int C_SalesRegion_ID, String trxName) { super (ctx, C_SalesRegion_ID, trxName); } // MSalesRegion /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MSalesRegion (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MSalesRegion /** * Before Save * @param newRecord new * @return true */ protected boolean beforeSave (boolean newRecord) { if (getAD_Org_ID() != 0) setAD_Org_ID(0); return true; } // beforeSave
/** * After Save. * Insert * - create tree * @param newRecord insert * @param success save success * @return success */ protected boolean afterSave (boolean newRecord, boolean success) { if (!success) return success; if (newRecord) insert_Tree(MTree_Base.TREETYPE_SalesRegion); // Value/Name change if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name"))) MAccount.updateValueDescription(getCtx(), "C_SalesRegion_ID=" + getC_SalesRegion_ID(), get_TrxName()); return true; } // afterSave /** * After Delete * @param success * @return deleted */ protected boolean afterDelete (boolean success) { if (success) delete_Tree(MTree_Base.TREETYPE_SalesRegion); return success; } // afterDelete } // MSalesRegion
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSalesRegion.java
1
请完成以下Java代码
public static String bankCard(String cardNum) { if (oConvertUtils.isEmpty(cardNum)) { return ""; } return formatBetween(cardNum, 6, 4); } /** * [公司开户银行联号] 公司开户银行联行号,显示前两位,其他用星号隐藏,每位1个星号 * @param code 公司开户银行联号 * @return <例子:12********> */ public static String cnapsCode(String code) { if (oConvertUtils.isEmpty(code)) { return ""; } return formatRight(code, 2); } /** * 将右边的格式化成* * @param str 字符串 * @param reservedLength 保留长度 * @return 格式化后的字符串 */ public static String formatRight(String str, int reservedLength){ String name = str.substring(0, reservedLength); String stars = String.join("", Collections.nCopies(str.length()-reservedLength, "*")); return name + stars;
} /** * 将左边的格式化成* * @param str 字符串 * @param reservedLength 保留长度 * @return 格式化后的字符串 */ public static String formatLeft(String str, int reservedLength){ int len = str.length(); String show = str.substring(len-reservedLength); String stars = String.join("", Collections.nCopies(len-reservedLength, "*")); return stars + show; } /** * 将中间的格式化成* * @param str 字符串 * @param beginLen 开始保留长度 * @param endLen 结尾保留长度 * @return 格式化后的字符串 */ public static String formatBetween(String str, int beginLen, int endLen){ int len = str.length(); String begin = str.substring(0, beginLen); String end = str.substring(len-endLen); String stars = String.join("", Collections.nCopies(len-beginLen-endLen, "*")); return begin + stars + end; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\desensitization\util\SensitiveInfoUtil.java
1
请完成以下Java代码
public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource;
} @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public int getStrategy() { return strategy; } public void setStrategy(int strategy) { this.strategy = strategy; } @Override public Rule toRule(){ AuthorityRule rule=new AuthorityRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\AuthorityRuleCorrectEntity.java
1
请完成以下Java代码
public class TaskCandidateGroupImpl extends TaskCandidateImpl implements TaskCandidateGroup { private String groupId; public TaskCandidateGroupImpl() {} public TaskCandidateGroupImpl(String groupId, String taskId) { super(taskId); this.groupId = groupId; } @Override public String getGroupId() { return groupId; } @Override public boolean equals(Object o) {
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TaskCandidateGroupImpl that = (TaskCandidateGroupImpl) o; return Objects.equals(groupId, that.groupId) && Objects.equals(getTaskId(), that.getTaskId()); } @Override public int hashCode() { return Objects.hash(groupId, getTaskId()); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-model-impl\src\main\java\org\activiti\api\task\model\impl\TaskCandidateGroupImpl.java
1
请完成以下Java代码
public org.compiere.model.I_AD_BusinessRule getAD_BusinessRule() { return get_ValueAsPO(COLUMNNAME_AD_BusinessRule_ID, org.compiere.model.I_AD_BusinessRule.class); } @Override public void setAD_BusinessRule(final org.compiere.model.I_AD_BusinessRule AD_BusinessRule) { set_ValueFromPO(COLUMNNAME_AD_BusinessRule_ID, org.compiere.model.I_AD_BusinessRule.class, AD_BusinessRule); } @Override public void setAD_BusinessRule_ID (final int AD_BusinessRule_ID) { if (AD_BusinessRule_ID < 1) set_Value (COLUMNNAME_AD_BusinessRule_ID, null); else set_Value (COLUMNNAME_AD_BusinessRule_ID, AD_BusinessRule_ID); } @Override public int getAD_BusinessRule_ID() { return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_ID); } @Override public void setAD_BusinessRule_WarningTarget_ID (final int AD_BusinessRule_WarningTarget_ID) { if (AD_BusinessRule_WarningTarget_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_WarningTarget_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_WarningTarget_ID, AD_BusinessRule_WarningTarget_ID); } @Override public int getAD_BusinessRule_WarningTarget_ID() { return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_WarningTarget_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); }
@Override public void setLookupSQL (final java.lang.String LookupSQL) { set_Value (COLUMNNAME_LookupSQL, LookupSQL); } @Override public java.lang.String getLookupSQL() { return get_ValueAsString(COLUMNNAME_LookupSQL); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_WarningTarget.java
1
请完成以下Java代码
public final class OrgPermission extends AbstractPermission implements Serializable { public static OrgPermission ofResourceAndReadOnly(final OrgResource resource, final boolean readOnly) { final ImmutableSet.Builder<Access> accesses = ImmutableSet.builder(); // READ access: this is implied if we are here accesses.add(Access.READ); // WRITE access: if (!readOnly) { accesses.add(Access.WRITE); } // LOGIN access: if (!resource.isGroupingOrg()) { accesses.add(Access.LOGIN); } return new OrgPermission(resource, accesses.build()); } /** * */ private static final long serialVersionUID = 6649713070452921967L; private final OrgResource resource; private final Set<Access> accesses; public OrgPermission(final OrgResource resource, final Set<Access> accesses) { super(); Check.assumeNotNull(resource, "resource not null"); this.resource = resource; this.accesses = ImmutableSet.copyOf(accesses); } @Override public int hashCode() { return new HashcodeBuilder() .append(resource) .append(accesses) .toHashcode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } final OrgPermission other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(resource, other.resource) .append(accesses, other.accesses) .isEqual(); } @Override
public String toString() { return resource + ", " + accesses; } @Override public boolean hasAccess(Access access) { return accesses.contains(access); } public boolean isReadOnly() { return hasAccess(Access.READ) && !hasAccess(Access.WRITE); } public boolean isReadWrite() { return hasAccess(Access.WRITE); } public ClientId getClientId() { return resource.getClientId(); } public OrgId getOrgId() { return resource.getOrgId(); } @Override public OrgResource getResource() { return resource; } @Override public Permission mergeWith(final Permission permissionFrom) { final OrgPermission orgPermissionFrom = checkCompatibleAndCast(permissionFrom); final ImmutableSet<Access> accesses = ImmutableSet.<Access> builder() .addAll(this.accesses) .addAll(orgPermissionFrom.accesses) .build(); return new OrgPermission(resource, accesses); } /** * Creates a copy of this permission but it will use the given resource. * * @return copy of this permission but having the given resource */ public OrgPermission copyWithResource(final OrgResource resource) { return new OrgPermission(resource, this.accesses); } } // OrgAccess
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgPermission.java
1
请在Spring Boot框架中完成以下Java代码
public SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler() { SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler = new SavedRequestAwareAuthenticationSuccessHandler(); successRedirectHandler.setDefaultTargetUrl("/home"); return successRedirectHandler; } @Bean @Qualifier("saml") public SimpleUrlAuthenticationFailureHandler authenticationFailureHandler() { SimpleUrlAuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler(); failureHandler.setUseForward(true); failureHandler.setDefaultFailureUrl("/error"); return failureHandler; } @Bean public SimpleUrlLogoutSuccessHandler successLogoutHandler() { SimpleUrlLogoutSuccessHandler successLogoutHandler = new SimpleUrlLogoutSuccessHandler(); successLogoutHandler.setDefaultTargetUrl("/"); return successLogoutHandler; } @Bean public SecurityContextLogoutHandler logoutHandler() { SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler(); logoutHandler.setInvalidateHttpSession(true); logoutHandler.setClearAuthentication(true); return logoutHandler; } @Bean public SAMLLogoutProcessingFilter samlLogoutProcessingFilter() { return new SAMLLogoutProcessingFilter(successLogoutHandler(), logoutHandler()); } @Bean public SAMLLogoutFilter samlLogoutFilter() {
return new SAMLLogoutFilter(successLogoutHandler(), new LogoutHandler[] { logoutHandler() }, new LogoutHandler[] { logoutHandler() }); } @Bean public HTTPPostBinding httpPostBinding() { return new HTTPPostBinding(parserPool(), VelocityFactory.getEngine()); } @Bean public HTTPRedirectDeflateBinding httpRedirectDeflateBinding() { return new HTTPRedirectDeflateBinding(parserPool()); } @Bean public SAMLProcessorImpl processor() { ArrayList<SAMLBinding> bindings = new ArrayList<>(); bindings.add(httpRedirectDeflateBinding()); bindings.add(httpPostBinding()); return new SAMLProcessorImpl(bindings); } }
repos\tutorials-master\spring-security-modules\spring-security-saml\src\main\java\com\baeldung\saml\config\SamlSecurityConfig.java
2
请完成以下Spring Boot application配置
application.servers[0].ip=127.0.0.1 application.servers[0].path=/path1 application.servers[1].ip=127.0.0.2 application.servers[1].path=/path2 application.servers[2].ip=127.0.0.3 application.servers[2].path=/path3 spring.datasource.url=jdbc:h2:dev spring.datasource.username=SA spring.datasource.password=password app.name=MyApp app.description=${app.name} is a Spring Boot application logging.file.name=myapplication.log bael.property=defaultValue bael.otherProperty=defaultOtherValue #--- spring.config.activate.on-profile=multidocument-dev spring.datasource.password=password spring.datasource.url=jdbc:h2:dev spring.datasource.username=SA bael.property=devValue #--- spring.config.
activate.on-profile=multidocument-integration-extension bael.otherProperty=integrationExtensionOtherValue #--- spring.config.activate.on-profile=multidocument-prod spring.datasource.password=password spring.datasource.url=jdbc:h2:prod spring.datasource.username=prodUser bael.property=prodValue
repos\tutorials-master\spring-boot-modules\spring-boot-properties-3\src\main\resources\application.properties
2
请完成以下Java代码
private IAttributeStorage getAttributeStorage(final I_M_HU cuHU) { return huContext.getHUAttributeStorageFactory().getAttributeStorage(cuHU); } private Quantity getCurrentTURemainingQty() { if (capacity.isInfiniteCapacity()) { return Quantity.infinite(capacity.getC_UOM()); } Quantity qtyRemaining = capacity.toQuantity(); if (this._currentTUQty != null) { qtyRemaining = qtyRemaining.subtract(this._currentTUQty); } return qtyRemaining; } private I_M_HU getOrCreateCurrentTU() { if (_currentTU == null) { _currentTU = newHUBuilder().create(tuPI); } return _currentTU; } private void closeCurrentTUIfCapacityExceeded() { if (_currentTU != null && getCurrentTURemainingQty().signum() <= 0) { closeCurrentTU(); } } void closeCurrentTU() { if (_currentTU != null && _currentAttributes != null) { final IAttributeStorage tuAttributes = getAttributeStorage(_currentTU); tuAttributes.setSaveOnChange(true); _currentAttributes.updateAggregatedValuesTo(tuAttributes); } _currentTU = null; _currentTUQty = null; _currentAttributes = null; } private void addToCurrentTUQty(final Quantity qtyToAdd) { Check.assumeNotNull(_currentTU, "current TU is created"); if (this._currentTUQty == null) { this._currentTUQty = Quantity.zero(capacity.getC_UOM()); } this._currentTUQty = this._currentTUQty.add(qtyToAdd); } private IHUBuilder newHUBuilder() { final IHUBuilder huBuilder = Services.get(IHandlingUnitsDAO.class).createHUBuilder(huContext); huBuilder.setLocatorId(locatorId); if (!Check.isEmpty(huStatus, true)) { huBuilder.setHUStatus(huStatus);
} if (bpartnerId != null) { huBuilder.setBPartnerId(bpartnerId); } if (bpartnerLocationRepoId > 0) { huBuilder.setC_BPartner_Location_ID(bpartnerLocationRepoId); } huBuilder.setHUPlanningReceiptOwnerPM(true); huBuilder.setHUClearanceStatusInfo(clearanceStatusInfo); return huBuilder; } private I_M_HU splitCU(final I_M_HU fromCU, final ProductId cuProductId, final Quantity qtyToSplit) { Check.assume(qtyToSplit.signum() > 0, "qtyToSplit shall be greater than zero but it was {}", qtyToSplit); final HUProducerDestination destination = HUProducerDestination.ofVirtualPI(); HULoader.builder() .source(HUListAllocationSourceDestination.of(fromCU)) .destination(destination) .load(AllocationUtils.builder() .setHUContext(huContext) .setProduct(cuProductId) .setQuantity(qtyToSplit) .setForceQtyAllocation(false) // no need to force .setClearanceStatusInfo(clearanceStatusInfo) .create()); return CollectionUtils.singleElement(destination.getCreatedHUs()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TULoaderInstance.java
1
请在Spring Boot框架中完成以下Java代码
public void updateUser(String userId, Set<Contact> contacts, Set<Address> addresses) throws Exception { User user = UserUtility.recreateUserState(repository, userId); if (user == null) throw new Exception("User does not exist."); user.getContacts() .stream() .filter(c -> !contacts.contains(c)) .forEach(c -> repository.addEvent(userId, new UserContactRemovedEvent(c.getType(), c.getDetail()))); contacts.stream() .filter(c -> !user.getContacts() .contains(c)) .forEach(c -> repository.addEvent(userId, new UserContactAddedEvent(c.getType(), c.getDetail()))); user.getAddresses() .stream() .filter(a -> !addresses.contains(a)) .forEach(a -> repository.addEvent(userId, new UserAddressRemovedEvent(a.getCity(), a.getState(), a.getPostcode()))); addresses.stream() .filter(a -> !user.getAddresses() .contains(a)) .forEach(a -> repository.addEvent(userId, new UserAddressAddedEvent(a.getCity(), a.getState(), a.getPostcode()))); } public Set<Contact> getContactByType(String userId, String contactType) throws Exception { User user = UserUtility.recreateUserState(repository, userId); if (user == null) throw new Exception("User does not exist."); return user.getContacts() .stream() .filter(c -> c.getType()
.equals(contactType)) .collect(Collectors.toSet()); } public Set<Address> getAddressByRegion(String userId, String state) throws Exception { User user = UserUtility.recreateUserState(repository, userId); if (user == null) throw new Exception("User does not exist."); return user.getAddresses() .stream() .filter(a -> a.getState() .equals(state)) .collect(Collectors.toSet()); } }
repos\tutorials-master\patterns-modules\cqrs-es\src\main\java\com\baeldung\patterns\es\service\UserService.java
2
请完成以下Java代码
public void setAD_WF_Responsible_ID (final int AD_WF_Responsible_ID) { if (AD_WF_Responsible_ID < 1) set_Value (COLUMNNAME_AD_WF_Responsible_ID, null); else set_Value (COLUMNNAME_AD_WF_Responsible_ID, AD_WF_Responsible_ID); } @Override public int getAD_WF_Responsible_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Responsible_ID); } @Override public void setAD_Workflow_ID (final int AD_Workflow_ID) { if (AD_Workflow_ID < 1) set_Value (COLUMNNAME_AD_Workflow_ID, null); else set_Value (COLUMNNAME_AD_Workflow_ID, AD_Workflow_ID); } @Override public int getAD_Workflow_ID() { return get_ValueAsInt(COLUMNNAME_AD_Workflow_ID); } @Override public void setPriority (final int Priority) { set_Value (COLUMNNAME_Priority, Priority); } @Override public int getPriority() { return get_ValueAsInt(COLUMNNAME_Priority); } @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 setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() {
return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setTextMsg (final java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } @Override public java.lang.String getTextMsg() { return get_ValueAsString(COLUMNNAME_TextMsg); } @Override public void setWF_Initial_User_ID (final int WF_Initial_User_ID) { if (WF_Initial_User_ID < 1) set_Value (COLUMNNAME_WF_Initial_User_ID, null); else set_Value (COLUMNNAME_WF_Initial_User_ID, WF_Initial_User_ID); } @Override public int getWF_Initial_User_ID() { return get_ValueAsInt(COLUMNNAME_WF_Initial_User_ID); } /** * WFState AD_Reference_ID=305 * Reference name: WF_Instance State */ public static final int WFSTATE_AD_Reference_ID=305; /** NotStarted = ON */ public static final String WFSTATE_NotStarted = "ON"; /** Running = OR */ public static final String WFSTATE_Running = "OR"; /** Suspended = OS */ public static final String WFSTATE_Suspended = "OS"; /** Completed = CC */ public static final String WFSTATE_Completed = "CC"; /** Aborted = CA */ public static final String WFSTATE_Aborted = "CA"; /** Terminated = CT */ public static final String WFSTATE_Terminated = "CT"; @Override public void setWFState (final java.lang.String WFState) { set_Value (COLUMNNAME_WFState, WFState); } @Override public java.lang.String getWFState() { return get_ValueAsString(COLUMNNAME_WFState); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Process.java
1
请完成以下Java代码
public class OrdersCollector implements IOrdersCollector { public static OrdersCollector newInstance() { return new OrdersCollector(); } private final AtomicInteger countOrders = new AtomicInteger(0); private static final AdMessageKey MSG_Event_Generated = AdMessageKey.of("Event_ProcurementPurchaseOrderGenerated"); private final DocumentUserNotificationsProducer<I_C_Order> orderGeneratedNotifier = DocumentUserNotificationsProducer.<I_C_Order> builder() .logger(ProcurementConstants.getLogger(OrdersCollector.class)) .topic(ProcurementConstants.USER_NOTIFICATIONS_TOPIC) .eventAD_Message(MSG_Event_Generated) .eventAD_MessageParamsExtractor(OrdersCollector::extractUserNotificationADMessageParams) .build(); private UserId defaultNotificationRecipientId; private OrdersCollector() { } private static List<Object> extractUserNotificationADMessageParams(final I_C_Order order) { final I_C_BPartner bpartner = Services.get(IOrderBL.class).getBPartner(order);
return ImmutableList.builder() .add(TableRecordReference.of(order)) .add(bpartner.getValue()) .add(bpartner.getName()) .build(); } public void setDefaultNotificationRecipientId(final UserId defaultNotificationRecipientId) { this.defaultNotificationRecipientId = defaultNotificationRecipientId; } @Override public void add(final I_C_Order order) { Loggables.addLog("@Created@ " + order.getDocumentNo()); orderGeneratedNotifier.notify(order, defaultNotificationRecipientId); countOrders.incrementAndGet(); } public int getCountOrders() { return countOrders.get(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\OrdersCollector.java
1
请在Spring Boot框架中完成以下Java代码
public JAXBElement<CustomType> createErpelPresentationDetailsExtension(CustomType value) { return new JAXBElement<CustomType>(_ErpelPresentationDetailsExtension_QNAME, CustomType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CustomType }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link CustomType }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/documents/ext", name = "ErpelReductionAndSurchargeDetailsExtension") public JAXBElement<CustomType> createErpelReductionAndSurchargeDetailsExtension(CustomType value) { return new JAXBElement<CustomType>(_ErpelReductionAndSurchargeDetailsExtension_QNAME, CustomType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CustomType }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link CustomType }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/documents/ext", name = "ErpelShipperExtension") public JAXBElement<CustomType> createErpelShipperExtension(CustomType value) { return new JAXBElement<CustomType>(_ErpelShipperExtension_QNAME, CustomType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CustomType }{@code >} * * @param value
* Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link CustomType }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/documents/ext", name = "ErpelSupplierExtension") public JAXBElement<CustomType> createErpelSupplierExtension(CustomType value) { return new JAXBElement<CustomType>(_ErpelSupplierExtension_QNAME, CustomType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CustomType }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link CustomType }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/documents/ext", name = "ErpelTaxExtension") public JAXBElement<CustomType> createErpelTaxExtension(CustomType value) { return new JAXBElement<CustomType>(_ErpelTaxExtension_QNAME, CustomType.class, null, value); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\ObjectFactory.java
2
请完成以下Java代码
public static int getTotalNumberOfLinesUsingNIOFiles(String fileName) { int lines = 0; try (Stream<String> fileStream = Files.lines(Paths.get(fileName))) { lines = (int) fileStream.count(); } catch (IOException ioe) { ioe.printStackTrace(); } return lines; } public static int getTotalNumberOfLinesUsingNIOFilesReadAllLines(String fileName) { int lines = 0; try { List<String> fileStream = Files.readAllLines(Paths.get(fileName)); lines = fileStream.size(); } catch (IOException ioe) { ioe.printStackTrace(); } return lines; } public static int getTotalNumberOfLinesUsingNIOFileChannel(String fileName) { int lines = 1; try (FileChannel channel = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ)) { ByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size()); while (byteBuffer.hasRemaining()) { byte currentChar = byteBuffer.get(); if (currentChar == '\n') { lines++; } } } catch (IOException ioe) { ioe.printStackTrace();
} return lines; } public static int getTotalNumberOfLinesUsingApacheCommonsIO(String fileName) { int lines = 0; try { LineIterator lineIterator = FileUtils.lineIterator(new File(fileName)); while (lineIterator.hasNext()) { lineIterator.nextLine(); lines++; } } catch (IOException ioe) { ioe.printStackTrace(); } return lines; } public static int getTotalNumberOfLinesUsingGoogleGuava(String fileName) { int lines = 0; try { List<String> lineItems = com.google.common.io.Files.readLines(Paths.get(fileName) .toFile(), Charset.defaultCharset()); lines = lineItems.size(); } catch (IOException ioe) { ioe.printStackTrace(); } return lines; } }
repos\tutorials-master\core-java-modules\core-java-nio-3\src\main\java\com\baeldung\lines\NumberOfLineFinder.java
1
请完成以下Java代码
public void setContent (final @Nullable java.lang.String Content) { set_ValueNoCheck (COLUMNNAME_Content, Content); } @Override public java.lang.String getContent() { return get_ValueAsString(COLUMNNAME_Content); } /** * Direction AD_Reference_ID=541551 * Reference name: RabbitMQ_Message_Audit_Direction */ public static final int DIRECTION_AD_Reference_ID=541551; /** In = I */ public static final String DIRECTION_In = "I"; /** Out = O */ public static final String DIRECTION_Out = "O"; @Override public void setDirection (final java.lang.String Direction) { set_ValueNoCheck (COLUMNNAME_Direction, Direction); } @Override public java.lang.String getDirection() { return get_ValueAsString(COLUMNNAME_Direction); } @Override public void setEvent_UUID (final @Nullable java.lang.String Event_UUID) { set_ValueNoCheck (COLUMNNAME_Event_UUID, Event_UUID); } @Override public java.lang.String getEvent_UUID() { return get_ValueAsString(COLUMNNAME_Event_UUID); } @Override public void setHost (final @Nullable java.lang.String Host) { set_ValueNoCheck (COLUMNNAME_Host, Host); } @Override public java.lang.String getHost() { return get_ValueAsString(COLUMNNAME_Host); } @Override public void setRabbitMQ_Message_Audit_ID (final int RabbitMQ_Message_Audit_ID)
{ if (RabbitMQ_Message_Audit_ID < 1) set_ValueNoCheck (COLUMNNAME_RabbitMQ_Message_Audit_ID, null); else set_ValueNoCheck (COLUMNNAME_RabbitMQ_Message_Audit_ID, RabbitMQ_Message_Audit_ID); } @Override public int getRabbitMQ_Message_Audit_ID() { return get_ValueAsInt(COLUMNNAME_RabbitMQ_Message_Audit_ID); } @Override public void setRabbitMQ_QueueName (final @Nullable java.lang.String RabbitMQ_QueueName) { set_ValueNoCheck (COLUMNNAME_RabbitMQ_QueueName, RabbitMQ_QueueName); } @Override public java.lang.String getRabbitMQ_QueueName() { return get_ValueAsString(COLUMNNAME_RabbitMQ_QueueName); } @Override public void setRelated_Event_UUID (final @Nullable java.lang.String Related_Event_UUID) { set_ValueNoCheck (COLUMNNAME_Related_Event_UUID, Related_Event_UUID); } @Override public java.lang.String getRelated_Event_UUID() { return get_ValueAsString(COLUMNNAME_Related_Event_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RabbitMQ_Message_Audit.java
1
请完成以下Java代码
public static boolean saveSentenceList(List<List<IWord>> sentenceList, String path) { return IOUtil.saveObjectTo(sentenceList, path); } public static List<List<IWord>> convert2SentenceList(String path) { List<Document> documentList = CorpusLoader.convert2DocumentList(path); List<List<IWord>> simpleList = new LinkedList<List<IWord>>(); for (Document document : documentList) { for (Sentence sentence : document.sentenceList) { simpleList.add(sentence.wordList); } } return simpleList; } public static List<List<Word>> convert2SimpleSentenceList(String path) { List<Document> documentList = CorpusLoader.convert2DocumentList(path); List<List<Word>> simpleList = new LinkedList<List<Word>>(); for (Document document : documentList) { simpleList.addAll(document.getSimpleSentenceList()); } return simpleList; } public static Document convert2Document(File file) { // try // { Document document = Document.create(file); if (document != null) { return document; } else { throw new IllegalArgumentException(file.getPath() + "读取失败"); } // } // catch (IOException e) // { // e.printStackTrace(); // } // return null; } public static interface Handler { void handle(Document document); } /** * 多线程任务 */ public static abstract class HandlerThread extends Thread implements Handler
{ /** * 这个线程负责处理这些事情 */ public List<File> fileList; public HandlerThread(String name) { super(name); } @Override public void run() { long start = System.currentTimeMillis(); System.out.printf("线程#%s 开始运行\n", getName()); int i = 0; for (File file : fileList) { System.out.print(file); Document document = convert2Document(file); System.out.println(" " + ++i + " / " + fileList.size()); handle(document); } System.out.printf("线程#%s 运行完毕,耗时%dms\n", getName(), System.currentTimeMillis() - start); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\CorpusLoader.java
1
请完成以下Java代码
public void handle(ServerWebExchange exchange, Mono<CsrfToken> csrfToken) { Assert.notNull(exchange, "exchange cannot be null"); Assert.notNull(csrfToken, "csrfToken cannot be null"); Mono<CsrfToken> updatedCsrfToken = csrfToken .map((token) -> new DefaultCsrfToken(token.getHeaderName(), token.getParameterName(), createXoredCsrfToken(this.secureRandom, token.getToken()))) .cast(CsrfToken.class) .cache(); super.handle(exchange, updatedCsrfToken); } @Override public Mono<String> resolveCsrfTokenValue(ServerWebExchange exchange, CsrfToken csrfToken) { return super.resolveCsrfTokenValue(exchange, csrfToken) .flatMap((actualToken) -> Mono.justOrEmpty(getTokenValue(actualToken, csrfToken.getToken()))); } private static @Nullable String getTokenValue(String actualToken, String token) { byte[] actualBytes; try { actualBytes = Base64.getUrlDecoder().decode(actualToken); } catch (Exception ex) { logger.trace(LogMessage.format("Not returning the CSRF token since it's not Base64-encoded"), ex); return null; } byte[] tokenBytes = Utf8.encode(token); int tokenSize = tokenBytes.length; if (actualBytes.length != tokenSize * 2) { logger.trace(LogMessage.format( "Not returning the CSRF token since its Base64-decoded length (%d) is not equal to (%d)", actualBytes.length, tokenSize * 2)); return null; } // extract token and random bytes byte[] xoredCsrf = new byte[tokenSize]; byte[] randomBytes = new byte[tokenSize]; System.arraycopy(actualBytes, 0, randomBytes, 0, tokenSize); System.arraycopy(actualBytes, tokenSize, xoredCsrf, 0, tokenSize); byte[] csrfBytes = xorCsrf(randomBytes, xoredCsrf); return (csrfBytes != null) ? Utf8.decode(csrfBytes) : null; } private static String createXoredCsrfToken(SecureRandom secureRandom, String token) {
byte[] tokenBytes = Utf8.encode(token); byte[] randomBytes = new byte[tokenBytes.length]; secureRandom.nextBytes(randomBytes); byte[] xoredBytes = xorCsrf(randomBytes, tokenBytes); byte[] combinedBytes = new byte[tokenBytes.length + randomBytes.length]; System.arraycopy(randomBytes, 0, combinedBytes, 0, randomBytes.length); System.arraycopy(xoredBytes, 0, combinedBytes, randomBytes.length, xoredBytes.length); return Base64.getUrlEncoder().encodeToString(combinedBytes); } private static byte[] xorCsrf(byte[] randomBytes, byte[] csrfBytes) { Assert.isTrue(randomBytes.length == csrfBytes.length, "arrays must be equal length"); int len = csrfBytes.length; byte[] xoredCsrf = new byte[len]; System.arraycopy(csrfBytes, 0, xoredCsrf, 0, len); for (int i = 0; i < len; i++) { xoredCsrf[i] ^= randomBytes[i]; } return xoredCsrf; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\XorServerCsrfTokenRequestAttributeHandler.java
1
请完成以下Java代码
protected Properties extractCtxFromItem(final Object item) { return InterfaceWrapperHelper.getCtx(item); } @Override protected String extractTrxNameFromItem(final Object item) { return InterfaceWrapperHelper.getTrxName(item); } @Override protected Object extractModelToEnqueueFromItem(final Collector collector, final Object item) { return TableRecordReference.of(item); } }; // services private final transient IQueueDAO queueDAO = Services.get(IQueueDAO.class);
private final transient IDocumentBL docActionBL = Services.get(IDocumentBL.class); private final transient ICounterDocBL counterDocumentBL = Services.get(ICounterDocBL.class); @Override public Result processWorkPackage(final I_C_Queue_WorkPackage workpackage, final String localTrxName) { final List<Object> models = queueDAO.retrieveAllItemsSkipMissing(workpackage, Object.class); for (final Object model : models) { final IDocument document = docActionBL.getDocument(model); final IDocument counterDocument = counterDocumentBL.createCounterDocument(document, false); Loggables.addLog("Document {0}: created counter document {1}", document, counterDocument); } return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\document\async\spi\impl\CreateCounterDocPP.java
1
请完成以下Java代码
public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystem_Other_ConfigParameter_ID (final int ExternalSystem_Other_ConfigParameter_ID) { if (ExternalSystem_Other_ConfigParameter_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Other_ConfigParameter_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Other_ConfigParameter_ID, ExternalSystem_Other_ConfigParameter_ID); } @Override public int getExternalSystem_Other_ConfigParameter_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Other_ConfigParameter_ID); } @Override public void setName (final String Name) { set_Value (COLUMNNAME_Name, Name); } @Override
public String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final @Nullable String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Other_ConfigParameter.java
1
请完成以下Java代码
public String getTableNameOrNull(final DocumentId documentId) { return null; } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return processes; } @Override protected InvoiceRows getRowsData() { return InvoiceRows.cast(super.getRowsData()); } public void addInvoice(@NonNull final InvoiceId invoiceId) { final InvoiceRows invoiceRows = getRowsData(); invoiceRows.addInvoice(invoiceId); } @Override public LookupValuesPage getFieldTypeahead(final RowEditingContext ctx, final String fieldName, final String query) { throw new UnsupportedOperationException(); } @Override public LookupValuesList getFieldDropdown(final RowEditingContext ctx, final String fieldName) {
throw new UnsupportedOperationException(); } public void markPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds) { getRowsData().markPreparedForAllocation(rowIds); invalidateAll(); } public void unmarkPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds) { getRowsData().unmarkPreparedForAllocation(rowIds); invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoicesView.java
1
请完成以下Java代码
private void createBankStatementLineRef( @NonNull final PaymentToLink paymentToLink, @NonNull final I_C_BankStatementLine bankStatementLine, final int lineNo) { final PaymentId paymentId = paymentToLink.getPaymentId(); final I_C_Payment payment = getPaymentById(paymentId); final BankStatementLineReference lineRef = bankStatementDAO.createBankStatementLineRef(BankStatementLineRefCreateRequest.builder() .bankStatementId(BankStatementId.ofRepoId(bankStatementLine.getC_BankStatement_ID())) .bankStatementLineId(BankStatementLineId.ofRepoId(bankStatementLine.getC_BankStatementLine_ID())) .processed(bankStatementLine.isProcessed()) // .orgId(OrgId.ofRepoId(bankStatementLine.getAD_Org_ID())) // .lineNo(lineNo) // .paymentId(paymentId) .bpartnerId(BPartnerId.ofRepoId(payment.getC_BPartner_ID())) .invoiceId(InvoiceId.ofRepoIdOrNull(payment.getC_Invoice_ID())) // .trxAmt(moneyService.toMoney(paymentToLink.getStatementLineAmt())) // .build()); // // Mark payment as reconciled
if (doReconcilePayments) { paymentBL.markReconciledAndSave( payment, PaymentReconcileReference.bankStatementLineRef(lineRef.getId())); } // linkedPayments.add(PaymentLinkResult.builder() .bankStatementId(lineRef.getBankStatementId()) .bankStatementLineId(lineRef.getBankStatementLineId()) .bankStatementLineRefId(lineRef.getBankStatementLineRefId()) .paymentId(lineRef.getPaymentId()) .statementTrxAmt(lineRef.getTrxAmt()) .paymentMarkedAsReconciled(payment.isReconciled()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\BankStatementLineMultiPaymentLinkCommand.java
1
请完成以下Java代码
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * Type AD_Reference_ID=540047 * Reference name: AD_BoilerPlate_VarType */ public static final int TYPE_AD_Reference_ID=540047; /** SQL = S */ public static final String TYPE_SQL = "S"; /** Rule Engine = R */ public static final String TYPE_RuleEngine = "R"; /** Set Type. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Type. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set Search Key.
@param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ @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\de\metas\letters\model\X_AD_BoilerPlate_Var.java
1
请在Spring Boot框架中完成以下Java代码
public String getRootScopeType() { return rootScopeType; } @Override public void setRootScopeType(String rootScopeType) { this.rootScopeType = rootScopeType; } @Override public Date getCreateTime() { return createTime; } @Override
public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String getHierarchyType() { return hierarchyType; } @Override public void setHierarchyType(String hierarchyType) { this.hierarchyType = hierarchyType; } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\HistoricEntityLinkEntityImpl.java
2
请在Spring Boot框架中完成以下Java代码
public DeliveryRecipientType getDeliveryRecipient() { return deliveryRecipient; } /** * Sets the value of the deliveryRecipient property. * * @param value * allowed object is * {@link DeliveryRecipientType } * */ public void setDeliveryRecipient(DeliveryRecipientType value) { this.deliveryRecipient = value; } /** * Details about the delivery of good or services specified in this document. * * @return * possible object is
* {@link DeliveryDetailsType } * */ public DeliveryDetailsType getDeliveryDetails() { return deliveryDetails; } /** * Sets the value of the deliveryDetails property. * * @param value * allowed object is * {@link DeliveryDetailsType } * */ public void setDeliveryDetails(DeliveryDetailsType value) { this.deliveryDetails = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DeliveryType.java
2
请在Spring Boot框架中完成以下Java代码
public String getServerEventId() { return serverEventId; } public void setServerEventId(String serverEventId) { this.serverEventId = serverEventId; } /** * * @return the date when this record was created, which is also the date when the sync request was submitted towards the remote endpoint. */ @Override public Date getDateCreated() { return super.getDateCreated(); } /** * * @return the date when the remote endpoint actually confirmed the data receipt. */ public Date getDateConfirmed() { return dateConfirmed; } public void setDateConfirmed(Date dateConfirmed) { this.dateConfirmed = dateConfirmed; } /** *
* @return the date when our local endpoint received the remote endpoint's confirmation. */ public Date getDateConfirmReceived() { return dateConfirmReceived; } public void setDateConfirmReceived(Date dateConfirmReceived) { this.dateConfirmReceived = dateConfirmReceived; } public long getEntryId() { return entryId; } public void setEntryId(long entryId) { this.entryId = entryId; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\SyncConfirm.java
2
请完成以下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 Category getCategory() { return category; } public void setCategory(Category category) { this.category = category;
} public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public Product clone() throws CloneNotSupportedException { Product clone = (Product) super.clone(); clone.setId(null); return clone; } }
repos\tutorials-master\persistence-modules\java-jpa-4\src\main\java\com\baeldung\jpa\cloneentity\Product.java
1
请完成以下Java代码
public String docValidate (PO po, int type) { log.info("po.get_TableName() = " + po.get_TableName()); String result = null; if (expHelper != null) { try { if ( type == TIMING_AFTER_COMPLETE || type == TIMING_AFTER_CLOSE || type == TIMING_AFTER_REVERSECORRECT || type == TIMING_AFTER_VOID || type == TIMING_AFTER_VOID || type == TIMING_AFTER_PREPARE ) { expHelper.exportRecord( po, MReplicationStrategy.REPLICATION_DOCUMENT , MReplicationStrategy.getReplicationDocument(po.getCtx(), m_AD_ReplicationStrategy_ID, po.get_Table_ID()).getReplicationType(), type); } } catch (Exception e) { e.printStackTrace(); result = e.toString(); } } return result; } /** * User Login. * Called when preferences are set * @param AD_Org_ID org * @param AD_Role_ID role * @param AD_User_ID user * @return error message or null */ public String login (int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { m_AD_Org_ID = AD_Org_ID; m_AD_Role_ID = AD_Role_ID; m_AD_User_ID = AD_User_ID;
log.info("AD_Org_ID =" + m_AD_Org_ID); log.info("AD_Role_ID =" + m_AD_Role_ID); log.info("AD_User_ID =" + m_AD_User_ID); return null; } /** * Get Client to be monitored * @return AD_Client_ID client */ public int getAD_Client_ID() { return m_AD_Client_ID; } /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer (ExportModelValidator.class.getName()); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\ExportModelValidator.java
1
请完成以下Java代码
public class SslUtils { private static void trustAllHttpsCertificates() throws Exception { TrustManager[] trustAllCerts = new TrustManager[1]; TrustManager tm = new miTM(); trustAllCerts[0] = tm; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } static class miTM implements TrustManager, X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { }
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { } } /** * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用 */ public static void ignoreSsl() throws Exception { HostnameVerifier hv = (urlHostName, session) -> true; trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv); } }
repos\kkFileView-master\server\src\main\java\cn\keking\utils\SslUtils.java
1
请完成以下Java代码
public ILock getExistingLockForOwner(final LockOwner lockOwner) { return getLockDatabase().retrieveLockForOwner(lockOwner); } @Override public <T> IQueryFilter<T> getNotLockedFilter(@NonNull String modelTableName, @NonNull String joinColumnNameFQ) { return getLockDatabase().getNotLockedFilter(modelTableName, joinColumnNameFQ); } @Override public <T> IQueryBuilder<T> getLockedRecordsQueryBuilder(final Class<T> modelClass, final Object contextProvider) { return getLockDatabase().getLockedRecordsQueryBuilder(modelClass, contextProvider); } @Override public int removeAutoCleanupLocks() { return getLockDatabase().removeAutoCleanupLocks(); } @Override public <T> List<T> retrieveAndLockMultipleRecords(@NonNull final IQuery<T> query, @NonNull final Class<T> clazz) { return getLockDatabase().retrieveAndLockMultipleRecords(query, clazz); } @Override
public <T> IQuery<T> addNotLockedClause(final IQuery<T> query) { return getLockDatabase().addNotLockedClause(query); } @Override public ExistingLockInfo getLockInfo(final TableRecordReference tableRecordReference, final LockOwner lockOwner) { return getLockDatabase().getLockInfo(tableRecordReference, lockOwner); } @Override public SetMultimap<TableRecordReference, ExistingLockInfo> getLockInfosByRecordIds(final @NonNull TableRecordReferenceSet recordRefs) { return getLockDatabase().getLockInfosByRecordIds(recordRefs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockManager.java
1
请完成以下Java代码
public class CorrelationPropertyBindingImpl extends BaseElementImpl implements CorrelationPropertyBinding { protected static AttributeReference<CorrelationProperty> correlationPropertyRefAttribute; protected static ChildElement<DataPath> dataPathChild; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CorrelationPropertyBinding.class, BPMN_ELEMENT_CORRELATION_PROPERTY_BINDING) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<CorrelationPropertyBinding>() { public CorrelationPropertyBinding newInstance(ModelTypeInstanceContext instanceContext) { return new CorrelationPropertyBindingImpl(instanceContext); } }); correlationPropertyRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_CORRELATION_PROPERTY_REF) .required() .qNameAttributeReference(CorrelationProperty.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); dataPathChild = sequenceBuilder.element(DataPath.class) .required() .build(); typeBuilder.build();
} public CorrelationPropertyBindingImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public CorrelationProperty getCorrelationProperty() { return correlationPropertyRefAttribute.getReferenceTargetElement(this); } public void setCorrelationProperty(CorrelationProperty correlationProperty) { correlationPropertyRefAttribute.setReferenceTargetElement(this, correlationProperty); } public DataPath getDataPath() { return dataPathChild.getChild(this); } public void setDataPath(DataPath dataPath) { dataPathChild.setChild(this, dataPath); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CorrelationPropertyBindingImpl.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { reportMetrics(commandContext); JobEntity jobEntity = commandContext.getJobManager().findJobById(jobId); boolean rescheduled = false; if (isRescheduleNow) { commandContext.getJobManager().reschedule(jobEntity, ClockUtil.getCurrentTime()); rescheduled = true; cancelCountEmptyRuns(configuration, jobEntity); } else { if (HistoryCleanupHelper.isWithinBatchWindow(ClockUtil.getCurrentTime(), commandContext.getProcessEngineConfiguration())) { Date nextRunDate = configuration.getNextRunWithDelay(ClockUtil.getCurrentTime()); if (HistoryCleanupHelper.isWithinBatchWindow(nextRunDate, commandContext.getProcessEngineConfiguration())) { commandContext.getJobManager().reschedule(jobEntity, nextRunDate); rescheduled = true; incrementCountEmptyRuns(configuration, jobEntity); } } } if (!rescheduled) { if (HistoryCleanupHelper.isBatchWindowConfigured(commandContext)) { rescheduleRegularCall(commandContext, jobEntity); } else { suspendJob(jobEntity); } cancelCountEmptyRuns(configuration, jobEntity); } return null; } protected void rescheduleRegularCall(CommandContext commandContext, JobEntity jobEntity) { final BatchWindow nextBatchWindow = commandContext.getProcessEngineConfiguration().getBatchWindowManager()
.getNextBatchWindow(ClockUtil.getCurrentTime(), commandContext.getProcessEngineConfiguration()); if (nextBatchWindow != null) { commandContext.getJobManager().reschedule(jobEntity, nextBatchWindow.getStart()); } else { LOG.warnHistoryCleanupBatchWindowNotFound(); suspendJob(jobEntity); } } protected void suspendJob(JobEntity jobEntity) { jobEntity.setSuspensionState(SuspensionState.SUSPENDED.getStateCode()); } protected void incrementCountEmptyRuns(HistoryCleanupJobHandlerConfiguration configuration, JobEntity jobEntity) { configuration.setCountEmptyRuns(configuration.getCountEmptyRuns() + 1); jobEntity.setJobHandlerConfiguration(configuration); } protected void cancelCountEmptyRuns(HistoryCleanupJobHandlerConfiguration configuration, JobEntity jobEntity) { configuration.setCountEmptyRuns(0); jobEntity.setJobHandlerConfiguration(configuration); } protected void reportMetrics(CommandContext commandContext) { ProcessEngineConfigurationImpl engineConfiguration = commandContext.getProcessEngineConfiguration(); if (engineConfiguration.isHistoryCleanupMetricsEnabled()) { for (Map.Entry<String, Long> report : reports.entrySet()){ engineConfiguration.getDbMetricsReporter().reportValueAtOnce(report.getKey(), report.getValue()); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupSchedulerCmd.java
1
请完成以下Java代码
public void deleteDocuments(DocumentIdsSelection documentIds) { throw new InvalidDocumentStateException(parentDocument, RESULT_TabSingleRowDetail.getName()); } @Override public DocumentValidStatus checkAndGetValidStatus(OnValidStatusChanged onValidStatusChanged) { if (singleDocument != null) { final DocumentValidStatus validState = singleDocument.checkAndGetValidStatus(onValidStatusChanged); if (!validState.isValid()) { logger.trace("Considering included document as invalid for saving because it is not valid; validState={}; document={}", validState, singleDocument); return validState; } } return DocumentValidStatus.documentValid(); } @Override public boolean hasChangesRecursivelly() { if (singleDocument == null) { return false; } return singleDocument.hasChangesRecursivelly(); } @Override public void saveIfHasChanges() { if (singleDocument != null) { final DocumentSaveStatus saveStatus = singleDocument.saveIfHasChanges(); if (saveStatus.isSaved()) { forgetSingleDocument(); }
else if (saveStatus.isDeleted()) { singleDocument.markAsDeleted(); forgetSingleDocument(); } } } private final void forgetSingleDocument() { singleDocument = null; } @Override public void markStaleAll() { staled = true; parentDocument.getChangesCollector().collectStaleDetailId(parentDocumentPath, getDetailId()); } @Override public void markStale(final DocumentIdsSelection rowIds) { markStaleAll(); } @Override public boolean isStale() { return staled; } @Override public int getNextLineNo() { return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\SingleRowDetailIncludedDocumentsCollection.java
1
请完成以下Java代码
public void createTopic(String topicName) throws Exception { try (Admin admin = Admin.create(properties)) { int partitions = 1; short replicationFactor = 1; NewTopic newTopic = new NewTopic(topicName, partitions, replicationFactor); CreateTopicsResult result = admin.createTopics(Collections.singleton(newTopic)); // get the async result for the new topic creation KafkaFuture<Void> future = result.values() .get(topicName); // call get() to block until topic creation has completed or failed future.get(); } } public void createTopicWithOptions(String topicName) throws Exception { Properties props = new Properties(); props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); try (Admin admin = Admin.create(props)) { int partitions = 1; short replicationFactor = 1; NewTopic newTopic = new NewTopic(topicName, partitions, replicationFactor); CreateTopicsOptions topicOptions = new CreateTopicsOptions().validateOnly(true) .retryOnQuotaViolation(true); CreateTopicsResult result = admin.createTopics(Collections.singleton(newTopic), topicOptions);
KafkaFuture<Void> future = result.values() .get(topicName); future.get(); } } public void createCompactedTopicWithCompression(String topicName) throws Exception { Properties props = new Properties(); props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); try (Admin admin = Admin.create(props)) { int partitions = 1; short replicationFactor = 1; // Create a compacted topic with 'lz4' compression codec Map<String, String> newTopicConfig = new HashMap<>(); newTopicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT); newTopicConfig.put(TopicConfig.COMPRESSION_TYPE_CONFIG, "lz4"); NewTopic newTopic = new NewTopic(topicName, partitions, replicationFactor).configs(newTopicConfig); CreateTopicsResult result = admin.createTopics(Collections.singleton(newTopic)); KafkaFuture<Void> future = result.values() .get(topicName); future.get(); } } }
repos\tutorials-master\apache-kafka-2\src\main\java\com\baeldung\kafka\admin\KafkaTopicApplication.java
1
请完成以下Java代码
public class TraceInterceptor implements ProducerInterceptor<String, String> { private int errorCounter = 0; private int successCounter = 0; /** * 最先调用,读取配置信息,只调用一次 */ @Override public void configure(Map<String, ?> configs) { System.out.println(JSON.toJSONString(configs)); } /** * 它运行在用户主线程中,在消息序列化和计算分区之前调用,这里最好不小修改topic 和分区参数,否则会出一些奇怪的现象。 * * @param record * @return */ @Override public ProducerRecord<String, String> onSend(ProducerRecord<String, String> record) { Headers headers = new RecordHeaders(); headers.add("traceId", UUID.randomUUID().toString().getBytes(Charset.forName("UTF8"))); // 修改消息 return new ProducerRecord<>(record.topic(), record.partition(), record.key(), record.value(), headers); } /** * 该方法会在消息从 RecordAccumulator 成功发送到 Kafka Broker 之后,或者在发送过程 中失败时调用。 * 并且通常都是在 producer 回调逻辑触发之前调用。 * onAcknowledgement 运行在 producer 的 IO 线程中,因此不要在该方法中放入很重的逻辑,否则会拖慢 producer 的消息 发送效率。 * * @param metadata * @param exception
*/ @Override public void onAcknowledgement(RecordMetadata metadata, Exception exception) { if (Objects.isNull(exception)) { // TODO 出错了 } } /** * 关闭 interceptor,主要用于执行一些资源清理工作,只调用一次 */ @Override public void close() { System.out.println("==========close============"); } }
repos\spring-boot-student-master\spring-boot-student-kafka\src\main\java\com\xiaolyuh\interceptor\TraceInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig { private final TokenAuthProvider tokenAuthProvider; private final ProducerTemplate producerTemplate; private final AuthenticationConfiguration authConfig; public WebSecurityConfig( @NotNull final TokenAuthProvider tokenAuthProvider, @NotNull final ProducerTemplate producerTemplate, @NotNull final AuthenticationConfiguration authConfig) { this.tokenAuthProvider = tokenAuthProvider; this.producerTemplate = producerTemplate; this.authConfig = authConfig; } @Bean public SecurityFilterChain filterChain(@NotNull final HttpSecurity http) throws Exception { //@formatter:off http.authenticationProvider(tokenAuthProvider) /** * CSRF disabled because: clients do not maintain browser sessions, authentication is stateless, we manually handle authentication and authorization
*/ .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authorize -> authorize .requestMatchers("/**" + RestServiceRoutes.WOO.getPath()).hasAuthority(RestServiceRoutes.WOO.getStringAuthority()) .requestMatchers("/**" + RestServiceRoutes.GRS.getPath()).hasAuthority(RestServiceRoutes.GRS.getStringAuthority()) .requestMatchers("/**" + ScriptedImportConversionDynamicAuthorizationManager.PATTERN).access(ScriptedImportConversionDynamicAuthorizationManager::getAuthorizationDecision) .requestMatchers("/actuator/**").hasAuthority(ACTUATOR_AUTHORITY) .anyRequest() .authenticated() ); //@formatter:on http.addFilterBefore(new AuthenticationFilter(authConfig.getAuthenticationManager()), BasicAuthenticationFilter.class); http.addFilterAfter(new AuditTrailFilter(producerTemplate), AuthenticationFilter.class); return http.build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\restapi\auth\WebSecurityConfig.java
2
请完成以下Java代码
public void setScrappedQty (java.math.BigDecimal ScrappedQty) { set_Value (COLUMNNAME_ScrappedQty, ScrappedQty); } /** Get Verworfene Menge. @return The Quantity scrapped due to QA issues */ @Override public java.math.BigDecimal getScrappedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty); if (bd == null) return Env.ZERO; return bd; } /** Set Zielmenge. @param TargetQty Target Movement Quantity */ @Override public void setTargetQty (java.math.BigDecimal TargetQty) { set_Value (COLUMNNAME_TargetQty, TargetQty); } /** Get Zielmenge. @return Target Movement Quantity */
@Override public java.math.BigDecimal getTargetQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty); if (bd == null) return Env.ZERO; return bd; } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { throw new IllegalArgumentException ("Value is virtual column"); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @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\compiere\model\X_M_MovementLine.java
1