instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public String getTenantIdLike() { return tenantIdLike; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getWithoutTenantId() { return withoutTenantId; } public String getCandidateOrAssigned() { return candidateOrAssigned; } public void setCandidateOrAssigned(String candidateOrAssigned) { this.candidateOrAssigned = candidateOrAssigned; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; }
public List<String> getCategoryIn() { return categoryIn; } public void setCategoryIn(List<String> categoryIn) { this.categoryIn = categoryIn; } public List<String> getCategoryNotIn() { return categoryNotIn; } public void setCategoryNotIn(List<String> categoryNotIn) { this.categoryNotIn = categoryNotIn; } public Boolean getWithoutCategory() { return withoutCategory; } public void setWithoutCategory(Boolean withoutCategory) { this.withoutCategory = withoutCategory; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskQueryRequest.java
2
请完成以下Java代码
private static class AggregatedAcctDocProvider implements IAcctDocProvider { private final ImmutableMap<String, IAcctDocProvider> providersByDocTableName; private AggregatedAcctDocProvider(final List<IAcctDocProvider> providers) { final ImmutableMap.Builder<String, IAcctDocProvider> mapBuilder = ImmutableMap.builder(); for (final IAcctDocProvider provider : providers) { for (final String docTableName : provider.getDocTableNames()) { mapBuilder.put(docTableName, provider); } } this.providersByDocTableName = mapBuilder.build(); } public boolean isAccountingTable(final String docTableName) { return getDocTableNames().contains(docTableName); } @Override public Set<String> getDocTableNames() { return providersByDocTableName.keySet(); } @Override public Doc<?> getOrNull( @NonNull final AcctDocRequiredServicesFacade services, @NonNull final List<AcctSchema> acctSchemas, @NonNull final TableRecordReference documentRef) { try { final String docTableName = documentRef.getTableName();
final IAcctDocProvider provider = providersByDocTableName.get(docTableName); if (provider == null) { return null; } return provider.getOrNull(services, acctSchemas, documentRef); } catch (final AdempiereException ex) { throw ex; } catch (final Exception ex) { throw PostingExecutionException.wrapIfNeeded(ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\AcctDocRegistry.java
1
请完成以下Java代码
public class ZipScriptScanner extends ForwardingScriptScanner { public static final transient List<String> SUPPORTED_EXTENSIONS = Arrays.asList("zip", "jar"); private static final transient Logger logger = LoggerFactory.getLogger(ZipScriptScanner.class); private final IFileRef rootFileRef; private DirectoryScriptScanner delegate = null; // lazy public ZipScriptScanner(final IFileRef fileRef) { rootFileRef = fileRef; } @Override protected synchronized IScriptScanner getDelegate() { DirectoryScriptScanner delegate = this.delegate; if (delegate == null) {
delegate = this.delegate = createDirectoryScriptScanner(); } return delegate; } private DirectoryScriptScanner createDirectoryScriptScanner() { final Stopwatch stopwatch = Stopwatch.createStarted(); final File zipFile = rootFileRef.getFile(); final File unzipDir = FileUtils.unzip(zipFile); stopwatch.stop(); logger.info("Unzipped {} to {} in {}", zipFile, unzipDir, stopwatch); return new DirectoryScriptScanner(new FileRef(unzipDir)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\ZipScriptScanner.java
1
请完成以下Java代码
protected void checkDefinitionFound(String definitionId, DecisionRequirementsDefinitionEntity definition) { ensureNotNull("no deployed decision requirements definition found with id '" + definitionId + "'", "decisionRequirementsDefinition", definition); } @Override protected void checkInvalidDefinitionByKey(String definitionKey, DecisionRequirementsDefinitionEntity definition) { // not needed } @Override protected void checkInvalidDefinitionByKeyAndTenantId(String definitionKey, String tenantId, DecisionRequirementsDefinitionEntity definition) { // not needed } @Override protected void checkInvalidDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId, DecisionRequirementsDefinitionEntity definition) { // not needed }
@Override protected void checkInvalidDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId, DecisionRequirementsDefinitionEntity definition) { // not needed } @Override protected void checkInvalidDefinitionByDeploymentAndKey(String deploymentId, String definitionKey, DecisionRequirementsDefinitionEntity definition) { // not needed } @Override protected void checkInvalidDefinitionWasCached(String deploymentId, String definitionId, DecisionRequirementsDefinitionEntity definition) { ensureNotNull("deployment '" + deploymentId + "' didn't put decision requirements definition '" + definitionId + "' in the cache", "cachedDecisionRequirementsDefinition", definition); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\DecisionRequirementsDefinitionCache.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; public BookstoreService(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } public void newAuthor() { Book book = new Book(); book.setIsbn("001-JN"); book.setTitle("A History of Ancient Prague"); book.setPrice(45); Author author = new Author(); author.setName("Joana Nimar"); author.setAge(34); author.setGenre("History"); author.setBook(book); authorRepository.save(author); }
public void byName() { Author author = authorRepository.findByName("Joana Nimar"); System.out.println(author); } public void byNameIsbn() { Author author = authorRepository.findByBookIsbn("001-JN"); System.out.println(author); } public void byBookIsbnNativeQuery() { Author author = authorRepository.findByBookIsbnNativeQuery("001-JN"); System.out.println(author); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJsonToMySQL\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
I_PMM_Balance retrieveForDateSegment(final PMMBalanceSegment segment, final Date date, final DateSegment dateSegment) { // // Set the date segment values final Timestamp monthDate = TimeUtil.trunc(date, TimeUtil.TRUNC_MONTH); final Timestamp weekDate; if (dateSegment == DateSegment.Week) { weekDate = TimeUtil.trunc(date, TimeUtil.TRUNC_WEEK); } else if (dateSegment == DateSegment.Month) { weekDate = null; } else { throw new AdempiereException("@NotSupported@ " + DateSegment.class + ": " + dateSegment); } final PlainContextAware context = PlainContextAware.newWithThreadInheritedTrx(); I_PMM_Balance balanceRecord = Services.get(IQueryBL.class).createQueryBuilder(I_PMM_Balance.class, context) // // BPartner + Product segment .addEqualsFilter(I_PMM_Balance.COLUMN_C_BPartner_ID, segment.getC_BPartner_ID()) .addEqualsFilter(I_PMM_Balance.COLUMN_M_Product_ID, segment.getM_Product_ID()) .addEqualsFilter(I_PMM_Balance.COLUMN_M_AttributeSetInstance_ID, segment.getM_AttributeSetInstance_ID() > 0 ? segment.getM_AttributeSetInstance_ID() : null) // .addEqualsFilter(I_PMM_Balance.COLUMN_M_HU_PI_Item_Product_ID, segment.getM_HU_PI_Item_Product_ID() > 0 ? segment.getM_HU_PI_Item_Product_ID() : null) .addEqualsFilter(I_PMM_Balance.COLUMN_C_Flatrate_DataEntry_ID, segment.getC_Flatrate_DataEntry_ID() > 0 ? segment.getC_Flatrate_DataEntry_ID() : null) // // Date segment .addEqualsFilter(I_PMM_Balance.COLUMN_MonthDate, monthDate) .addEqualsFilter(I_PMM_Balance.COLUMN_WeekDate, weekDate) // .create() .firstOnly(I_PMM_Balance.class); // // Create new record if not found if (balanceRecord == null) { balanceRecord = InterfaceWrapperHelper.newInstance(I_PMM_Balance.class, context); balanceRecord.setAD_Org_ID(Env.CTXVALUE_AD_Org_ID_Any);
// // BPartner + Product segment balanceRecord.setC_BPartner_ID(segment.getC_BPartner_ID()); balanceRecord.setM_Product_ID(segment.getM_Product_ID()); if (segment.getM_AttributeSetInstance_ID() > 0) { balanceRecord.setM_AttributeSetInstance_ID(segment.getM_AttributeSetInstance_ID()); } // balanceRecord.setM_HU_PI_Item_Product_ID(segment.getM_HU_PI_Item_Product_ID()); if (segment.getC_Flatrate_DataEntry_ID() > 0) { balanceRecord.setC_Flatrate_DataEntry_ID(segment.getC_Flatrate_DataEntry_ID()); } // // Date segment balanceRecord.setMonthDate(monthDate); balanceRecord.setWeekDate(weekDate); // // Qtys balanceRecord.setQtyOrdered(BigDecimal.ZERO); balanceRecord.setQtyOrdered_TU(BigDecimal.ZERO); balanceRecord.setQtyPromised(BigDecimal.ZERO); balanceRecord.setQtyPromised_TU(BigDecimal.ZERO); } return balanceRecord; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\balance\impl\PMMBalanceDAO.java
1
请完成以下Java代码
public @NonNull CurrencyCode getCurrencyCodeById(@NonNull final CurrencyId currencyId) { return currencyDAO.getCurrencyCodeById(currencyId); } @Override @NonNull public Currency getByCurrencyCode(@NonNull final CurrencyCode currencyCode) { return currencyDAO.getByCurrencyCode(currencyCode); } @Override @NonNull public Money convertToBase(@NonNull final CurrencyConversionContext conversionCtx, @NonNull final Money amt) { final CurrencyId currencyToId = getBaseCurrencyId(conversionCtx.getClientId(), conversionCtx.getOrgId()); final CurrencyConversionResult currencyConversionResult = convert(conversionCtx, amt, currencyToId); return Money.of(currencyConversionResult.getAmount(), currencyToId); } private static CurrencyConversionResult.CurrencyConversionResultBuilder prepareCurrencyConversionResult(@NonNull final CurrencyConversionContext conversionCtx) { return CurrencyConversionResult.builder() .clientId(conversionCtx.getClientId()) .orgId(conversionCtx.getOrgId()) .conversionDate(conversionCtx.getConversionDate()) .conversionTypeId(conversionCtx.getConversionTypeId()); } @Override public Money convert( @NonNull final Money amount, @NonNull final CurrencyId toCurrencyId, @NonNull final LocalDate conversionDate, @NonNull final ClientAndOrgId clientAndOrgId) { if (CurrencyId.equals(amount.getCurrencyId(), toCurrencyId)) { return amount; } else if(amount.isZero())
{ return Money.zero(toCurrencyId); } final CurrencyConversionContext conversionCtx = createCurrencyConversionContext( LocalDateAndOrgId.ofLocalDate(conversionDate, clientAndOrgId.getOrgId()), (CurrencyConversionTypeId)null, clientAndOrgId.getClientId()); final CurrencyConversionResult conversionResult = convert( conversionCtx, amount.toBigDecimal(), amount.getCurrencyId(), toCurrencyId); return Money.of(conversionResult.getAmount(), toCurrencyId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\CurrencyBL.java
1
请完成以下Java代码
public class TaskCancelledListenerDelegate implements ActivitiEventListener { private final List<TaskRuntimeEventListener<TaskCancelledEvent>> listeners; private final ToTaskCancelledConverter toTaskCancelledConverter; public TaskCancelledListenerDelegate( List<TaskRuntimeEventListener<TaskCancelledEvent>> listeners, ToTaskCancelledConverter toTaskCancelledConverter ) { this.listeners = listeners; this.toTaskCancelledConverter = toTaskCancelledConverter; } @Override public void onEvent(ActivitiEvent event) {
if (event instanceof ActivitiEntityEvent) { toTaskCancelledConverter .from((ActivitiEntityEvent) event) .ifPresent(convertedEvent -> { for (TaskRuntimeEventListener<TaskCancelledEvent> listener : listeners) { listener.onEvent(convertedEvent); } }); } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TaskCancelledListenerDelegate.java
1
请在Spring Boot框架中完成以下Java代码
public class NotificationsCleanUpService extends AbstractCleanUpService { private final SqlPartitioningRepository partitioningRepository; private final NotificationRequestDao notificationRequestDao; @Value("${sql.ttl.notifications.ttl:2592000}") private long ttlInSec; @Value("${sql.notifications.partition_size:168}") private int partitionSizeInHours; public NotificationsCleanUpService(PartitionService partitionService, SqlPartitioningRepository partitioningRepository, NotificationRequestDao notificationRequestDao) { super(partitionService); this.partitioningRepository = partitioningRepository; this.notificationRequestDao = notificationRequestDao; } @Scheduled(initialDelayString = "#{T(org.apache.commons.lang3.RandomUtils).nextLong(0, ${sql.ttl.notifications.checking_interval_ms:86400000})}", fixedDelayString = "${sql.ttl.notifications.checking_interval_ms:86400000}") public void cleanUp() {
long expTime = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(ttlInSec); long partitionDurationMs = TimeUnit.HOURS.toMillis(partitionSizeInHours); if (!isSystemTenantPartitionMine()) { partitioningRepository.cleanupPartitionsCache(NOTIFICATION_TABLE_NAME, expTime, partitionDurationMs); return; } long lastRemovedNotificationTs = partitioningRepository.dropPartitionsBefore(NOTIFICATION_TABLE_NAME, expTime, partitionDurationMs); if (lastRemovedNotificationTs > 0) { long gap = TimeUnit.MINUTES.toMillis(10); long requestExpTime = lastRemovedNotificationTs - TimeUnit.SECONDS.toMillis(NotificationRequestConfig.MAX_SENDING_DELAY) - gap; int removed = notificationRequestDao.removeAllByCreatedTimeBefore(requestExpTime); log.info("Removed {} outdated notification requests older than {}", removed, requestExpTime); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ttl\NotificationsCleanUpService.java
2
请在Spring Boot框架中完成以下Java代码
public class Account { @Id private int id; @Column private String name; @Column private String type; @Column private boolean active; @Column private String description; public Account() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name;
} public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\dynamicinsert\model\Account.java
2
请完成以下Java代码
public PickingJobStepPickFrom getPickFrom(final PickingJobStepPickFromKey key) { final PickingJobStepPickFrom pickFrom = map.get(key); if (pickFrom == null) { throw new AdempiereException("No Pick From defined for " + key); } return pickFrom; } public PickingJobStepPickFrom getPickFromByHUQRCode(@NonNull final HUQRCode qrCode) { return map.values() .stream() .filter(pickFrom -> HUQRCode.equals(pickFrom.getPickFromHU().getQrCode(), qrCode)) .findFirst() .orElseThrow(() -> new AdempiereException("No HU found for " + qrCode)); } public boolean isNothingPicked() { return map.values().stream().allMatch(PickingJobStepPickFrom::isNotPicked); } public PickingJobStepPickFromMap reduceWithPickedEvent( @NonNull PickingJobStepPickFromKey key, @NonNull PickingJobStepPickedTo pickedTo) { return withChangedPickFrom(key, pickFrom -> pickFrom.withPickedEvent(pickedTo)); } public PickingJobStepPickFromMap reduceWithUnpickEvent( @NonNull PickingJobStepPickFromKey key, @NonNull PickingJobStepUnpickInfo unpicked) { return withChangedPickFrom(key, pickFrom -> pickFrom.withUnPickedEvent(unpicked)); } private PickingJobStepPickFromMap withChangedPickFrom( @NonNull PickingJobStepPickFromKey key, @NonNull UnaryOperator<PickingJobStepPickFrom> pickFromMapper) { if (!map.containsKey(key)) { throw new AdempiereException("No PickFrom " + key + " found in " + this); } final ImmutableMap<PickingJobStepPickFromKey, PickingJobStepPickFrom> newMap = CollectionUtils.mapValue(map, key, pickFromMapper); return !Objects.equals(this.map, newMap) ? new PickingJobStepPickFromMap(newMap) : this; } public Optional<Quantity> getQtyPicked() { return map.values() .stream() .map(pickFrom -> pickFrom.getQtyPicked().orElse(null)) .filter(Objects::nonNull) .reduce(Quantity::add);
} public Optional<Quantity> getQtyRejected() { // returning only from mainPickFrom because I wanted to keep the same logic we already have in misc/services/mobile-webui/mobile-webui-frontend/src/utils/picking.js, getQtyPickedOrRejectedTotalForLine return getMainPickFrom().getQtyRejected(); } @NonNull public List<HuId> getPickedHUIds() { return map.values() .stream() .map(PickingJobStepPickFrom::getPickedTo) .filter(Objects::nonNull) .filter(pickedTo -> pickedTo.getQtyPicked().signum() > 0) .map(PickingJobStepPickedTo::getPickedHuIds) .flatMap(List::stream) .collect(ImmutableList.toImmutableList()); } @NonNull public Optional<PickingJobStepPickedToHU> getLastPickedHU() { return map.values() .stream() .map(PickingJobStepPickFrom::getPickedTo) .filter(Objects::nonNull) .filter(pickedTo -> pickedTo.getQtyPicked().signum() > 0) .map(PickingJobStepPickedTo::getLastPickedHu) .filter(Optional::isPresent) .map(Optional::get) .max(Comparator.comparing(PickingJobStepPickedToHU::getCreatedAt)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickFromMap.java
1
请完成以下Java代码
public void setMD_Candidate_Purchase_Detail_ID (int MD_Candidate_Purchase_Detail_ID) { if (MD_Candidate_Purchase_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_Purchase_Detail_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_Purchase_Detail_ID, Integer.valueOf(MD_Candidate_Purchase_Detail_ID)); } @Override public int getMD_Candidate_Purchase_Detail_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_Purchase_Detail_ID); } @Override public void setM_ReceiptSchedule_ID (int M_ReceiptSchedule_ID) { if (M_ReceiptSchedule_ID < 1) set_Value (COLUMNNAME_M_ReceiptSchedule_ID, null); else set_Value (COLUMNNAME_M_ReceiptSchedule_ID, Integer.valueOf(M_ReceiptSchedule_ID)); } @Override public int getM_ReceiptSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID); } @Override public void setPlannedQty (java.math.BigDecimal PlannedQty) { set_Value (COLUMNNAME_PlannedQty, PlannedQty); } @Override public java.math.BigDecimal getPlannedQty() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPP_Product_Planning_ID (int PP_Product_Planning_ID) { if (PP_Product_Planning_ID < 1) set_Value (COLUMNNAME_PP_Product_Planning_ID, null); else set_Value (COLUMNNAME_PP_Product_Planning_ID, Integer.valueOf(PP_Product_Planning_ID));
} @Override public int getPP_Product_Planning_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID); } @Override public void setQtyOrdered (java.math.BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public java.math.BigDecimal getQtyOrdered() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Purchase_Detail.java
1
请在Spring Boot框架中完成以下Java代码
public String getCorrelationId() { return correlationId; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() {
return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } public boolean isExecutable() { return executable; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\TimerJobQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
class OidcLogoutAuthenticationToken extends AbstractAuthenticationToken { @Serial private static final long serialVersionUID = -1568528983223505540L; private final String logoutToken; private final ClientRegistration clientRegistration; /** * Construct an {@link OidcLogoutAuthenticationToken} * @param logoutToken a signed, serialized OIDC Logout token * @param clientRegistration the {@link ClientRegistration client} associated with * this token; this is usually derived from material in the logout HTTP request */ OidcLogoutAuthenticationToken(String logoutToken, ClientRegistration clientRegistration) { super(AuthorityUtils.NO_AUTHORITIES); this.logoutToken = logoutToken; this.clientRegistration = clientRegistration; } /** * {@inheritDoc} */ @Override public String getCredentials() { return this.logoutToken; } /**
* {@inheritDoc} */ @Override public String getPrincipal() { return this.logoutToken; } /** * Get the signed, serialized OIDC Logout token * @return the logout token */ String getLogoutToken() { return this.logoutToken; } /** * Get the {@link ClientRegistration} associated with this logout token * @return the {@link ClientRegistration} */ ClientRegistration getClientRegistration() { return this.clientRegistration; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OidcLogoutAuthenticationToken.java
2
请完成以下Java代码
private static ManageSchedulerRequest extractManageSchedulerRequest(@NonNull final Event event) { final String requestStr = event.getProperty(PROPERTY_ManageSchedulerRequest); final ManageSchedulerRequest request; try { request = JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(requestStr, ManageSchedulerRequest.class); } catch (final JsonProcessingException e) { throw new AdempiereException("Exception deserializing manageSchedulerRequest", e) .appendParametersToMessage() .setParameter("manageSchedulerRequest", requestStr); } return request; } private void registerHandler(@NonNull final ManageSchedulerRequestHandler handler) { getEventBus().subscribe(SchedulerEventBusService.ManageSchedulerRequestHandlerAsEventListener.builder() .handler(handler) .eventLogUserService(eventLogUserService) .build()); logger.info("Registered handler: {}", handler); } @lombok.ToString private static final class ManageSchedulerRequestHandlerAsEventListener implements IEventListener { private final EventLogUserService eventLogUserService; private final ManageSchedulerRequestHandler handler; @lombok.Builder private ManageSchedulerRequestHandlerAsEventListener( @NonNull final ManageSchedulerRequestHandler handler, @NonNull final EventLogUserService eventLogUserService)
{ this.handler = handler; this.eventLogUserService = eventLogUserService; } @Override public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event) { final ManageSchedulerRequest request = extractManageSchedulerRequest(event); try (final IAutoCloseable ignored = switchCtx(request); final MDC.MDCCloseable ignored1 = MDC.putCloseable("eventHandler.className", handler.getClass().getName())) { eventLogUserService.invokeHandlerAndLog(EventLogUserService.InvokeHandlerAndLogRequest.builder() .handlerClass(handler.getClass()) .invokaction(() -> handleRequest(request)) .build()); } } private void handleRequest(@NonNull final ManageSchedulerRequest request) { handler.handleRequest(request); } private IAutoCloseable switchCtx(@NonNull final ManageSchedulerRequest request) { final Properties ctx = createCtx(request); return Env.switchContext(ctx); } private Properties createCtx(@NonNull final ManageSchedulerRequest request) { final Properties ctx = Env.newTemporaryCtx(); Env.setClientId(ctx, request.getClientId()); return ctx; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scheduler\eventbus\SchedulerEventBusService.java
1
请完成以下Java代码
protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (ProcessInfoParameter element : para) { String name = element.getParameterName(); if (element.getParameter() == null) { } else { log.error("Unknown Parameter: " + name); } } p_M_InOut_ID = getRecord_ID(); } @Override protected String doIt() throws Exception { final I_M_InOut inOut = InterfaceWrapperHelper.create(getCtx(), p_M_InOut_ID, I_M_InOut.class, getTrxName()); final IInOutInvoiceCandidateBL inOutBL = Services.get(IInOutInvoiceCandidateBL.class); final boolean isApprovedForInvoicing = inOutBL.isApproveInOutForInvoicing(inOut); // set the flag on true if the inout is active and complete/closed inOut.setIsInOutApprovedForInvoicing(isApprovedForInvoicing); InterfaceWrapperHelper.save(inOut); // set the linked rechnungsdispos as inOutApprovedForInvoicing and ApprovedForInvoicing inOutBL.approveForInvoicingLinkedInvoiceCandidates(inOut); return MSG_OK; }
@Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { // Make this process only available for inout entries that are active and have the status Completed or Closed if (I_M_InOut.Table_Name.equals(context.getTableName())) { final I_M_InOut inout = context.getSelectedModel(I_M_InOut.class); final DocStatus inoutDocStatus = DocStatus.ofCode(inout.getDocStatus()); return ProcessPreconditionsResolution.acceptIf(inoutDocStatus.isCompletedOrClosed()); } else { return ProcessPreconditionsResolution.reject(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\process\M_InOut_ApproveForInvoicing.java
1
请完成以下Java代码
public final void initialize(final ModelValidationEngine engine, final MClient client) { if (client != null) { ad_Client_ID = client.getAD_Client_ID(); } engine.addModelChange(I_C_OrderLine.Table_Name, this); engine.addModelChange(I_M_Storage.Table_Name, this); } @Override public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { // nothing to do return null; } @Override public String docValidate(final PO po, final int timing) { // nothing to do return null; } @Override public String modelChange(final PO po, int type) { if (type != TYPE_BEFORE_CHANGE && type != TYPE_BEFORE_NEW) { return null;
} if (!po.is_ValueChanged(I_C_OrderLine.COLUMNNAME_QtyReserved)) { return null; } if (po instanceof MStorage) { final MStorage st = (MStorage)po; if (st.getQtyReserved().signum() < 0) { st.setQtyReserved(BigDecimal.ZERO); // no need for the warning & stacktrace for now. // final AdempiereException ex = new AdempiereException("@" + C_OrderLine.ERR_NEGATIVE_QTY_RESERVED + "@. Setting QtyReserved to ZERO." // + "\nStorage: " + st); // logger.warn(ex.getLocalizedMessage(), ex); logger.info(Services.get(IMsgBL.class).getMsg(po.getCtx(), C_OrderLine.ERR_NEGATIVE_QTY_RESERVED.toAD_MessageWithMarkers() + ". Setting QtyReserved to ZERO." + "\nStorage: " + st)); return null; } } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\ProhibitNegativeQtyReserved.java
1
请完成以下Java代码
public static List<Field> getClassFields(Class<?> clazz) { List<Field> list = new ArrayList<Field>(); Field[] fields; do{ fields = clazz.getDeclaredFields(); for(int i = 0;i<fields.length;i++){ list.add(fields[i]); } clazz = clazz.getSuperclass(); }while(clazz!= Object.class&&clazz!=null); return list; } /** * 获取表字段名 * @param clazz * @param name * @return */ public static String getTableFieldName(Class<?> clazz, String name) { try { //如果字段加注解了@TableField(exist = false),不走DB查询 Field field = null; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException e) { //e.printStackTrace(); } //如果为空,则去父类查找字段 if (field == null) { List<Field> allFields = getClassFields(clazz); List<Field> searchFields = allFields.stream().filter(a -> a.getName().equals(name)).collect(Collectors.toList()); if(searchFields!=null && searchFields.size()>0){
field = searchFields.get(0); } } if (field != null) { TableField tableField = field.getAnnotation(TableField.class); if (tableField != null){ if(tableField.exist() == false){ //如果设置了TableField false 这个字段不需要处理 return null; }else{ String column = tableField.value(); //如果设置了TableField value 这个字段是实体字段 if(!"".equals(column)){ return column; } } } } } catch (Exception e) { e.printStackTrace(); } return name; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\ReflectHelper.java
1
请完成以下Java代码
public class ResponseUtil { /** * 往 response 写出 json * * @param response 响应 * @param status 状态 * @param data 返回数据 */ public static void renderJson(HttpServletResponse response, IStatus status, Object data) { try { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setContentType("application/json;charset=UTF-8"); response.setStatus(200); // FIXME: hutool 的 BUG:JSONUtil.toJsonStr() // 将JSON转为String的时候,忽略null值的时候转成的String存在错误 response.getWriter().write(JSONUtil.toJsonStr(new JSONObject(ApiResponse.ofStatus(status, data), false))); } catch (IOException e) { log.error("Response写出JSON异常,", e); }
} /** * 往 response 写出 json * * @param response 响应 * @param exception 异常 */ public static void renderJson(HttpServletResponse response, BaseException exception) { try { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setContentType("application/json;charset=UTF-8"); response.setStatus(200); // FIXME: hutool 的 BUG:JSONUtil.toJsonStr() // 将JSON转为String的时候,忽略null值的时候转成的String存在错误 response.getWriter().write(JSONUtil.toJsonStr(new JSONObject(ApiResponse.ofException(exception), false))); } catch (IOException e) { log.error("Response写出JSON异常,", e); } } }
repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\util\ResponseUtil.java
1
请完成以下Java代码
public class UserPrincipal implements UserDetails { /** * 主键 */ private Long id; /** * 用户名 */ private String username; /** * 密码 */ @JsonIgnore private String password; /** * 昵称 */ private String nickname; /** * 手机 */ private String phone; /** * 邮箱 */ private String email; /** * 生日 */ private Long birthday; /** * 性别,男-1,女-2 */ private Integer sex; /** * 状态,启用-1,禁用-0 */ private Integer status; /** * 创建时间 */ private Long createTime; /** * 更新时间 */ private Long updateTime; /** * 用户角色列表
*/ private List<String> roles; /** * 用户权限列表 */ private Collection<? extends GrantedAuthority> authorities; public static UserPrincipal create(User user, List<Role> roles, List<Permission> permissions) { List<String> roleNames = roles.stream().map(Role::getName).collect(Collectors.toList()); List<GrantedAuthority> authorities = permissions.stream().filter(permission -> StrUtil.isNotBlank(permission.getPermission())).map(permission -> new SimpleGrantedAuthority(permission.getPermission())).collect(Collectors.toList()); return new UserPrincipal(user.getId(), user.getUsername(), user.getPassword(), user.getNickname(), user.getPhone(), user.getEmail(), user.getBirthday(), user.getSex(), user.getStatus(), user.getCreateTime(), user.getUpdateTime(), roleNames, authorities); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return Objects.equals(this.status, Consts.ENABLE); } }
repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\vo\UserPrincipal.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_Calendar_ID (int C_Calendar_ID) { if (C_Calendar_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, Integer.valueOf(C_Calendar_ID)); } @Override public int getC_Calendar_ID() { return get_ValueAsInt(COLUMNNAME_C_Calendar_ID); } @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return (java.lang.String)get_Value(COLUMNNAME_Description); }
@Override public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } @Override public boolean isDefault() { return get_ValueAsBoolean(COLUMNNAME_IsDefault); } @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Calendar.java
1
请在Spring Boot框架中完成以下Java代码
public String xxlJobRemove() { Map<String, Object> jobInfo = Maps.newHashMap(); jobInfo.put("id", 4); HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/remove").form(jobInfo).execute(); log.info("【execute】= {}", execute); return execute.body(); } /** * 测试手动停止任务 */ @GetMapping("/stop") public String xxlJobStop() { Map<String, Object> jobInfo = Maps.newHashMap(); jobInfo.put("id", 4); HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/stop").form(jobInfo).execute(); log.info("【execute】= {}", execute);
return execute.body(); } /** * 测试手动启动任务 */ @GetMapping("/start") public String xxlJobStart() { Map<String, Object> jobInfo = Maps.newHashMap(); jobInfo.put("id", 4); HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/start").form(jobInfo).execute(); log.info("【execute】= {}", execute); return execute.body(); } }
repos\spring-boot-demo-master\demo-task-xxl-job\src\main\java\com\xkcoding\task\xxl\job\controller\ManualOperateController.java
2
请完成以下Java代码
public String getKey() { return key; } @Override public Optional<String> getStrValue() { return Optional.ofNullable(null); } @Override public Optional<Long> getLongValue() { return Optional.ofNullable(null); } @Override public Optional<Boolean> getBooleanValue() { return Optional.ofNullable(null); } @Override public Optional<Double> getDoubleValue() { return Optional.ofNullable(null); } @Override public Optional<String> getJsonValue() { return Optional.ofNullable(null); } @Override
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof BasicKvEntry)) return false; BasicKvEntry that = (BasicKvEntry) o; return Objects.equals(key, that.key); } @Override public int hashCode() { return Objects.hash(key); } @Override public String toString() { return "BasicKvEntry{" + "key='" + key + '\'' + '}'; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BasicKvEntry.java
1
请完成以下Java代码
public void setReversal_ID (int Reversal_ID) { if (Reversal_ID < 1) set_Value (COLUMNNAME_Reversal_ID, null); else set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID)); } /** Get Reversal ID. @return ID of document reversal */ @Override public int getReversal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class); } @Override public void setSalesRep(org.compiere.model.I_AD_User SalesRep) { set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep); } /** Set Aussendienst. @param SalesRep_ID Aussendienst */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Aussendienst. @return Aussendienst */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } /** Set Nutzer 1. @param User1_ID User defined list element #1 */ @Override public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get Nutzer 1. @return User defined list element #1 */ @Override public int getUser1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); if (ii == null)
return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } /** Set Nutzer 2. @param User2_ID User defined list element #2 */ @Override public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get Nutzer 2. @return User defined list element #2 */ @Override public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Movement.java
1
请完成以下Java代码
public class CassandraClient { private static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class); public static void main(String args[]) { CassandraConnector connector = new CassandraConnector(); connector.connect("127.0.0.1", null); Session session = connector.getSession(); KeyspaceRepository sr = new KeyspaceRepository(session); sr.createKeyspace("library", "SimpleStrategy", 1); sr.useKeyspace("library"); BookRepository br = new BookRepository(session); br.createTable(); br.alterTablebooks("publisher", "text"); br.createTableBooksByTitle();
Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming"); br.insertBookBatch(book); br.selectAll().forEach(o -> LOG.info("Title in books: " + o.getTitle())); br.selectAllBookByTitle().forEach(o -> LOG.info("Title in booksByTitle: " + o.getTitle())); br.deletebookByTitle("Effective Java"); br.deleteTable("books"); br.deleteTable("booksByTitle"); sr.deleteKeyspace("library"); connector.close(); } }
repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\cassandra\java\client\CassandraClient.java
1
请完成以下Java代码
public class SseClientApp { private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices"; public static void main(String... args) throws Exception { Client client = ClientBuilder.newClient(); WebTarget target = client.target(url); try (SseEventSource eventSource = SseEventSource.target(target).build()) { eventSource.register(onEvent, onError, onComplete); eventSource.open(); //Consuming events for one hour Thread.sleep(60 * 60 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } client.close(); System.out.println("End"); }
// A new event is received private static Consumer<InboundSseEvent> onEvent = (inboundSseEvent) -> { String data = inboundSseEvent.readData(); System.out.println(data); }; //Error private static Consumer<Throwable> onError = (throwable) -> { throwable.printStackTrace(); }; //Connection close and there is nothing to receive private static Runnable onComplete = () -> { System.out.println("Done!"); }; }
repos\tutorials-master\apache-cxf-modules\sse-jaxrs\sse-jaxrs-client\src\main\java\com\baeldung\sse\jaxrs\client\SseClientApp.java
1
请在Spring Boot框架中完成以下Java代码
public class GithubIssueLinkMatcher { static String PROJECT_OWNER_TOKEN = "ownerToken"; static String PROJECT_REFERENCE_TOKEN = "projectToken"; static String OWNER_GROUP = "owner"; static String PROJECT_GROUP ="project"; static String ISSUE_NO_GROUP = "issueNo"; static String ISSUE_LINK_PATTERN = "https:\\/\\/github.com\\/(?<owner>ownerToken)\\/(?<project>projectToken)\\/issues\\/(?<issueNo>[0-9]+)"; Pattern linkPattern; public static GithubIssueLinkMatcher of(final ImmutableSet<String> owners, final ImmutableSet<String> projects) { final Joiner joiner = Joiner.on("|"); final String pattern = ISSUE_LINK_PATTERN .replace(PROJECT_OWNER_TOKEN,joiner.join(owners)) .replace(PROJECT_REFERENCE_TOKEN, joiner.join(projects)); return new GithubIssueLinkMatcher(Pattern.compile(pattern)); } @NonNull public Optional<GithubIssueLink> getFirstMatch(@NonNull final String textToParse) { final Matcher matcher = linkPattern.matcher(textToParse); if (matcher.find()) { return Optional.of(buildIssueLink(matcher)); } return Optional.empty(); } @NonNull private GithubIssueLink buildIssueLink(@NonNull final Matcher matcher) {
return GithubIssueLink.builder() .githubIdSearchKey( GithubIdSearchKey .builder() .repositoryOwner(matcher.group(OWNER_GROUP)) .repository(matcher.group(PROJECT_GROUP)) .issueNo(matcher.group(ISSUE_NO_GROUP)) .build()) .url(matcher.group().trim()) .build(); } private GithubIssueLinkMatcher(@NonNull final Pattern pattern) { this.linkPattern = pattern; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\github\link\GithubIssueLinkMatcher.java
2
请完成以下Spring Boot application配置
logging.level.org.springframework=info #spring.security.user.name=in28minutes #spring.security.user.password=dummy spring.datasource.url=jdbc:h2:mem:testdb spring.jpa.defer-datasource-initialization=true spring.main.banner-mo
de=off logging.pattern.console= %d{MM-dd HH:mm:ss} - %logger{36} - %msg%n #CHANGE server.port=5000
repos\master-spring-and-spring-boot-main\91-aws\03-rest-api-full-stack-h2\src\main\resources\application.properties
2
请完成以下Java代码
public class JacksonJsonDataFormatReader extends TextBasedDataFormatReader { private static final JacksonJsonLogger JSON_LOGGER = JacksonJsonLogger.JSON_TREE_LOGGER; private static final Pattern INPUT_MATCHING_PATTERN = Pattern.compile("\\A(\\s)*[{\\[]"); protected JacksonJsonDataFormat format; public JacksonJsonDataFormatReader(JacksonJsonDataFormat format) { this.format = format; } public Object readInput(Reader input) { ObjectMapper mapper = format.getObjectMapper(); try { final JsonNode jsonNode = mapper.readTree(input); if (jsonNode instanceof MissingNode) { throw new IOException("Input is empty");
} return jsonNode; } catch (JsonProcessingException e) { throw JSON_LOGGER.unableToParseInput(e); } catch (IOException e) { throw JSON_LOGGER.unableToParseInput(e); } } protected Pattern getInputDetectionPattern() { return INPUT_MATCHING_PATTERN; } }
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\format\JacksonJsonDataFormatReader.java
1
请完成以下Java代码
public String getSerializerName() { return typedValueField.getSerializerName(); } @Override public void setSerializerName(String serializerName) { typedValueField.setSerializerName(serializerName); } public String getByteArrayValueId() { return byteArrayField.getByteArrayId(); } public byte[] getByteArrayValue() { return byteArrayField.getByteArrayValue(); } public void setByteArrayValue(byte[] bytes) { byteArrayField.setByteArrayValue(bytes); } public String getName() { return getVariableName(); } // entity lifecycle ///////////////////////////////////////////////////////// public void postLoad() { // make sure the serializer is initialized typedValueField.postLoad(); } // getters and setters ////////////////////////////////////////////////////// public String getTypeName() { return typedValueField.getTypeName(); } public String getVariableTypeName() { return getTypeName(); } public Date getTime() { return timestamp; }
@Override public String toString() { return this.getClass().getSimpleName() + "[variableName=" + variableName + ", variableInstanceId=" + variableInstanceId + ", revision=" + revision + ", serializerName=" + serializerName + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue + ", textValue2=" + textValue2 + ", byteArrayId=" + byteArrayId + ", activityInstanceId=" + activityInstanceId + ", eventType=" + eventType + ", executionId=" + executionId + ", id=" + id + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntity.java
1
请完成以下Java代码
public @Nullable String getGroupId() { return this.groupId; } /** * Return the client id. * @return the client id. * @since 3.2 */ @Nullable public String getClientId() { return this.clientId; } /** * Return the source topic. * @return the source. */ public String getSource() { return this.record.topic(); } /** * Return the consumer record. * @return the record. * @since 3.0.6 */ public ConsumerRecord<?, ?> getRecord() { return this.record; } /** * Return the partition.
* @return the partition. * @since 3.2 */ public String getPartition() { return Integer.toString(this.record.partition()); } /** * Return the offset. * @return the offset. * @since 3.2 */ public String getOffset() { return Long.toString(this.record.offset()); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaRecordReceiverContext.java
1
请完成以下Java代码
public void setTelephone(String telephone) { this.telephone = telephone; } /** * Get the user type. * * @return the user type */ public Integer getUserType() { return userType; } /** * Set the user type. * * @param userType the user type */ public void setUserType(Integer userType) { this.userType = userType; } /** * Get the creates the by. * * @return the creates the by */ public String getCreateBy() { return createBy; } /** * Set the creates the by. * * @param createBy the creates the by */ public void setCreateBy(String createBy) { this.createBy = createBy; } /** * Get the creates the time. * * @return the creates the time */ public Date getCreateTime() { return createTime; } /** * Set the creates the time. * * @param createTime the creates the time */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * Get the update by. * * @return the update by */ public String getUpdateBy() { return updateBy; } /** * Set the update by. * * @param updateBy the update by */ public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } /** * Get the update time. * * @return the update time */ public Date getUpdateTime() { return updateTime; }
/** * Set the update time. * * @param updateTime the update time */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } /** * Get the disabled. * * @return the disabled */ public Integer getDisabled() { return disabled; } /** * Set the disabled. * * @param disabled the disabled */ public void setDisabled(Integer disabled) { this.disabled = disabled; } /** * Get the theme. * * @return the theme */ public String getTheme() { return theme; } /** * Set the theme. * * @param theme theme */ public void setTheme(String theme) { this.theme = theme; } /** * Get the checks if is ldap. * * @return the checks if is ldap */ public Integer getIsLdap() { return isLdap; } /** * Set the checks if is ldap. * * @param isLdap the checks if is ldap */ public void setIsLdap(Integer isLdap) { this.isLdap = isLdap; } }
repos\springBoot-master\springboot-mybatis\src\main\java\com\us\example\bean\User.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { this.processInstanceQuery = processInstanceQuery; } public boolean isSkipIoMappings() { return skipIoMappings; } public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMappings = skipIoMappings; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners; } public void applyTo(ModificationBuilder builder, ProcessEngine processEngine, ObjectMapper objectMapper) { for (ProcessInstanceModificationInstructionDto instruction : instructions) { instruction.applyTo(builder, processEngine, objectMapper);
} } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { this.historicProcessInstanceQuery = historicProcessInstanceQuery; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ModificationDto.java
1
请完成以下Java代码
public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Schema(description = "JSON representation of the Administration Settings value") public JsonNode getJsonValue() { return jsonValue; } public void setJsonValue(JsonNode jsonValue) { this.jsonValue = jsonValue; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((jsonValue == null) ? 0 : jsonValue.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false; AdminSettings other = (AdminSettings) obj; if (jsonValue == null) { if (other.jsonValue != null) return false; } else if (!jsonValue.equals(other.jsonValue)) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("AdminSettings [key="); builder.append(key); builder.append(", jsonValue="); builder.append(jsonValue); builder.append(", createdTime="); builder.append(createdTime); builder.append(", id="); builder.append(id); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\AdminSettings.java
1
请在Spring Boot框架中完成以下Java代码
public ApplicationRunner init() { return args -> { System.out.println("\n------------------- Joana Nimar's Books --------------------"); List<Book> detachedBooks = bookstoreService.fetchBooksOfAuthor("Joana Nimar"); detachedBooks.forEach(b -> System.out.println(b)); System.out.println("\n---------- Books of Joana Nimar updated in detached state------------"); // ,update first book title detachedBooks.get(0).setTitle("A History of Ancient Rome"); // remove second title detachedBooks.remove(1); // add a new book
Book book = new Book(); book.setTitle("History In 100 Minutes"); book.setIsbn("005-JN"); detachedBooks.add(book); detachedBooks.forEach(b -> System.out.println(b)); System.out.println("\n----------------- Merging books of Joana Nimar ----------------"); bookstoreService.updateBooksOfAuthor("Joana Nimar", detachedBooks); System.out.println("\n----------------- Books of Joana Nimar After Merge ----------------"); List<Book> books = bookstoreService.fetchBooksOfAuthor("Joana Nimar"); books.forEach(b -> System.out.println(b)); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootMergeCollections\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public class CommonsParser { public static Map<String, Map<String, String>> parseIniFile(File fileToParse) throws IOException, ConfigurationException { Map<String, Map<String, String>> iniFileContents = new HashMap<>(); INIConfiguration iniConfiguration = new INIConfiguration(); try (FileReader fileReader = new FileReader(fileToParse)) { iniConfiguration.read(fileReader); } for (String section : iniConfiguration.getSections()) { Map<String, String> subSectionMap = new HashMap<>(); SubnodeConfiguration confSection = iniConfiguration.getSection(section); Iterator<String> keyIterator = confSection.getKeys(); while (keyIterator.hasNext()) { String key = keyIterator.next(); String value = confSection.getProperty(key) .toString();
subSectionMap.put(key, value); } iniFileContents.put(section, subSectionMap); } return iniFileContents; } public static String readIniFileValue(File fileToParse, String section, String value) throws IOException, ConfigurationException { INIConfiguration iniConfiguration = new INIConfiguration(); try (FileReader fileReader = new FileReader(fileToParse)) { iniConfiguration.read(fileReader); } return iniConfiguration.getSection(section).getProperty(value).toString(); } }
repos\tutorials-master\libraries-files\src\main\java\com\baeldung\ini\CommonsParser.java
1
请在Spring Boot框架中完成以下Java代码
public Map<TopicPartition, Long> getConsumerGrpOffsets(String groupId) throws ExecutionException, InterruptedException { ListConsumerGroupOffsetsResult info = adminClient.listConsumerGroupOffsets(groupId); Map<TopicPartition, OffsetAndMetadata> metadataMap = info .partitionsToOffsetAndMetadata() .get(); Map<TopicPartition, Long> groupOffset = new HashMap<>(); for (Map.Entry<TopicPartition, OffsetAndMetadata> entry : metadataMap.entrySet()) { TopicPartition key = entry.getKey(); OffsetAndMetadata metadata = entry.getValue(); groupOffset.putIfAbsent(new TopicPartition(key.topic(), key.partition()), metadata.offset()); } return groupOffset; } private Map<TopicPartition, Long> getProducerOffsets(Map<TopicPartition, Long> consumerGrpOffset) { List<TopicPartition> topicPartitions = new LinkedList<>(); for (Map.Entry<TopicPartition, Long> entry : consumerGrpOffset.entrySet()) { TopicPartition key = entry.getKey(); topicPartitions.add(new TopicPartition(key.topic(), key.partition())); } return consumer.endOffsets(topicPartitions); } public Map<TopicPartition, Long> computeLags( Map<TopicPartition, Long> consumerGrpOffsets, Map<TopicPartition, Long> producerOffsets) { Map<TopicPartition, Long> lags = new HashMap<>(); for (Map.Entry<TopicPartition, Long> entry : consumerGrpOffsets.entrySet()) { Long producerOffset = producerOffsets.get(entry.getKey()); Long consumerOffset = consumerGrpOffsets.get(entry.getKey()); long lag = Math.abs(Math.max(0, producerOffset) - Math.max(0, consumerOffset)); lags.putIfAbsent(entry.getKey(), lag); } return lags; }
private AdminClient getAdminClient(String bootstrapServerConfig) { Properties config = new Properties(); config.put( AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServerConfig); return AdminClient.create(config); } private KafkaConsumer<String, String> getKafkaConsumer( String bootstrapServerConfig) { Properties properties = new Properties(); properties.setProperty( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServerConfig); properties.setProperty( ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); properties.setProperty( ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); return new KafkaConsumer<>(properties); } }
repos\tutorials-master\spring-kafka-2\src\main\java\com\baeldung\spring\kafka\monitoring\service\LagAnalyzerService.java
2
请完成以下Java代码
private ProductPlanning createOrUpdateProductPlanningAndSave(@NonNull final ProductId productId, final @NonNull OrgId orgId, @NonNull final ProductPlanningSchema schema) { final ProductPlanningSchemaId schemaId = schema.getIdNotNull(); ProductPlanning productPlanning = productPlanningDAO.retrieveActiveProductPlanningByProductAndSchemaId(productId, schemaId).orElse(null); final ProductPlanning.ProductPlanningBuilder builder = productPlanning != null ? productPlanning.toBuilder() : ProductPlanning.builder(); builder.productId(productId); builder.productPlanningSchemaId(schemaId); updateProductPlanningFromSchema(builder, schema); builder.orgId(orgId); productPlanning = productPlanningDAO.save(builder.build()); return productPlanning; } private void updateProductPlanningFromSchemaAndSave( final ProductPlanning productPlanning, final ProductPlanningSchema schema) { final ProductPlanning.ProductPlanningBuilder builder = productPlanning.toBuilder(); updateProductPlanningFromSchema(builder, schema); productPlanningDAO.save(builder.build()); } private static void updateProductPlanningFromSchema(
final ProductPlanning.ProductPlanningBuilder builder, final ProductPlanningSchema schema) { builder.isAttributeDependant(schema.isAttributeDependant()); builder.plantId(schema.getPlantId()); builder.warehouseId(schema.getWarehouseId()); builder.plannerId(schema.getPlannerId()); builder.isManufactured(StringUtils.toBoolean(schema.getManufactured())); builder.isCreatePlan(schema.isCreatePlan()); builder.isDocComplete(schema.isCompleteGeneratedDocuments()); builder.workflowId(schema.getRoutingId()); builder.distributionNetworkId(schema.getDistributionNetworkId()); builder.isPickDirectlyIfFeasible(schema.isPickDirectlyIfFeasible()); builder.onMaterialReceiptWithDestWarehouse(schema.getOnMaterialReceiptWithDestWarehouse()); builder.manufacturingAggregationId(schema.getManufacturingAggregationId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impl\ProductPlanningSchemaBL.java
1
请在Spring Boot框架中完成以下Java代码
public JobServiceConfiguration getJobServiceConfiguration() { return jobServiceConfiguration; } @Override public void setJobServiceConfiguration(JobServiceConfiguration jobServiceConfiguration) { this.jobServiceConfiguration = jobServiceConfiguration; } protected boolean isAsyncExecutorActive() { return isExecutorActive(jobServiceConfiguration.getAsyncExecutor()); } protected boolean isAsyncExecutorRemainingCapacitySufficient(int neededCapacity) { return getAsyncExecutor().isActive() && getAsyncExecutor().getTaskExecutor().getRemainingCapacity() >= neededCapacity; } protected boolean isAsyncHistoryExecutorActive() { return isExecutorActive(jobServiceConfiguration.getAsyncHistoryExecutor()); } protected boolean isExecutorActive(AsyncExecutor asyncExecutor) { return asyncExecutor != null && asyncExecutor.isActive(); } protected CommandContext getCommandContext() { return Context.getCommandContext(); } protected AsyncExecutor getAsyncExecutor() { return jobServiceConfiguration.getAsyncExecutor();
} protected AsyncExecutor getAsyncHistoryExecutor() { return jobServiceConfiguration.getAsyncHistoryExecutor(); } protected void callJobProcessors(JobProcessorContext.Phase processorType, AbstractJobEntity abstractJobEntity) { JobProcessorUtil.callJobProcessors(jobServiceConfiguration, processorType, abstractJobEntity); } protected void callHistoryJobProcessors(HistoryJobProcessorContext.Phase processorType, HistoryJobEntity historyJobEntity) { JobProcessorUtil.callHistoryJobProcessors(jobServiceConfiguration, processorType, historyJobEntity); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\DefaultJobManager.java
2
请完成以下Java代码
public void invokeLater(final int windowNo, final Runnable runnable) { invoke() .setParentComponentByWindowNo(windowNo) .setInvokeLater(true) .setOnFail(OnFail.ThrowException) // backward compatibility .invoke(runnable); } /** * This method does nothing. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}. */ @Deprecated @Override public void hideBusyDialog() { // nothing } /** * This method does nothing. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#disableServerPush()}. */ @Deprecated
@Override public void disableServerPush() { // nothing } /** * This method throws an UnsupportedOperationException. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#infoNoWait(int, String)}. * @throws UnsupportedOperationException */ @Deprecated @Override public void infoNoWait(int WindowNo, String AD_Message) { throw new UnsupportedOperationException("not implemented"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUIInstance.java
1
请完成以下Java代码
private void process(final Object bean, final BiConsumer<EventBus, Object> consumer, final String action) { Object proxy = this.getTargetObject(bean); final Subscriber annotation = AnnotationUtils.getAnnotation(proxy.getClass(), Subscriber.class); if (annotation == null) return; this.logger.info("{}: processing bean of type {} during {}", this.getClass().getSimpleName(), proxy.getClass().getName(), action); final String annotationValue = annotation.value(); try { final Expression expression = this.expressionParser.parseExpression(annotationValue); final Object value = expression.getValue(); if (!(value instanceof EventBus)) { this.logger.error("{}: expression {} did not evaluate to an instance of EventBus for bean of type {}", this.getClass().getSimpleName(), annotationValue, proxy.getClass().getSimpleName()); return; } final EventBus eventBus = (EventBus)value; consumer.accept(eventBus, proxy); } catch (ExpressionException ex) { this.logger.error("{}: unable to parse/evaluate expression {} for bean of type {}", this.getClass().getSimpleName(), annotationValue, proxy.getClass().getName()); }
} private Object getTargetObject(Object proxy) throws BeansException { if (AopUtils.isJdkDynamicProxy(proxy)) { try { return ((Advised)proxy).getTargetSource().getTarget(); } catch (Exception e) { throw new FatalBeanException("Error getting target of JDK proxy", e); } } return proxy; } }
repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\beanpostprocessor\GuavaEventBusBeanPostProcessor.java
1
请完成以下Java代码
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 static MRegistrationAttribute get (Properties ctx, int A_RegistrationAttribute_ID, String trxName) { Integer key = new Integer(A_RegistrationAttribute_ID); MRegistrationAttribute retValue = (MRegistrationAttribute)s_cache.get(key); if (retValue == null) { retValue = new MRegistrationAttribute (ctx, A_RegistrationAttribute_ID, trxName); s_cache.put(key, retValue); } return retValue; } // getAll /** Static Logger */ private static Logger s_log = LogManager.getLogger(MRegistrationAttribute.class); /** Cache */ private static CCache<Integer,MRegistrationAttribute> s_cache = new CCache<Integer,MRegistrationAttribute>("A_RegistrationAttribute", 20); /************************************************************************** * Standard Constructor
* @param ctx context * @param A_RegistrationAttribute_ID id */ public MRegistrationAttribute (Properties ctx, int A_RegistrationAttribute_ID, String trxName) { super(ctx, A_RegistrationAttribute_ID, trxName); } // MRegistrationAttribute /** * Load Constructor * @param ctx context * @param rs result set */ public MRegistrationAttribute (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MRegistrationAttribute } // MRegistrationAttribute
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRegistrationAttribute.java
1
请完成以下Java代码
public class Category { public static final String JSON_PROPERTY_ID = "id"; private Long id; public static final String JSON_PROPERTY_NAME = "name"; private String name; public Category id(Long id) { this.id = id; return this; } /** * Get id * @return id **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Category name(String name) { this.name = name; return this; } /** * Get name * @return name **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(java.lang.Object o) { if (this == o) {
return true; } if (o == null || getClass() != o.getClass()) { return false; } Category category = (Category) o; return Objects.equals(this.id, category.id) && Objects.equals(this.name, category.name); } @Override public int hashCode() { return Objects.hash(id, name); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Category {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Category.java
1
请在Spring Boot框架中完成以下Java代码
public class Customer { @Id @GeneratedValue private long id; @Column(name = "first_name", nullable = false) private String firstName; @Column(name = "last_name", nullable = false) private String lastName; public Customer() { super(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName;
} public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; } }
repos\tutorials-master\docker-modules\docker-spring-boot-postgres\src\main\java\com\baeldung\docker\Customer.java
2
请在Spring Boot框架中完成以下Java代码
class User implements Serializable { @Id private Long id; private String username; private String password; @Transient private String repeatedPassword; public User() { } public User(Long id, String username, String password, String repeatedPassword) { this.id = id; this.username = username; this.password = password; this.repeatedPassword = repeatedPassword; } public Long getId() { return id; } public void setId(Long id) {
this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepeatedPassword() { return repeatedPassword; } public void setRepeatedPassword(String repeatedPassword) { this.repeatedPassword = repeatedPassword; } }
repos\tutorials-master\jackson-modules\jackson-annotations\src\main\java\com\baeldung\jackson\jsonignorevstransient\User.java
2
请完成以下Java代码
public static SimpleItem create(String param) { if (param == null) return null; String[] array = param.split(" "); return create(array); } public static SimpleItem create(String param[]) { if (param.length % 2 == 1) return null; SimpleItem item = new SimpleItem(); int natureCount = (param.length) / 2; for (int i = 0; i < natureCount; ++i) { item.labelMap.put(param[2 * i], Integer.parseInt(param[1 + 2 * i])); } return item; } /** * 合并两个条目,两者的标签map会合并 * @param other */ public void combine(SimpleItem other) { for (Map.Entry<String, Integer> entry : other.labelMap.entrySet()) { addLabel(entry.getKey(), entry.getValue()); }
} /** * 获取全部频次 * @return */ public int getTotalFrequency() { int frequency = 0; for (Integer f : labelMap.values()) { frequency += f; } return frequency; } public String getMostLikelyLabel() { return labelMap.entrySet().iterator().next().getKey(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\item\SimpleItem.java
1
请完成以下Java代码
public ResponseEntity<StreamingResponseBody> getZipStream() { return ResponseEntity .ok() .header("Content-Disposition", "attachment; filename=\"files.zip\"") .body(out -> { ZipOutputStream zipOutputStream = new ZipOutputStream(out); zipOutputStream.setLevel(9); addFilesToArchive(zipOutputStream); }); } @GetMapping(value = "/zip-archive-stream-secured", produces = "application/zip") public ResponseEntity<StreamingResponseBody> getZipSecuredStream() { return ResponseEntity .ok() .header("Content-Disposition", "attachment; filename=\"files.zip\"") .body(out -> { net.lingala.zip4j.io.outputstream.ZipOutputStream zipOutputStream = new net.lingala.zip4j.io.outputstream.ZipOutputStream(out, "password".toCharArray()); addFilesToArchive(zipOutputStream); }); } void addFilesToArchive(net.lingala.zip4j.io.outputstream.ZipOutputStream zipOutputStream) throws IOException { List<String> filesNames = new ArrayList<>(); filesNames.add("first-file.txt"); filesNames.add("second-file.txt"); ZipParameters zipParameters = new ZipParameters(); zipParameters.setCompressionMethod(CompressionMethod.DEFLATE); zipParameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD); zipParameters.setEncryptFiles(true); for (String fileName : filesNames) { File file = new File(ZipArchiveController.class.getClassLoader() .getResource(fileName).getFile()); zipParameters.setFileNameInZip(file.getName()); zipOutputStream.putNextEntry(zipParameters); FileInputStream fileInputStream = new FileInputStream(file); IOUtils.copy(fileInputStream, zipOutputStream); fileInputStream.close(); zipOutputStream.closeEntry(); } zipOutputStream.flush(); IOUtils.closeQuietly(zipOutputStream);
} void addFilesToArchive(ZipOutputStream zipOutputStream) throws IOException { List<String> filesNames = new ArrayList<>(); filesNames.add("first-file.txt"); filesNames.add("second-file.txt"); for (String fileName : filesNames) { File file = new File(ZipArchiveController.class.getClassLoader() .getResource(fileName).getFile()); zipOutputStream.putNextEntry(new ZipEntry(file.getName())); FileInputStream fileInputStream = new FileInputStream(file); IOUtils.copy(fileInputStream, zipOutputStream); fileInputStream.close(); zipOutputStream.closeEntry(); } zipOutputStream.finish(); zipOutputStream.flush(); IOUtils.closeQuietly(zipOutputStream); } }
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\zip\ZipArchiveController.java
1
请在Spring Boot框架中完成以下Java代码
public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getExpressNo() { return expressNo; } public void setExpressNo(String expressNo) { this.expressNo = expressNo; } public UserEntity getBuyer() { return buyer; } public void setBuyer(UserEntity buyer) { this.buyer = buyer; }
@Override public String toString() { return "OrdersEntity{" + "id='" + id + '\'' + ", buyer=" + buyer + ", company=" + company + ", productOrderList=" + productOrderList + ", orderStateEnum=" + orderStateEnum + ", orderStateTimeList=" + orderStateTimeList + ", payModeEnum=" + payModeEnum + ", totalPrice='" + totalPrice + '\'' + ", receiptEntity=" + receiptEntity + ", locationEntity=" + locationEntity + ", remark='" + remark + '\'' + ", expressNo='" + expressNo + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\OrdersEntity.java
2
请在Spring Boot框架中完成以下Java代码
public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo; } public String getCvn2() { return cvn2; } public void setCvn2(String cvn2) { this.cvn2 = cvn2; } public String getExpDate() { return expDate; } public void setExpDate(String expDate) { this.expDate = expDate; } public String getIsDefault() {
return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } public String getIsAuth() { return isAuth; } public void setIsAuth(String isAuth) { this.isAuth = isAuth; } public String getStatusDesc() { if (StringUtil.isEmpty(this.getStatus())) { return ""; } else { return PublicStatusEnum.getEnum(this.getStatus()).getDesc(); } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserQuickPayBankAccount.java
2
请完成以下Java代码
protected void createEventListeners(BpmnParse bpmnParse, List<EventListener> eventListeners) { if (eventListeners != null && !eventListeners.isEmpty()) { for (EventListener eventListener : eventListeners) { // Extract specific event-types (if any) ActivitiEventType[] types = ActivitiEventType.getTypesFromString(eventListener.getEvents()); if (ImplementationType.IMPLEMENTATION_TYPE_CLASS.equals(eventListener.getImplementationType())) { getEventSupport(bpmnParse.getBpmnModel()).addEventListener( bpmnParse.getListenerFactory().createClassDelegateEventListener(eventListener), types ); } else if ( ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals( eventListener.getImplementationType() ) ) { getEventSupport(bpmnParse.getBpmnModel()).addEventListener( bpmnParse.getListenerFactory().createDelegateExpressionEventListener(eventListener), types ); } else if ( ImplementationType.IMPLEMENTATION_TYPE_THROW_SIGNAL_EVENT.equals( eventListener.getImplementationType() ) || ImplementationType.IMPLEMENTATION_TYPE_THROW_GLOBAL_SIGNAL_EVENT.equals( eventListener.getImplementationType() ) || ImplementationType.IMPLEMENTATION_TYPE_THROW_MESSAGE_EVENT.equals( eventListener.getImplementationType() ) || ImplementationType.IMPLEMENTATION_TYPE_THROW_ERROR_EVENT.equals( eventListener.getImplementationType() ) ) { getEventSupport(bpmnParse.getBpmnModel()).addEventListener( bpmnParse.getListenerFactory().createEventThrowingEventListener(eventListener),
types ); } else { LOGGER.warn( "Unsupported implementation type for EventListener: " + eventListener.getImplementationType() + " for element " + bpmnParse.getCurrentFlowElement().getId() ); } } } } protected ActivitiEventSupport getEventSupport(BpmnModel bpmnModel) { return (ActivitiEventSupport) bpmnModel.getEventSupport(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\ProcessParseHandler.java
1
请在Spring Boot框架中完成以下Java代码
RSocketMessageHandler serverRSocketMessageHandler(RSocketStrategies rSocketStrategies, IntegrationProperties integrationProperties) { RSocketMessageHandler messageHandler = new ServerRSocketMessageHandler( integrationProperties.getRsocket().getServer().isMessageMappingEnabled()); messageHandler.setRSocketStrategies(rSocketStrategies); return messageHandler; } @Bean @ConditionalOnMissingBean ServerRSocketConnector serverRSocketConnector(ServerRSocketMessageHandler messageHandler) { return new ServerRSocketConnector(messageHandler); } } @Configuration(proxyBeanMethods = false) protected static class IntegrationRSocketClientConfiguration { @Bean @ConditionalOnMissingBean @Conditional(RemoteRSocketServerAddressConfigured.class) ClientRSocketConnector clientRSocketConnector(IntegrationProperties integrationProperties, RSocketStrategies rSocketStrategies) { IntegrationProperties.RSocket.Client client = integrationProperties.getRsocket().getClient(); ClientRSocketConnector clientRSocketConnector; if (client.getUri() != null) { clientRSocketConnector = new ClientRSocketConnector(client.getUri()); } else if (client.getHost() != null && client.getPort() != null) { clientRSocketConnector = new ClientRSocketConnector(client.getHost(), client.getPort()); } else { throw new IllegalStateException("Neither uri nor host and port is set");
} clientRSocketConnector.setRSocketStrategies(rSocketStrategies); return clientRSocketConnector; } /** * Check if a remote address is configured for the RSocket Integration client. */ static class RemoteRSocketServerAddressConfigured extends AnyNestedCondition { RemoteRSocketServerAddressConfigured() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty("spring.integration.rsocket.client.uri") static class WebSocketAddressConfigured { } @ConditionalOnProperty({ "spring.integration.rsocket.client.host", "spring.integration.rsocket.client.port" }) static class TcpAddressConfigured { } } } } }
repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationAutoConfiguration.java
2
请完成以下Java代码
private List<String> createUpdateSqls(int adReferenceId, Map<String, String> name2valuesMap) { final List<String> updateSqls = new ArrayList<>(name2valuesMap.size()); for (final Map.Entry<String, String> name2value : name2valuesMap.entrySet()) { final String name = name2value.getKey(); final String value = name2value.getValue(); final String sql = "UPDATE AD_Ref_List SET ValueName='" + name + "'" + " WHERE AD_Reference_ID=" + adReferenceId + " AND Value='" + value + "'" + ";"; updateSqls.add(sql); } return updateSqls; } private Map<String, String> extractNameAndValueForPrefix(String prefix, Field[] classFields) { final Map<String, String> name2value = new LinkedHashMap<>(); for (final Field field : classFields) { final String fieldName = field.getName(); if (!fieldName.startsWith(prefix)) { continue; } if (fieldName.endsWith(SUFFIX_AD_Reference_ID)) { continue; } final String name = fieldName.substring(prefix.length()); final String value = getFieldValueAsString(field); name2value.put(name, value); } return name2value; } private final String getFieldValueAsString(final Field field) { try { return (String)field.get(null); } catch (Exception e) { throw new RuntimeException("Cannot get value of " + field); } }
private final int getFieldValueAsInt(final Field field) { try { return (int)field.get(null); } catch (Exception e) { throw new RuntimeException("Cannot get value of " + field); } } private Class<?> loadClass(String classname) { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { return classLoader.loadClass(classname); } catch (ClassNotFoundException e) { throw new RuntimeException("Cannot load class: " + classname, e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\tools\AD_Ref_List_ValueName_UpdateFromClass.java
1
请完成以下Java代码
public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Write-off Amount. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Write-off Amount. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashLine.java
1
请在Spring Boot框架中完成以下Java代码
public LogoutResponseConfigurer logoutUrl(String logoutUrl) { this.logoutUrl = logoutUrl; return this; } /** * Use this {@link LogoutHandler} for processing a logout response from the * asserting party * @param authenticator the {@link AuthenticationManager} to use * @return the {@link LogoutRequestConfigurer} for further customizations */ public LogoutResponseConfigurer logoutResponseValidator(Saml2LogoutResponseValidator authenticator) { this.logoutResponseValidator = authenticator; return this; } /** * Use this {@link Saml2LogoutRequestResolver} for producing a logout response to * send to the asserting party * @param logoutResponseResolver the {@link Saml2LogoutResponseResolver} to use * @return the {@link LogoutRequestConfigurer} for further customizations */ public LogoutResponseConfigurer logoutResponseResolver(Saml2LogoutResponseResolver logoutResponseResolver) { this.logoutResponseResolver = logoutResponseResolver; return this; } private Saml2LogoutResponseValidator logoutResponseValidator() { if (this.logoutResponseValidator != null) { return this.logoutResponseValidator; } if (USE_OPENSAML_5) { return new OpenSaml5LogoutResponseValidator(); } throw new IllegalArgumentException( "Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5"); } private Saml2LogoutResponseResolver logoutResponseResolver(RelyingPartyRegistrationRepository registrations) { if (this.logoutResponseResolver != null) { return this.logoutResponseResolver; } if (USE_OPENSAML_5) { return new OpenSaml5LogoutResponseResolver(registrations); } throw new IllegalArgumentException( "Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5");
} } private static class Saml2RequestMatcher implements RequestMatcher { private final SecurityContextHolderStrategy securityContextHolderStrategy; Saml2RequestMatcher(SecurityContextHolderStrategy securityContextHolderStrategy) { this.securityContextHolderStrategy = securityContextHolderStrategy; } @Override public boolean matches(HttpServletRequest request) { Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); if (authentication == null) { return false; } if (authentication.getPrincipal() instanceof Saml2AuthenticatedPrincipal) { return true; } if (authentication.getCredentials() instanceof Saml2ResponseAssertionAccessor) { return true; } return authentication instanceof Saml2Authentication; } } private static class Saml2RelyingPartyInitiatedLogoutFilter extends LogoutFilter { Saml2RelyingPartyInitiatedLogoutFilter(LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers) { super(logoutSuccessHandler, handlers); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\saml2\Saml2LogoutConfigurer.java
2
请完成以下Java代码
public boolean setValueNoCheck(String propertyName, Object value) { return po.set_ValueOfColumn(propertyName, value); } @Override public Object getReferencedObject(final String propertyName, final Method interfaceMethod) throws Exception { final Class<?> returnType = interfaceMethod.getReturnType(); return po.get_ValueAsPO(propertyName, returnType); } @Override public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value) { po.set_ValueFromPO(idPropertyName, parameterType, value); } @Override public boolean invokeEquals(final Object[] methodArgs) { if (methodArgs == null || methodArgs.length != 1) {
throw new IllegalArgumentException("Invalid method arguments to be used for equals(): " + methodArgs); } return po.equals(methodArgs[0]); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { return method.invoke(po, methodArgs); } @Override public boolean isCalculated(final String columnName) { return getPOInfo().isCalculated(columnName); } @Override public boolean hasColumnName(final String columnName) { return getPOInfo().hasColumnName(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POModelInternalAccessor.java
1
请在Spring Boot框架中完成以下Java代码
public class InvokeActivateShopware6ExternalConfig extends InvokeActivateExternalConfig { public static final String PARAM_BASE_URL = "BaseURL"; @Param(parameterName = PARAM_BASE_URL) protected String baseURl; public static final String PARAM_CLIENT_ID = "Client_Id"; @Param(parameterName = PARAM_CLIENT_ID) protected String clientId; public static final String PARAM_CLIENT_SECRET = "Client_Secret"; @Param(parameterName = PARAM_CLIENT_SECRET) protected String clientSecret; @Override protected void activateRecord() { final ExternalSystemParentConfig parentConfig = getSelectedExternalSystemConfig(ExternalSystemParentConfigId.ofRepoId(getRecord_ID())) .orElseThrow(() -> new AdempiereException("No inactive externalSystemConfig found for parentConfig") .appendParametersToMessage() .setParameter("parentConfigId", ExternalSystemParentConfigId.ofRepoId(getRecord_ID()))); final ExternalSystemShopware6Config childConfig = ExternalSystemShopware6Config.cast(parentConfig.getChildConfig()) .toBuilder() .baseUrl(baseURl) .clientId(clientId) .clientSecret(clientSecret) .isActive(true) .build(); final ExternalSystemParentConfig recordUpdated = parentConfig.toBuilder() .active(true) .childConfig(childConfig) .build(); externalSystemConfigRepo.saveConfig(recordUpdated); }
@Override protected ExternalSystemType getExternalSystemType() { return ExternalSystemType.Shopware6; } @Override protected long getSelectedRecordCount(final IProcessPreconditionsContext context) { return context.getSelectedIncludedRecords() .stream() .filter(recordRef -> I_ExternalSystem_Config_Shopware6.Table_Name.equals(recordRef.getTableName())) .count(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeActivateShopware6ExternalConfig.java
2
请在Spring Boot框架中完成以下Java代码
private MonitoringEvent buildMonitoringEvent(String id, String device, String type, double value, long timestamp) { try { MonitoringEvent evt = new MonitoringEvent(); // Map generated values to the MonitoringEvent fields evt.setEventId(random.nextInt(10_000)); evt.setDeviceId(device); evt.setEventType(type); // Use a human-friendly event name String name = type + "-" + id.substring(0, 8); evt.setEventName(name); // creationDate as ISO-8601 string evt.setCreationDate(Instant.ofEpochMilli(timestamp).toString());
// status: for availability events, use UP/DOWN; otherwise store numeric value as string if ("APPLICATION_AVAILABILITY".equals(type)) { evt.setStatus(value == 1.0 ? "UP" : "DOWN"); } else { evt.setStatus(String.format("%.2f", value)); } return evt; } catch (Exception e) { // In case of unexpected error, return null (caller will skip) return null; } } }
repos\tutorials-master\netflix-modules\hollow\src\main\java\com\baeldung\hollow\service\MonitoringDataService.java
2
请完成以下Java代码
public class PP_Cost_Collector { private final IPPCostCollectorBL costCollectorBL = Services.get(IPPCostCollectorBL.class); private final IPPOrderRoutingRepository orderRoutingRepository = Services.get(IPPOrderRoutingRepository.class); @CalloutMethod(columnNames = I_PP_Cost_Collector.COLUMNNAME_PP_Order_ID) public void onPP_Order_ID(final I_PP_Cost_Collector cc) { final I_PP_Order ppOrder = cc.getPP_Order(); if (ppOrder == null) { return; } costCollectorBL.updateCostCollectorFromOrder(cc, ppOrder); } @CalloutMethod(columnNames = I_PP_Cost_Collector.COLUMNNAME_PP_Order_Node_ID) public void onPP_Order_Node_ID(final I_PP_Cost_Collector cc) { final PPOrderId orderId = PPOrderId.ofRepoIdOrNull(cc.getPP_Order_ID()); if (orderId == null) { return; } final PPOrderRoutingActivityId orderRoutingActivityId = PPOrderRoutingActivityId.ofRepoIdOrNull(orderId, cc.getPP_Order_Node_ID()); if (orderRoutingActivityId == null) { return; } final PPOrderRoutingActivity orderActivity = orderRoutingRepository.getOrderRoutingActivity(orderRoutingActivityId); cc.setS_Resource_ID(orderActivity.getResourceId().getRepoId()); cc.setIsSubcontracting(orderActivity.isSubcontracting()); final Quantity qtyToDeliver = orderActivity.getQtyToDeliver(); costCollectorBL.setQuantities(cc, PPCostCollectorQuantities.ofMovementQty(qtyToDeliver)); updateDurationReal(cc); // shall be automatically triggered } @CalloutMethod(columnNames = I_PP_Cost_Collector.COLUMNNAME_MovementQty) public void onMovementQty(final I_PP_Cost_Collector cc) { updateDurationReal(cc); }
/** * Calculates and sets DurationReal based on selected PP_Order_Node */ private void updateDurationReal(final I_PP_Cost_Collector cc) { final WorkingTime durationReal = computeWorkingTime(cc); if (durationReal == null) { return; } cc.setDurationReal(durationReal.toBigDecimalUsingActivityTimeUnit()); } @Nullable private WorkingTime computeWorkingTime(final I_PP_Cost_Collector cc) { final PPOrderId orderId = PPOrderId.ofRepoIdOrNull(cc.getPP_Order_ID()); if (orderId == null) { return null; } final PPOrderRoutingActivityId activityId = PPOrderRoutingActivityId.ofRepoIdOrNull(orderId, cc.getPP_Order_Node_ID()); if (activityId == null) { return null; } final PPOrderRoutingActivity activity = orderRoutingRepository.getOrderRoutingActivity(activityId); return WorkingTime.builder() .durationPerOneUnit(activity.getDurationPerOneUnit()) .unitsPerCycle(activity.getUnitsPerCycle()) .qty(costCollectorBL.getMovementQty(cc)) .activityTimeUnit(activity.getDurationUnit()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\callout\PP_Cost_Collector.java
1
请完成以下Java代码
public boolean isAllowCredentials() { return allowCredentials; } public void setAllowCredentials(boolean allowCredentials) { this.allowCredentials = allowCredentials; } public Set<String> getAllowedOrigins() { return allowedOrigins == null ? Collections.emptySet() : allowedOrigins; } public void setAllowedOrigins(Set<String> allowedOrigins) { this.allowedOrigins = allowedOrigins; } public Set<String> getAllowedHeaders() { return allowedHeaders == null ? Collections.emptySet() : allowedHeaders; } public void setAllowedHeaders(Set<String> allowedHeaders) { this.allowedHeaders = allowedHeaders; } public Set<String> getExposedHeaders() {
return exposedHeaders == null ? Collections.emptySet() : exposedHeaders; } public void setExposedHeaders(Set<String> exposedHeaders) { this.exposedHeaders = exposedHeaders; } public Set<String> getAllowedMethods() { return allowedMethods == null ? Collections.emptySet() : allowedMethods; } public void setAllowedMethods(Set<String> allowedMethods) { this.allowedMethods = allowedMethods; } } }
repos\flowable-engine-main\modules\flowable-app-rest\src\main\java\org\flowable\rest\app\properties\RestAppProperties.java
1
请完成以下Java代码
public class CashDeposit1 { @XmlElement(name = "NoteDnmtn", required = true) protected ActiveCurrencyAndAmount noteDnmtn; @XmlElement(name = "NbOfNotes", required = true) protected String nbOfNotes; @XmlElement(name = "Amt", required = true) protected ActiveCurrencyAndAmount amt; /** * Gets the value of the noteDnmtn property. * * @return * possible object is * {@link ActiveCurrencyAndAmount } * */ public ActiveCurrencyAndAmount getNoteDnmtn() { return noteDnmtn; } /** * Sets the value of the noteDnmtn property. * * @param value * allowed object is * {@link ActiveCurrencyAndAmount } * */ public void setNoteDnmtn(ActiveCurrencyAndAmount value) { this.noteDnmtn = value; } /** * Gets the value of the nbOfNotes property. * * @return * possible object is * {@link String } * */ public String getNbOfNotes() { return nbOfNotes; } /** * Sets the value of the nbOfNotes property. *
* @param value * allowed object is * {@link String } * */ public void setNbOfNotes(String value) { this.nbOfNotes = value; } /** * Gets the value of the amt property. * * @return * possible object is * {@link ActiveCurrencyAndAmount } * */ public ActiveCurrencyAndAmount getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ActiveCurrencyAndAmount } * */ public void setAmt(ActiveCurrencyAndAmount value) { this.amt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CashDeposit1.java
1
请完成以下Java代码
public boolean isSubMenu() { return m_subMenus != null; } public boolean isAction() { return m_action != null; } public String getName() { return m_name; } public HTMLEditor_MenuAction[] getSubMenus()
{ return m_subMenus; } public String getActionName() { return m_actionName; } public Action getAction() { return m_action; } } // MenuAction
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\HTMLEditor.java
1
请完成以下Java代码
public Mono<MatchResult> matches(ServerWebExchange exchange) { ServerHttpRequest request = exchange.getRequest(); PathContainer path = request.getPath().pathWithinApplication(); if (this.method != null && !this.method.equals(request.getMethod())) { return MatchResult.notMatch().doOnNext((result) -> { if (logger.isDebugEnabled()) { logger.debug("Request '" + request.getMethod() + " " + path + "' doesn't match '" + this.method + " " + this.pattern.getPatternString() + "'"); } }); } PathPattern.PathMatchInfo pathMatchInfo = this.pattern.matchAndExtract(path); if (pathMatchInfo == null) { return MatchResult.notMatch().doOnNext((result) -> { if (logger.isDebugEnabled()) { logger.debug("Request '" + request.getMethod() + " " + path + "' doesn't match '" + this.method + " " + this.pattern.getPatternString() + "'"); }
}); } Map<String, String> pathVariables = pathMatchInfo.getUriVariables(); Map<String, Object> variables = new HashMap<>(pathVariables); if (logger.isDebugEnabled()) { logger .debug("Checking match of request : '" + path + "'; against '" + this.pattern.getPatternString() + "'"); } return MatchResult.match(variables); } @Override public String toString() { return "PathMatcherServerWebExchangeMatcher{" + "pattern='" + this.pattern + '\'' + ", method=" + this.method + '}'; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\util\matcher\PathPatternParserServerWebExchangeMatcher.java
1
请完成以下Java代码
public ExternalTaskQuery createExternalTaskQuery() { return new ExternalTaskQueryImpl(commandExecutor); } @Override public List<String> getTopicNames() { return commandExecutor.execute(new GetTopicNamesCmd(false,false,false)); } @Override public List<String> getTopicNames(boolean withLockedTasks, boolean withUnlockedTasks, boolean withRetriesLeft) { return commandExecutor.execute(new GetTopicNamesCmd(withLockedTasks, withUnlockedTasks, withRetriesLeft)); } public String getExternalTaskErrorDetails(String externalTaskId) { return commandExecutor.execute(new GetExternalTaskErrorDetailsCmd(externalTaskId)); } @Override public void setRetries(String externalTaskId, int retries) { setRetries(externalTaskId, retries, true); } @Override public void setRetries(List<String> externalTaskIds, int retries) { updateRetries() .externalTaskIds(externalTaskIds) .set(retries); }
@Override public Batch setRetriesAsync(List<String> externalTaskIds, ExternalTaskQuery externalTaskQuery, int retries) { return updateRetries() .externalTaskIds(externalTaskIds) .externalTaskQuery(externalTaskQuery) .setAsync(retries); } @Override public UpdateExternalTaskRetriesSelectBuilder updateRetries() { return new UpdateExternalTaskRetriesBuilderImpl(commandExecutor); } @Override public void extendLock(String externalTaskId, String workerId, long lockDuration) { commandExecutor.execute(new ExtendLockOnExternalTaskCmd(externalTaskId, workerId, lockDuration)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskServiceImpl.java
1
请完成以下Java代码
public void setExpanded(final boolean expanded) { final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel(); findPanelCollapsible.setCollapsed(!expanded); } @Override public final void requestFocus() { final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel(); if (findPanelCollapsible.isCollapsed()) { return; } findPanel.requestFocus(); } @Override public final boolean requestFocusInWindow() { final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel(); if (findPanelCollapsible.isCollapsed()) { return false; } return findPanel.requestFocusInWindow(); } /** * @return true if it's expanded and the underlying {@link FindPanel} allows focus. */ @Override public boolean isFocusable() { if (!isExpanded()) { return false; } return findPanel.isFocusable(); } /** * Adds a runnable to be executed when the this panel is collapsed or expanded.
* * @param runnable */ @Override public void runOnExpandedStateChange(final Runnable runnable) { Check.assumeNotNull(runnable, "runnable not null"); final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel(); findPanelCollapsible.addPropertyChangeListener("collapsed", new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { runnable.run(); } }); } private static final class CollapsiblePanel extends JXTaskPane implements IUISubClassIDAware { private static final long serialVersionUID = 1L; public CollapsiblePanel() { super(); } @Override public String getUISubClassID() { return AdempiereTaskPaneUI.UISUBCLASSID_VPanel_FindPanel; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer_Collapsible.java
1
请完成以下Java代码
public void run() { onCollapsedStateChanged(); } }); setExpanded(!builder.isSearchPanelCollapsed()); } protected abstract void init(final FindPanelBuilder builder); /** @return swing component */ public abstract JComponent getComponent(); public abstract boolean isExpanded(); public abstract void setExpanded(final boolean expanded);
public abstract void runOnExpandedStateChange(final Runnable runnable); public abstract boolean isFocusable(); public abstract void requestFocus(); public abstract boolean requestFocusInWindow(); private void onCollapsedStateChanged() { requestFocus(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer.java
1
请完成以下Java代码
private void handleFlowElement(Process process, FlowElement flowElement, List<ValidationError> errors) { if (flowElement instanceof Activity) { Activity activity = (Activity) flowElement; if (activity instanceof SubProcess) { SubProcess subProcess = (SubProcess) activity; for (FlowElement subElement : subProcess.getFlowElements()) { handleFlowElement(process, subElement, errors); } } else { handleValidations(process, activity, errors); } } } protected void handleConstraints(Process process, Activity activity, List<ValidationError> errors) { if (activity.getId() != null && activity.getId().length() > ID_MAX_LENGTH) { Map<String, String> params = new HashMap<>(); params.put("maxLength", String.valueOf(ID_MAX_LENGTH)); addError(errors, Problems.FLOW_ELEMENT_ID_TOO_LONG, process, activity, params); } } protected void handleMultiInstanceLoopCharacteristics( Process process, Activity activity, List<ValidationError> errors ) { MultiInstanceLoopCharacteristics multiInstanceLoopCharacteristics = activity.getLoopCharacteristics(); if (multiInstanceLoopCharacteristics != null) { if ( StringUtils.isEmpty(multiInstanceLoopCharacteristics.getLoopCardinality()) && StringUtils.isEmpty(multiInstanceLoopCharacteristics.getInputDataItem()) ) { addError(errors, Problems.MULTI_INSTANCE_MISSING_COLLECTION, process, activity); }
} } protected void handleDataAssociations(Process process, Activity activity, List<ValidationError> errors) { if (activity.getDataInputAssociations() != null) { for (DataAssociation dataAssociation : activity.getDataInputAssociations()) { if (StringUtils.isEmpty(dataAssociation.getTargetRef())) { addError(errors, Problems.DATA_ASSOCIATION_MISSING_TARGETREF, process, activity); } } } if (activity.getDataOutputAssociations() != null) { for (DataAssociation dataAssociation : activity.getDataOutputAssociations()) { if (StringUtils.isEmpty(dataAssociation.getTargetRef())) { addError(errors, Problems.DATA_ASSOCIATION_MISSING_TARGETREF, process, activity); } } } } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\impl\FlowElementValidator.java
1
请完成以下Java代码
private String[] split(String to_split) { if ( to_split == null || to_split.length() == 0 ) { String[] array = new String[0]; return array; } StringBuffer sb = new StringBuffer(to_split.length()+50); StringCharacterIterator sci = new StringCharacterIterator(to_split); int length = 0; for (char c = sci.first(); c != CharacterIterator.DONE; c = sci.next()) { if(String.valueOf(c).equals(" ")) length++; else if(sci.getEndIndex()-1 == sci.getIndex()) length++; } String[] array = new String[length]; length = 0; String tmp = new String(); for (char c = sci.first(); c!= CharacterIterator.DONE; c = sci.next()) { if(String.valueOf(c).equals(" ")) { array[length] = tmp;
tmp = new String(); length++; } else if(sci.getEndIndex()-1 == sci.getIndex()) { tmp = tmp+String.valueOf(sci.last()); array[length] = tmp; tmp = new String(); length++; } else tmp += String.valueOf(c); } return(array); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\filter\StringFilter.java
1
请完成以下Java代码
private static Class<?> nullSafeType(Object obj) { return obj != null ? obj.getClass() : null; } private static String nullSafeTypeName(Class<?> type) { return type != null ? type.getName() : null; } public static String nullSafeTypeName(Object obj) { return nullSafeTypeName(nullSafeType(obj)); } /** * The {@link AssertThat} {@link FunctionalInterface interface} defines a contract for making assertion about * a given {@link Object} used as the {@link #getSubject() subject} of the assert statement. * * @param <T> {@link Class type} of the {@link Object} that is the {@link #getSubject() subject} of the assertion. */ @FunctionalInterface public interface AssertThat<T> { /** * Returns the {@link Object} used as the subject of this assertion. * * @return the {@link Object} used as the subject of this assertion. * @see java.lang.Object */ T getSubject(); /** * Asserts the {@link #getSubject() subject} is not {@literal null}. */ default void isNotNull() { assertIsNotNull(getSubject()); }
/** * Asserts the {@link #getSubject()} is an instance of {@link GemFireCacheImpl}. */ default void isInstanceOfGemFireCacheImpl() { assertIsInstanceOf(getSubject(), GemFireCacheImpl.class); } /** * Asserts the {@link #getSubject()} is an instance of {@link InternalDistributedSystem}. */ default void isInstanceOfInternalDistributedSystem() { assertIsInstanceOf(getSubject(), InternalDistributedSystem.class); } /** * Asserts the {@link #getSubject()} is not an instance of {@link AbstractRegion}. */ default void isNotInstanceOfAbstractRegion() { assertIsNotInstanceOf(getSubject(), AbstractRegion.class); } /** * Asserts the {@link #getSubject()} is not an instance of {@link GemFireCacheImpl}. */ default void isNotInstanceOfGemFireCacheImpl() { assertIsNotInstanceOf(getSubject(), GemFireCacheImpl.class); } /** * Asserts the {@link #getSubject()} is not an instance of {@link InternalDistributedSystem}. */ default void isNotInstanceOfInternalDistributedSystem() { assertIsNotInstanceOf(getSubject(), InternalDistributedSystem.class); } } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\util\GeodeAssertions.java
1
请完成以下Java代码
protected void prepare() { // nothing to do } /** * Recalculates SeqNo in AD_User_SortPref_Line in 10-steps for the current AD_User_SortPref_Hdr, keeping the order they already had */ @Override protected String doIt() throws Exception { // // Services final ITrxManager trxManager = Services.get(ITrxManager.class); final IUserSortPrefDAO userSortPrefDAO = Services.get(IUserSortPrefDAO.class); final Properties ctx = getCtx(); trxManager.runInNewTrx(new TrxRunnable() { @Override public void run(final String localTrxName) throws Exception {
int seqNumber = 10; final ProcessInfo processInfo = getProcessInfo(); final int recordId = processInfo.getRecord_ID(); final I_AD_User_SortPref_Hdr hdr = InterfaceWrapperHelper.create(ctx, recordId, I_AD_User_SortPref_Hdr.class, localTrxName); final Iterator<I_AD_User_SortPref_Line> sortPreferenceLines = userSortPrefDAO.retrieveSortPreferenceLines(hdr).iterator(); while (sortPreferenceLines.hasNext()) { final I_AD_User_SortPref_Line sortPreferenceLine = sortPreferenceLines.next(); sortPreferenceLine.setSeqNo(seqNumber); InterfaceWrapperHelper.save(sortPreferenceLine); seqNumber = seqNumber + 10; } } }); return "@SeqNoRecalculated@"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\process\AD_User_SortPref_Hdr_RecalculateSeqNo.java
1
请完成以下Java代码
public void accept(ServerWebExchange exchange, CachedResponse cachedResponse) { ServerHttpResponse response = exchange.getResponse(); long calculatedMaxAgeInSeconds = calculateMaxAgeInSeconds(exchange.getRequest(), cachedResponse, configuredTimeToLive); rewriteCacheControlMaxAge(response.getHeaders(), calculatedMaxAgeInSeconds); } private long calculateMaxAgeInSeconds(ServerHttpRequest request, CachedResponse cachedResponse, Duration configuredTimeToLive) { boolean noCache = LocalResponseCacheUtils.isNoCacheRequest(request); long maxAge; if (noCache && ignoreNoCacheUpdate || configuredTimeToLive.getSeconds() < 0) { maxAge = 0; } else { long calculatedMaxAge = configuredTimeToLive.minus(getElapsedTimeInSeconds(cachedResponse)).getSeconds(); maxAge = Math.max(0, calculatedMaxAge); } return maxAge; } private Duration getElapsedTimeInSeconds(CachedResponse cachedResponse) { return Duration.ofMillis(clock.millis() - cachedResponse.timestamp().getTime()); } private static void rewriteCacheControlMaxAge(HttpHeaders headers, long seconds) { boolean isMaxAgePresent = headers.getCacheControl() != null && headers.getCacheControl().contains(MAX_AGE_PREFIX); List<String> newCacheControlDirectives = new ArrayList<>(); if (isMaxAgePresent) { List<String> cacheControlHeaders = headers.get(HttpHeaders.CACHE_CONTROL); cacheControlHeaders = cacheControlHeaders == null ? Collections.emptyList() : cacheControlHeaders; for (String value : cacheControlHeaders) { if (value.contains(MAX_AGE_PREFIX)) { if (seconds == -1) { List<String> removedMaxAgeList = Arrays.stream(value.split(",")) .filter(i -> !i.trim().startsWith(MAX_AGE_PREFIX)) .collect(Collectors.toList());
value = String.join(",", removedMaxAgeList); } else { value = value.replaceFirst("\\bmax-age=\\d+\\b", MAX_AGE_PREFIX + seconds); } } newCacheControlDirectives.add(value); } } else { List<String> cacheControlHeaders = headers.get(HttpHeaders.CACHE_CONTROL); newCacheControlDirectives = cacheControlHeaders == null ? new ArrayList<>() : new ArrayList<>(cacheControlHeaders); newCacheControlDirectives.add("max-age=" + seconds); } headers.remove(HttpHeaders.CACHE_CONTROL); headers.addAll(HttpHeaders.CACHE_CONTROL, newCacheControlDirectives); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\postprocessor\SetMaxAgeHeaderAfterCacheExchangeMutator.java
1
请完成以下Java代码
protected boolean beforeSave(final boolean newRecord) { final IInventoryBL inventoryBL = Services.get(IInventoryBL.class); if (newRecord && Services.get(IInventoryBL.class).isComplete(getM_Inventory())) { throw new AdempiereException("@ParentComplete@ @M_Inventory_ID@"); } if (newRecord && is_ManualUserAction()) { // Product requires ASI if (getM_AttributeSetInstance_ID() <= 0) { final ProductId productId = ProductId.ofRepoId(getM_Product_ID()); if(Services.get(IProductBL.class).isASIMandatory(productId, isSOTrx())) { throw new FillMandatoryException(COLUMNNAME_M_AttributeSetInstance_ID); } } // No ASI } // new or manual // Set Line No if (getLine() <= 0) { final String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_InventoryLine WHERE M_Inventory_ID=?"; final int lineNo = DB.getSQLValueEx(get_TrxName(), sql, getM_Inventory_ID()); setLine(lineNo); } // Enforce Qty UOM if (newRecord || is_ValueChanged(COLUMNNAME_QtyCount)) { setQtyCount(getQtyCount()); } if (newRecord || is_ValueChanged(COLUMNNAME_QtyInternalUse)) { setQtyInternalUse(getQtyInternalUse()); } // InternalUse Inventory if (isInternalUseInventory()) { if (!INVENTORYTYPE_ChargeAccount.equals(getInventoryType())) { setInventoryType(INVENTORYTYPE_ChargeAccount); } // if (getC_Charge_ID() <= 0) { inventoryBL.setDefaultInternalChargeId(this); } } else if (INVENTORYTYPE_ChargeAccount.equals(getInventoryType())) { if (getC_Charge_ID() <= 0)
{ throw new FillMandatoryException(COLUMNNAME_C_Charge_ID); } } else if (getC_Charge_ID() > 0) { setC_Charge_ID(0); } // Set AD_Org to parent if not charge if (getC_Charge_ID() <= 0) { setAD_Org_ID(getM_Inventory().getAD_Org_ID()); } return true; } @Deprecated private boolean isInternalUseInventory() { return Services.get(IInventoryBL.class).isInternalUseInventory(this); } /** * @return true if is an outgoing transaction */ @Deprecated private boolean isSOTrx() { return Services.get(IInventoryBL.class).isSOTrx(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInventoryLine.java
1
请完成以下Java代码
public class FormPropertyImpl implements FormProperty { protected String id; protected String name; protected FormType type; protected boolean isRequired; protected boolean isReadable; protected boolean isWritable; protected String value; public FormPropertyImpl(FormPropertyHandler formPropertyHandler) { this.id = formPropertyHandler.getId(); this.name = formPropertyHandler.getName(); this.type = formPropertyHandler.getType(); this.isRequired = formPropertyHandler.isRequired(); this.isReadable = formPropertyHandler.isReadable(); this.isWritable = formPropertyHandler.isWritable(); } public String getId() { return id; } public String getName() { return name; } public FormType getType() { return type; } public String getValue() { return value; }
public boolean isRequired() { return isRequired; } public boolean isReadable() { return isReadable; } public void setValue(String value) { this.value = value; } public boolean isWritable() { return isWritable; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\FormPropertyImpl.java
1
请完成以下Java代码
public String getOperateMan() { return operateMan; } public void setOperateMan(String operateMan) { this.operateMan = operateMan; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getOrderStatus() { return orderStatus; } public void setOrderStatus(Integer orderStatus) { this.orderStatus = orderStatus; } public String getNote() {
return note; } public void setNote(String note) { this.note = note; } @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(", orderId=").append(orderId); sb.append(", operateMan=").append(operateMan); sb.append(", createTime=").append(createTime); sb.append(", orderStatus=").append(orderStatus); sb.append(", note=").append(note); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderOperateHistory.java
1
请完成以下Java代码
protected TreeBuilder createTreeBuilder(Properties properties, Builder.Feature... features) { Class<?> clazz = load(TreeBuilder.class, properties); if (clazz == null) { return new Builder(features); } try { if (Builder.class.isAssignableFrom(clazz)) { Constructor<?> constructor = clazz.getConstructor(Builder.Feature[].class); if (constructor == null) { if (features == null || features.length == 0) { return TreeBuilder.class.cast(clazz.getDeclaredConstructor().newInstance()); } else { throw new ELException("Builder " + clazz + " is missing constructor (can't pass features)"); } } else { return TreeBuilder.class.cast(constructor.newInstance((Object) features)); } } else { return TreeBuilder.class.cast(clazz.getDeclaredConstructor().newInstance()); } } catch (Exception e) { throw new ELException("TreeBuilder " + clazz + " could not be instantiated", e); } } private Class<?> load(Class<?> clazz, Properties properties) { if (properties != null) { String className = properties.getProperty(clazz.getName()); if (className != null) { ClassLoader loader; try { loader = Thread.currentThread().getContextClassLoader(); } catch (Exception e) { throw new ELException("Could not get context class loader", e); } try { return loader == null ? Class.forName(className) : loader.loadClass(className); } catch (ClassNotFoundException e) { throw new ELException("Class " + className + " not found", e); } catch (Exception e) { throw new ELException("Class " + className + " could not be instantiated", e); } } } return null; } @Override public Object coerceToType(Object obj, Class<?> targetType) {
return converter.convert(obj, targetType); } @Override public final ObjectValueExpression createValueExpression(Object instance, Class<?> expectedType) { return new ObjectValueExpression(converter, instance, expectedType); } @Override public final TreeValueExpression createValueExpression(ELContext context, String expression, Class<?> expectedType) { return new TreeValueExpression(store, context.getFunctionMapper(), context.getVariableMapper(), converter, expression, expectedType); } @Override public final TreeMethodExpression createMethodExpression(ELContext context, String expression, Class<?> expectedReturnType, Class<?>[] expectedParamTypes) { return new TreeMethodExpression(store, context.getFunctionMapper(), context.getVariableMapper(), converter, expression, expectedReturnType, expectedParamTypes); } }
repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\ExpressionFactoryImpl.java
1
请在Spring Boot框架中完成以下Java代码
protected final Map<Class<?>, List<Annotation>> getAnnotations(AnnotationMetadata metadata) { MultiValueMap<Class<?>, Annotation> annotations = new LinkedMultiValueMap<>(); Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), getBeanClassLoader()); collectAnnotations(source, annotations, new HashSet<>()); return Collections.unmodifiableMap(annotations); } private void collectAnnotations(@Nullable Class<?> source, MultiValueMap<Class<?>, Annotation> annotations, HashSet<Class<?>> seen) { if (source != null && seen.add(source)) { for (Annotation annotation : source.getDeclaredAnnotations()) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { if (ANNOTATION_NAMES.contains(annotation.annotationType().getName())) { annotations.add(source, annotation); } collectAnnotations(annotation.annotationType(), annotations, seen); }
} collectAnnotations(source.getSuperclass(), annotations, seen); } } @Override public int getOrder() { return super.getOrder() - 1; } @Override protected void handleInvalidExcludes(List<String> invalidExcludes) { // Ignore for test } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ImportAutoConfigurationImportSelector.java
2
请完成以下Java代码
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { List<String> keysToDelete = keys.stream() .map(keyPattern -> TbNodeUtils.processPattern(keyPattern, msg)) .distinct() .filter(StringUtils::isNotBlank) .collect(Collectors.toList()); if (keysToDelete.isEmpty()) { ctx.tellSuccess(msg); } else { AttributeScope scope = getScope(msg.getMetaData().getValue(SCOPE)); ctx.getTelemetryService().deleteAttributes(AttributesDeleteRequest.builder() .tenantId(ctx.getTenantId()) .entityId(msg.getOriginator()) .scope(scope) .keys(keysToDelete) .notifyDevice(checkNotifyDevice(msg.getMetaData().getValue(NOTIFY_DEVICE_METADATA_KEY), scope)) .previousCalculatedFieldIds(msg.getPreviousCalculatedFieldIds()) .tbMsgId(msg.getId()) .tbMsgType(msg.getInternalType()) .callback(config.isSendAttributesDeletedNotification() ? new AttributesDeleteNodeCallback(ctx, msg, scope.name(), keysToDelete) :
new TelemetryNodeCallback(ctx, msg)) .build()); } } private AttributeScope getScope(String mdScopeValue) { if (StringUtils.isNotEmpty(mdScopeValue)) { return AttributeScope.valueOf(mdScopeValue); } return AttributeScope.valueOf(config.getScope()); } private boolean checkNotifyDevice(String notifyDeviceMdValue, AttributeScope scope) { return (AttributeScope.SHARED_SCOPE == scope) && (config.isNotifyDevice() || Boolean.parseBoolean(notifyDeviceMdValue)); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\telemetry\TbMsgDeleteAttributesNode.java
1
请完成以下Java代码
public static FlowableVersion getPreviousVersion(String version) { int currentVersion = findMatchingVersionIndex(version); if (currentVersion > 0) { return FLOWABLE_VERSIONS.get(currentVersion - 1); } return null; } public static int getFlowableVersionIndexForDbVersion(String dbVersion) { int matchingVersionIndex; if ("fox".equalsIgnoreCase(dbVersion)) { dbVersion = "5.13"; } // Determine index in the sequence of Flowable releases matchingVersionIndex = findMatchingVersionIndex(dbVersion); // If no match has been found, but the version starts with '5.x', // we assume it's the last version (see comment in the VERSIONS list) if (matchingVersionIndex < 0 && dbVersion != null && dbVersion.startsWith("5.")) { matchingVersionIndex = findMatchingVersionIndex(FlowableVersions.LAST_V5_VERSION); } // Exception when no match was found: unknown/unsupported version if (matchingVersionIndex < 0) { throw new FlowableException("Could not update Flowable database schema: unknown version from database: '" + dbVersion + "'"); } return matchingVersionIndex; } public static boolean hasCamMigrationVersion(String version) { int index = findMatchingCamMigrationIndex(version); if (index >= 0) {
return true; } else { return false; } } protected static int findMatchingCamMigrationIndex(String dbVersion) { int index = 0; int matchingVersionIndex = -1; while (matchingVersionIndex < 0 && index < FlowableVersions.CAM_MIGRATION_VERSIONS.size()) { if (FlowableVersions.CAM_MIGRATION_VERSIONS.get(index).matches(dbVersion)) { matchingVersionIndex = index; } else { index++; } } return matchingVersionIndex; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\FlowableVersions.java
1
请在Spring Boot框架中完成以下Java代码
public class KPIField { @NonNull String fieldName; boolean groupBy; @NonNull ITranslatableString caption; @NonNull ITranslatableString offsetCaption; @NonNull ITranslatableString description; @Nullable ITranslatableString unit; @NonNull KPIFieldValueType valueType; @Nullable Integer numberPrecision; @Nullable String color; @Builder private KPIField( @NonNull final String fieldName, final boolean groupBy, @NonNull final ITranslatableString caption, @Nullable final ITranslatableString offsetCaption, @Nullable final ITranslatableString description, @Nullable final ITranslatableString unit, @NonNull final KPIFieldValueType valueType, @Nullable final Integer numberPrecision, @Nullable final String color) { this.fieldName = fieldName; this.groupBy = groupBy; this.caption = caption; this.offsetCaption = offsetCaption != null ? offsetCaption : TranslatableStrings.empty(); this.description = description != null ? description : TranslatableStrings.empty(); this.unit = !TranslatableStrings.isBlank(unit) ? unit : null; this.valueType = valueType; this.numberPrecision = numberPrecision; this.color = color; } @Override
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("fieldName", fieldName) .add("groupBy", groupBy) .add("valueType", valueType) .toString(); } public String getOffsetFieldName() { return fieldName + "_offset"; } public String getCaption(final String adLanguage) { return caption.translate(adLanguage); } public String getOffsetCaption(final String adLanguage) { return offsetCaption.translate(adLanguage); } public String getDescription(final String adLanguage) { return description.translate(adLanguage); } public Optional<String> getUnit(final String adLanguage) { return unit != null ? StringUtils.trimBlankToOptional(unit.translate(adLanguage)) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\KPIField.java
2
请完成以下Java代码
public final class AuthorizationCodeReactiveOAuth2AuthorizedClientProvider implements ReactiveOAuth2AuthorizedClientProvider { /** * Attempt to authorize the {@link OAuth2AuthorizationContext#getClientRegistration() * client} in the provided {@code context}. Returns an empty {@code Mono} if * authorization is not supported, e.g. the client's * {@link ClientRegistration#getAuthorizationGrantType() authorization grant type} is * not {@link AuthorizationGrantType#AUTHORIZATION_CODE authorization_code} OR the * client is already authorized. * @param context the context that holds authorization-specific state for the client * @return an empty {@code Mono} if authorization is not supported or the client is * already authorized * @throws ClientAuthorizationRequiredException in order to trigger authorization in * which the {@link OAuth2AuthorizationRequestRedirectWebFilter} will catch and * initiate the authorization request
*/ @Override public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); if (AuthorizationGrantType.AUTHORIZATION_CODE.equals( context.getClientRegistration().getAuthorizationGrantType()) && context.getAuthorizedClient() == null) { // ClientAuthorizationRequiredException is caught by // OAuth2AuthorizationRequestRedirectWebFilter which initiates authorization return Mono.error(() -> new ClientAuthorizationRequiredException( context.getClientRegistration().getRegistrationId())); } return Mono.empty(); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\AuthorizationCodeReactiveOAuth2AuthorizedClientProvider.java
1
请完成以下Java代码
public class TimerCatchIntermediateEventJobHandler extends TimerEventHandler implements JobHandler { private static final Logger LOGGER = LoggerFactory.getLogger(TimerCatchIntermediateEventJobHandler.class); public static final String TYPE = "timer-intermediate-transition"; @Override public String getType() { return TYPE; } @Override public void execute(Job job, String configuration, ExecutionEntity execution, CommandContext commandContext) { String nestedActivityId = TimerEventHandler.getActivityIdFromConfiguration(configuration); ActivityImpl intermediateEventActivity = execution.getProcessDefinition().findActivity(nestedActivityId); if (intermediateEventActivity == null) { throw new ActivitiException("Error while firing timer: intermediate event activity " + nestedActivityId + " not found"); } try { if (commandContext.getEventDispatcher().isEnabled()) { commandContext.getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.TIMER_FIRED, job), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
} if (!execution.getActivity().getId().equals(intermediateEventActivity.getId())) { execution.setActivity(intermediateEventActivity); } execution.signal(null, null); } catch (RuntimeException e) { LogMDC.putMDCExecution(execution); LOGGER.error("exception during timer execution", e); LogMDC.clear(); throw e; } catch (Exception e) { LogMDC.putMDCExecution(execution); LOGGER.error("exception during timer execution", e); LogMDC.clear(); throw new ActivitiException("exception during timer execution: " + e.getMessage(), e); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerCatchIntermediateEventJobHandler.java
1
请完成以下Java代码
static HttpHeaders filterRequest(@Nullable List<HttpHeadersFilter> filters, ServerWebExchange exchange) { HttpHeaders headers = exchange.getRequest().getHeaders(); return filter(filters, headers, exchange, Type.REQUEST); } static HttpHeaders filter(@Nullable List<HttpHeadersFilter> filters, HttpHeaders input, ServerWebExchange exchange, Type type) { if (filters != null) { HttpHeaders filtered = input; for (int i = 0; i < filters.size(); i++) { HttpHeadersFilter filter = filters.get(i); if (filter.supports(type)) { filtered = filter.filter(filtered, exchange); } } return filtered; } return input; } /** * Filters a set of Http Headers. * @param input Http Headers * @param exchange a {@link ServerWebExchange} that should be filtered
* @return filtered Http Headers */ HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange); default boolean supports(Type type) { return type.equals(Type.REQUEST); } enum Type { /** * Filter for request headers. */ REQUEST, /** * Filter for response headers. */ RESPONSE } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\HttpHeadersFilter.java
1
请完成以下Java代码
public void setM_DiscountSchema_ID (final int M_DiscountSchema_ID) { if (M_DiscountSchema_ID < 1) set_Value (COLUMNNAME_M_DiscountSchema_ID, null); else set_Value (COLUMNNAME_M_DiscountSchema_ID, M_DiscountSchema_ID); } @Override public int getM_DiscountSchema_ID() { return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID); } @Override public void setM_PriceList_ID (final int M_PriceList_ID) { if (M_PriceList_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, M_PriceList_ID); } @Override public int getM_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_M_PriceList_ID); } @Override public void setM_Pricelist_Version_Base_ID (final int M_Pricelist_Version_Base_ID) { if (M_Pricelist_Version_Base_ID < 1) set_Value (COLUMNNAME_M_Pricelist_Version_Base_ID, null); else set_Value (COLUMNNAME_M_Pricelist_Version_Base_ID, M_Pricelist_Version_Base_ID); } @Override public int getM_Pricelist_Version_Base_ID() { return get_ValueAsInt(COLUMNNAME_M_Pricelist_Version_Base_ID); } @Override public void setM_PriceList_Version_ID (final int M_PriceList_Version_ID) { if (M_PriceList_Version_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, M_PriceList_Version_ID); } @Override public int getM_PriceList_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_PriceList_Version_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); } @Override
public void setProcCreate (final @Nullable java.lang.String ProcCreate) { set_Value (COLUMNNAME_ProcCreate, ProcCreate); } @Override public java.lang.String getProcCreate() { return get_ValueAsString(COLUMNNAME_ProcCreate); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PriceList_Version.java
1
请在Spring Boot框架中完成以下Java代码
public class SenderType { @XmlElement(required = true) protected String id; protected String codeQualifier; protected String internalId; protected String internalSubId; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the codeQualifier property. * * @return * possible object is * {@link String } * */ public String getCodeQualifier() { return codeQualifier; } /** * Sets the value of the codeQualifier property. * * @param value * allowed object is * {@link String } * */ public void setCodeQualifier(String value) { this.codeQualifier = value; } /** * Gets the value of the internalId property. * * @return * possible object is * {@link String } * */ public String getInternalId() { return internalId; }
/** * Sets the value of the internalId property. * * @param value * allowed object is * {@link String } * */ public void setInternalId(String value) { this.internalId = value; } /** * Gets the value of the internalSubId property. * * @return * possible object is * {@link String } * */ public String getInternalSubId() { return internalSubId; } /** * Sets the value of the internalSubId property. * * @param value * allowed object is * {@link String } * */ public void setInternalSubId(String value) { this.internalSubId = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\SenderType.java
2
请在Spring Boot框架中完成以下Java代码
public void pullFromAppServer( @RequestHeader("apiKey") final String apiKey) { assertValidApiKey(apiKey); senderToMetasfreshService.requestFromMetasfreshAllMasterdataAsync(); } /** * @param dateFromStr inclusive (>=). Value e.g. {@link 2025-02-11}. * @param dateToStr also inclusive (<=). Value e.g. {@link 2025-02-11}. */ @GetMapping("/pushReports") public void pushReports( @RequestHeader("apiKey") final String apiKey, @RequestParam(name = "bpartnerId", required = false, defaultValue = "0") final long bpartnerId, @RequestParam(name = "productId", required = false, defaultValue = "0") final long productId, @RequestParam("dateFrom") final String dateFromStr, @RequestParam("dateTo") final String dateToStr) { assertValidApiKey(apiKey); final LocalDate dateFrom = LocalDate.parse(dateFromStr); final LocalDate dateTo = LocalDate.parse(dateToStr); pushDailyReports(bpartnerId, productId, dateFrom, dateTo); pushWeeklyReports(bpartnerId, productId, dateFrom, dateTo); } private void pushDailyReports( final long bpartnerId, final long productId, final LocalDate dateFrom, final LocalDate dateTo) { final List<ProductSupply> productSupplies = productSuppliesService.getProductSupplies( bpartnerId, productId, dateFrom, dateTo); senderToMetasfreshService.pushDailyReportsAsync(productSupplies); } private void pushWeeklyReports( final long bpartnerId, final long productId, final LocalDate dateFrom,
final LocalDate dateTo) { final List<WeekSupply> records = productSuppliesService.getWeeklySupplies( bpartnerId, productId, dateFrom, dateTo); senderToMetasfreshService.pushWeeklyReportsAsync(records); } @GetMapping("/pushActiveRfQs") public void pushActiveRfQs( @RequestHeader("apiKey") final String apiKey, @RequestParam(name = "bpartnerId", required = false, defaultValue = "0") final long bpartnerId) { assertValidApiKey(apiKey); final BPartner bpartner = bpartnerId > 0 ? bpartnersRepository.getOne(bpartnerId) : null; final List<Rfq> rfqs = rfqService.getActiveRfqs(bpartner); senderToMetasfreshService.pushRfqsAsync(rfqs); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\MetasfreshSyncRestController.java
2
请完成以下Spring Boot application配置
server.servlet.contextPath=/ spring.h2.console.enabled=true logging.level.org.hibernate.SQL=info spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=create spr
ing.sql.init.mode=always spring.jpa.defer-datasource-initialization=true
repos\tutorials-master\spring-web-modules\spring-rest-angular\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public ExtendedQuantityType getAdditionalQuantitiy() { return additionalQuantitiy; } /** * Sets the value of the additionalQuantitiy property. * * @param value * allowed object is * {@link ExtendedQuantityType } * */ public void setAdditionalQuantitiy(ExtendedQuantityType value) { this.additionalQuantitiy = value; } /** * DEPRICATED - please Document/Details/ItemList/ListLineItem/ListLineItemExtension/ListLineItemExtension/AdditionalBusinessPartner instead Gets the value of the additionalBusinessPartner property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the additionalBusinessPartner property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdditionalBusinessPartner().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BusinessEntityType } * *
*/ public List<BusinessEntityType> getAdditionalBusinessPartner() { if (additionalBusinessPartner == null) { additionalBusinessPartner = new ArrayList<BusinessEntityType>(); } return this.additionalBusinessPartner; } /** * Other references if no dedicated field is available.Gets the value of the additionalReference property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the additionalReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdditionalReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType } * * */ public List<ReferenceType> getAdditionalReference() { if (additionalReference == null) { additionalReference = new ArrayList<ReferenceType>(); } return this.additionalReference; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\SLSRPTListLineExtensionType.java
2
请在Spring Boot框架中完成以下Java代码
private boolean isPdxReadSerializedEnabled(@NonNull Environment environment) { return Optional.ofNullable(environment) .filter(env -> env.getProperty(PDX_READ_SERIALIZED_PROPERTY, Boolean.class, false)) .isPresent(); } } private static final boolean DEFAULT_EXPORT_ENABLED = false; private static final Predicate<Environment> disableGemFireShutdownHookPredicate = environment -> Optional.ofNullable(environment) .filter(env -> env.getProperty(CacheDataImporterExporterReference.EXPORT_ENABLED_PROPERTY_NAME, Boolean.class, DEFAULT_EXPORT_ENABLED)) .isPresent(); static abstract class AbstractDisableGemFireShutdownHookSupport { boolean shouldDisableGemFireShutdownHook(@Nullable Environment environment) { return disableGemFireShutdownHookPredicate.test(environment); } /** * If we do not disable Apache Geode's {@link org.apache.geode.distributed.DistributedSystem} JRE/JVM runtime * shutdown hook then the {@link org.apache.geode.cache.Region} is prematurely closed by the JRE/JVM shutdown hook * before Spring's {@link org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor}s can do * their work of exporting data from the {@link org.apache.geode.cache.Region} as JSON. */ void disableGemFireShutdownHook(@Nullable Environment environment) {
System.setProperty(GEMFIRE_DISABLE_SHUTDOWN_HOOK, Boolean.TRUE.toString()); } } static abstract class CacheDataImporterExporterReference extends AbstractCacheDataImporterExporter { static final String EXPORT_ENABLED_PROPERTY_NAME = AbstractCacheDataImporterExporter.CACHE_DATA_EXPORT_ENABLED_PROPERTY_NAME; } static class DisableGemFireShutdownHookCondition extends AbstractDisableGemFireShutdownHookSupport implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return shouldDisableGemFireShutdownHook(context.getEnvironment()); } } public static class DisableGemFireShutdownHookEnvironmentPostProcessor extends AbstractDisableGemFireShutdownHookSupport implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (shouldDisableGemFireShutdownHook(environment)) { disableGemFireShutdownHook(environment); } } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\DataImportExportAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
protected <T> T checkNotNull(Optional<T> reference) throws ThingsboardException { return checkNotNull(reference, "Requested item wasn't found!"); } protected <T> T checkNotNull(Optional<T> reference, String notFoundMessage) throws ThingsboardException { if (reference.isPresent()) { return reference.get(); } else { throw new ThingsboardException(notFoundMessage, ThingsboardErrorCode.ITEM_NOT_FOUND); } } protected <I extends EntityId> I emptyId(EntityType entityType) { return (I) EntityIdFactory.getByTypeAndUuid(entityType, ModelConstants.NULL_UUID); } protected ListenableFuture<UUID> autoCommit(User user, EntityId entityId) {
if (vcService != null) { return vcService.autoCommit(user, entityId); } else { // We do not support auto-commit for rule engine return Futures.immediateFailedFuture(new RuntimeException("Operation not supported!")); } } protected ListenableFuture<UUID> autoCommit(User user, EntityType entityType, List<UUID> entityIds) { if (vcService != null) { return vcService.autoCommit(user, entityType, entityIds); } else { // We do not support auto-commit for rule engine return Futures.immediateFailedFuture(new RuntimeException("Operation not supported!")); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\AbstractTbEntityService.java
2
请完成以下Java代码
private void updateWindowFromElement(final I_AD_Window window) { // do not copy translations from element to window if (!IElementTranslationBL.DYNATTR_AD_Window_UpdateTranslations.getValue(window, true)) { return; } final I_AD_Element windowElement = adElementDAO.getById(window.getAD_Element_ID()); if (windowElement == null) { // nothing to do. It was not yet set return; } window.setName(windowElement.getName()); window.setDescription(windowElement.getDescription()); window.setHelp(windowElement.getHelp()); } private void updateTranslationsForElement(final I_AD_Window window) { final AdElementId windowElementId = AdElementId.ofRepoIdOrNull(window.getAD_Element_ID()); if (windowElementId == null) { // nothing to do. It was not yet set return; } elementTranslationBL.updateWindowTranslationsFromElement(windowElementId);
} private void recreateElementLinkForWindow(final I_AD_Window window) { final AdWindowId adWindowId = AdWindowId.ofRepoIdOrNull(window.getAD_Window_ID()); if (adWindowId != null) { final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class); elementLinksService.recreateADElementLinkForWindowId(adWindowId); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void onBeforeWindowDelete(final I_AD_Window window) { final AdWindowId adWindowId = AdWindowId.ofRepoId(window.getAD_Window_ID()); final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class); elementLinksService.deleteExistingADElementLinkForWindowId(adWindowId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\model\interceptor\AD_Window.java
1
请完成以下Java代码
protected static Stream<HUEditorRow> retrieveEligibleHUEditorRows(@NonNull final Stream<HUEditorRow> inputStream) { final SourceHUsService sourceHuService = SourceHUsService.get(); return inputStream .filter(HUEditorRow::isHUStatusActive) .filter(huRow -> !sourceHuService.isHuOrAnyParentSourceHu(huRow.getHuId())); } protected Optional<PPOrderLinesView> getPPOrderView() { final ViewId parentViewId = getView().getParentViewId(); if (parentViewId == null) { return Optional.empty(); }
final PPOrderLinesView ppOrderView = getViewsRepo().getView(parentViewId, PPOrderLinesView.class); return Optional.of(ppOrderView); } @Nullable protected PPOrderBOMLineId getSelectedOrderBOMLineId() { final DocumentId documentId = getView().getParentRowId(); if (documentId == null) { return null; } return PPOrderLineRowId.fromDocumentId(documentId) .getPPOrderBOMLineIdIfApplies() .orElse(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_HUEditor_ProcessBase.java
1
请完成以下Java代码
private static JCTree.JCIf createCheck(VariableTree parameter, Context context) { TreeMaker factory = TreeMaker.instance(context); Names symbolsTable = Names.instance(context); return factory.at(((JCTree) parameter).pos) .If(factory.Parens(createIfCondition(factory, symbolsTable, parameter)), createIfBlock(factory, symbolsTable, parameter), null); } private static JCTree.JCBinary createIfCondition(TreeMaker factory, Names symbolsTable, VariableTree parameter) { Name parameterId = symbolsTable.fromString(parameter.getName().toString()); return factory.Binary(JCTree.Tag.LE, factory.Ident(parameterId), factory.Literal(TypeTag.INT, 0)); } private static JCTree.JCBlock createIfBlock(TreeMaker factory, Names symbolsTable, VariableTree parameter) { String parameterName = parameter.getName().toString();
Name parameterId = symbolsTable.fromString(parameterName); String errorMessagePrefix = String.format("Argument '%s' of type %s is marked by @%s but got '", parameterName, parameter.getType(), Positive.class.getSimpleName()); String errorMessageSuffix = "' for it"; return factory.Block(0, com.sun.tools.javac.util.List.of( factory.Throw( factory.NewClass(null, nil(), factory.Ident(symbolsTable.fromString(IllegalArgumentException.class.getSimpleName())), com.sun.tools.javac.util.List.of(factory.Binary(JCTree.Tag.PLUS, factory.Binary(JCTree.Tag.PLUS, factory.Literal(TypeTag.CLASS, errorMessagePrefix), factory.Ident(parameterId)), factory.Literal(TypeTag.CLASS, errorMessageSuffix))), null)))); } }
repos\tutorials-master\core-java-modules\core-java-sun\src\main\java\com\baeldung\javac\SampleJavacPlugin.java
1
请完成以下Java代码
private ColumnNode selectColumnNodeHeuristic() { int min = Integer.MAX_VALUE; ColumnNode ret = null; for (ColumnNode c = (ColumnNode) header.R; c != header; c = (ColumnNode) c.R) { if (c.size < min) { min = c.size; ret = c; } } return ret; } private ColumnNode makeDLXBoard(boolean[][] grid) { final int COLS = grid[0].length; ColumnNode headerNode = new ColumnNode("header"); List<ColumnNode> columnNodes = new ArrayList<>(); for (int i = 0; i < COLS; i++) { ColumnNode n = new ColumnNode(Integer.toString(i)); columnNodes.add(n); headerNode = (ColumnNode) headerNode.hookRight(n); } headerNode = headerNode.R.C; for (boolean[] aGrid : grid) { DancingNode prev = null; for (int j = 0; j < COLS; j++) { if (aGrid[j]) { ColumnNode col = columnNodes.get(j); DancingNode newNode = new DancingNode(col); if (prev == null) prev = newNode; col.U.hookDown(newNode); prev = prev.hookRight(newNode); col.size++; } } } headerNode.size = COLS; return headerNode; } DancingLinks(boolean[][] cover) { header = makeDLXBoard(cover); } public void runSolver() { answer = new LinkedList<>(); search(0);
} private void handleSolution(List<DancingNode> answer) { int[][] result = parseBoard(answer); printSolution(result); } private int size = 9; private int[][] parseBoard(List<DancingNode> answer) { int[][] result = new int[size][size]; for (DancingNode n : answer) { DancingNode rcNode = n; int min = Integer.parseInt(rcNode.C.name); for (DancingNode tmp = n.R; tmp != n; tmp = tmp.R) { int val = Integer.parseInt(tmp.C.name); if (val < min) { min = val; rcNode = tmp; } } int ans1 = Integer.parseInt(rcNode.C.name); int ans2 = Integer.parseInt(rcNode.R.C.name); int r = ans1 / size; int c = ans1 % size; int num = (ans2 % size) + 1; result[r][c] = num; } return result; } private static void printSolution(int[][] result) { int size = result.length; for (int[] aResult : result) { StringBuilder ret = new StringBuilder(); for (int j = 0; j < size; j++) { ret.append(aResult[j]).append(" "); } System.out.println(ret); } System.out.println(); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\sudoku\DancingLinks.java
1
请完成以下Java代码
public IAttributeSplitterStrategy retrieveSplitterStrategy() { return NullSplitterStrategy.instance; } @Override public IHUAttributeTransferStrategy retrieveTransferStrategy() { return SkipHUAttributeTransferStrategy.instance; } @Override public boolean isUseInASI() { return false; } @Override public boolean isDefinedByTemplate() { return false; } @Override public void addAttributeValueListener(final IAttributeValueListener listener) { // nothing } @Override public List<ValueNamePair> getAvailableValues() { throw new InvalidAttributeValueException("method not supported for " + this); } @Override public IAttributeValuesProvider getAttributeValuesProvider() { throw new InvalidAttributeValueException("method not supported for " + this); } @Override public I_C_UOM getC_UOM() { return null; } @Override public IAttributeValueCallout getAttributeValueCallout() { return NullAttributeValueCallout.instance; } @Override public IAttributeValueGenerator getAttributeValueGeneratorOrNull() { return null; } @Override public void removeAttributeValueListener(final IAttributeValueListener listener) { // nothing } @Override public boolean isReadonlyUI() { return true; } @Override public boolean isDisplayedUI() { return false;
} @Override public boolean isMandatory() { return false; } @Override public int getDisplaySeqNo() { return 0; } @Override public NamePair getNullAttributeValue() { return null; } /** * @return true; we consider Null attributes as always generated */ @Override public boolean isNew() { return true; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\NullAttributeValue.java
1
请完成以下Java代码
public boolean isCompleted() { return qtyToAllocate.signum() == 0; } @Override public void subtractAllocatedQty(@NonNull final BigDecimal qtyAllocated) { final BigDecimal qtyToAllocateNew = qtyToAllocate.subtract(qtyAllocated); Check.assume(qtyToAllocateNew.signum() >= 0, "Cannot allocate {} when qtyToAllocate is {}", qtyAllocated, qtyToAllocate); qtyToAllocate = qtyToAllocateNew; } @Override public BigDecimal getQtyToAllocate() { return qtyToAllocate; } @Override public BigDecimal getQtyAllocated() { return qtyToAllocateInitial.subtract(qtyToAllocate); } @Override public void addTransaction(final IHUTransactionCandidate trx) { transactions.add(trx); } @Override public void addTransactions(final List<IHUTransactionCandidate> trxs) { trxs.forEach(trx -> addTransaction(trx)); } @Override public List<IHUTransactionCandidate> getTransactions()
{ return transactionsRO; } @Override public void addAttributeTransaction(final IHUTransactionAttribute attributeTrx) { attributeTransactions.add(attributeTrx); } @Override public void addAttributeTransactions(final List<IHUTransactionAttribute> attributeTrxs) { attributeTransactions.addAll(attributeTrxs); } @Override public List<IHUTransactionAttribute> getAttributeTransactions() { return attributeTransactionsRO; } @Override public void aggregateTransactions() { final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class); final List<IHUTransactionCandidate> aggregateTransactions = huTrxBL.aggregateTransactions(transactions); transactions.clear(); transactions.addAll(aggregateTransactions); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\MutableAllocationResult.java
1
请完成以下Java代码
public int getC_UOM_ID() { return inoutLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { // we assume inoutLine's UOM is correct if (uomId > 0) { inoutLine.setC_UOM_ID(uomId); } } @Override public BigDecimal getQtyTU() { return inoutLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { inoutLine.setQtyEnteredTU(qtyPacks); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override
public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public boolean isInDispute() { return inoutLine.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { inoutLine.setIsInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InOutLineHUPackingAware.java
1
请在Spring Boot框架中完成以下Java代码
public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPrice (final BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } @Override public BigDecimal getPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProductName (final java.lang.String ProductName) { set_Value (COLUMNNAME_ProductName, ProductName); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setQty (final 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 setScannedBarcode (final @Nullable java.lang.String ScannedBarcode) { set_Value (COLUMNNAME_ScannedBarcode, ScannedBarcode); } @Override public java.lang.String getScannedBarcode() { return get_ValueAsString(COLUMNNAME_ScannedBarcode); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_OrderLine.java
2
请完成以下Java代码
public String completeIt(@NonNull final DocumentTableFields docFields) { final I_QM_Analysis_Report analysisReport = extractQMAnalysisReport(docFields); analysisReport.setDocAction(IDocument.ACTION_ReActivate); if (analysisReport.isProcessed()) { throw new AdempiereException("@Processed@=@Y@"); } final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(analysisReport.getM_AttributeSetInstance_ID()); final I_M_Material_Tracking materialTracking = materialTrackingAttributeBL.getMaterialTrackingOrNull(asiId); if (materialTracking != null) { final I_M_Material_Tracking_Ref ref = materialTrackingDAO.createMaterialTrackingRefNoSave(materialTracking, analysisReport); InterfaceWrapperHelper.save(ref); } analysisReport.setProcessed(true); return IDocument.STATUS_Completed; } @Override public void voidIt(final DocumentTableFields docFields) { final I_QM_Analysis_Report analysisReport = extractQMAnalysisReport(docFields);
analysisReport.setProcessed(true); analysisReport.setDocAction(IDocument.ACTION_None); } @Override public void reactivateIt(@NonNull final DocumentTableFields docFields) { final I_QM_Analysis_Report analysisReport = extractQMAnalysisReport(docFields); analysisReport.setProcessed(false); analysisReport.setDocAction(IDocument.ACTION_Complete); } private static I_QM_Analysis_Report extractQMAnalysisReport(@NonNull final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_QM_Analysis_Report.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.qualitymgmt\src\main\java\de\metas\qualitymgmt\analysis\QMAnalysisReportDocumentHandler.java
1
请完成以下Java代码
private static final HuId extractHuId(final I_M_HU hu) { return hu != null ? HuId.ofRepoIdOrNull(hu.getM_HU_ID()) : null; } @Override public int compareTo(final HUTopLevel other) { if (this == other) { return 0; } if (other == null) { return +1; // nulls last } return hashKey.compareTo(other.hashKey); } /** * @return top level HU; never return <code>null</code> */ public I_M_HU getM_HU_TopLevel() { return topLevelHU; }
public I_M_HU getM_LU_HU() { return luHU; } public I_M_HU getM_TU_HU() { return tuHU; } public I_M_HU getVHU() { return vhu; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\HUTopLevel.java
1
请完成以下Java代码
public Map<String, String> initParams() { initParams.put(DISABLED_PARAM, null); initParams.put(VALUE_PARAM, null); return initParams; } @Override public void parseParams() { String disabled = initParams.get(DISABLED_PARAM); if (ServletFilterUtil.isEmpty(disabled)) { setDisabled(false); } else { setDisabled(Boolean.parseBoolean(disabled)); } String value = initParams.get(VALUE_PARAM); if (!isDisabled()) { if (!ServletFilterUtil.isEmpty(value)) { setValue(value);
} else { setValue(HEADER_DEFAULT_VALUE); } } } @Override public String getHeaderName() { return HEADER_NAME; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\headersec\provider\impl\ContentTypeOptionsProvider.java
1