instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public UserEntity getUserEntity() {
return userEntity; } public void setUserEntity(UserEntity userEntity) { this.userEntity = userEntity; } public List<CommentEntity> getCommentEntityList() { return commentEntityList; } public void setCommentEntityList(List<CommentEntity> commentEntityList) { this.commentEntityList = commentEntityList; } @Override public String toString() { return "ArticleEntity{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", content='" + content + '\'' + ", userEntity=" + userEntity + ", commentEntityList=" + commentEntityList + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\ArticleEntity.java
2
请完成以下Java代码
public void restore() { this.delegate.restore(); } private static final class DelegateAccessor implements ThreadLocalAccessor<Object> { @Override public Object key() { return SecurityContext.class.getName(); } @Override public Object getValue() { return SecurityContextHolder.getContext(); } @Override public void setValue(Object value) { SecurityContextHolder.setContext((SecurityContext) value); } @Override public void setValue() { SecurityContextHolder.clearContext(); } @Override public void restore(Object previousValue) { SecurityContextHolder.setContext((SecurityContext) previousValue); } @Override public void restore() { SecurityContextHolder.clearContext(); } @Override @Deprecated(since = "1.3.0", forRemoval = true) public void reset() { SecurityContextHolder.clearContext(); }
} private static final class NoOpAccessor implements ThreadLocalAccessor<Object> { @Override public Object key() { return getClass().getName(); } @Override public @Nullable Object getValue() { return null; } @Override public void setValue(Object value) { } @Override public void setValue() { } @Override public void restore(Object previousValue) { } @Override public void restore() { } @Override @Deprecated(since = "1.3.0", forRemoval = true) public void reset() { } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\SecurityContextThreadLocalAccessor.java
1
请在Spring Boot框架中完成以下Java代码
public String getCommercialInvoiceConsigneeVatNumber() { return commercialInvoiceConsigneeVatNumber; } /** * Sets the value of the commercialInvoiceConsigneeVatNumber property. * * @param value * allowed object is * {@link String } * */ public void setCommercialInvoiceConsigneeVatNumber(String value) { this.commercialInvoiceConsigneeVatNumber = value; } /** * Gets the value of the commercialInvoiceConsignee property. * * @return * possible object is * {@link Address } *
*/ public Address getCommercialInvoiceConsignee() { return commercialInvoiceConsignee; } /** * Sets the value of the commercialInvoiceConsignee property. * * @param value * allowed object is * {@link Address } * */ public void setCommercialInvoiceConsignee(Address value) { this.commercialInvoiceConsignee = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\International.java
2
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Function Prefix. @param FunctionPrefix Data sent before the function */ public void setFunctionPrefix (String FunctionPrefix) { set_Value (COLUMNNAME_FunctionPrefix, FunctionPrefix); } /** Get Function Prefix. @return Data sent before the function */ public String getFunctionPrefix () { return (String)get_Value(COLUMNNAME_FunctionPrefix); } /** Set Function Suffix. @param FunctionSuffix Data sent after the function */ public void setFunctionSuffix (String FunctionSuffix) { set_Value (COLUMNNAME_FunctionSuffix, FunctionSuffix); } /** Get Function Suffix. @return Data sent after the function */ public String getFunctionSuffix () { return (String)get_Value(COLUMNNAME_FunctionSuffix); } /** Set XY Position. @param IsXYPosition The Function is XY position */ public void setIsXYPosition (boolean IsXYPosition) { set_Value (COLUMNNAME_IsXYPosition, Boolean.valueOf(IsXYPosition)); } /** Get XY Position. @return The Function is XY position */ public boolean isXYPosition () { Object oo = get_Value(COLUMNNAME_IsXYPosition); if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set XY Separator. @param XYSeparator The separator between the X and Y function. */ public void setXYSeparator (String XYSeparator) { set_Value (COLUMNNAME_XYSeparator, XYSeparator); } /** Get XY Separator. @return The separator between the X and Y function. */ public String getXYSeparator () { return (String)get_Value(COLUMNNAME_XYSeparator); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinterFunction.java
1
请完成以下Java代码
public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public colgroup addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public colgroup addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element.
*/ public colgroup addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public colgroup addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public colgroup removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\colgroup.java
1
请完成以下Java代码
public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public org.compiere.model.I_M_InOut getM_InOut() { return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class); } @Override public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut) { set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut); } @Override public void setM_InOut_ID (final int M_InOut_ID) { if (M_InOut_ID < 1) set_Value (COLUMNNAME_M_InOut_ID, null); else set_Value (COLUMNNAME_M_InOut_ID, M_InOut_ID); } @Override public int getM_InOut_ID() { return get_ValueAsInt(COLUMNNAME_M_InOut_ID); } @Override public org.compiere.model.I_M_InOutLine getM_InOutLine() { return get_ValueAsPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class); } @Override public void setM_InOutLine(final org.compiere.model.I_M_InOutLine M_InOutLine) { set_ValueFromPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class, M_InOutLine); } @Override public void setM_InOutLine_ID (final int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_Value (COLUMNNAME_M_InOutLine_ID, null); else set_Value (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID); } @Override public int getM_InOutLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID); } @Override public void setQtyDeliveredInUOM (final @Nullable BigDecimal QtyDeliveredInUOM) {
set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM); } @Override public BigDecimal getQtyDeliveredInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyEntered (final @Nullable BigDecimal QtyEntered) { set_Value (COLUMNNAME_QtyEntered, QtyEntered); } @Override public BigDecimal getQtyEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInvoicedInUOM (final @Nullable BigDecimal QtyInvoicedInUOM) { set_Value (COLUMNNAME_QtyInvoicedInUOM, QtyInvoicedInUOM); } @Override public BigDecimal getQtyInvoicedInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInUOM); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_CallOrderDetail.java
1
请完成以下Java代码
public void setEventClass(String eventClass) { this.eventClass = eventClass; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public int getSpeedKmPerS() { return speedKmPerS; } public void setSpeedKmPerS(int speedKmPerS) { this.speedKmPerS = speedKmPerS; } } class Coordinates {
@JsonProperty("latitude") private double latitude; @JsonProperty("longitude") private double longitude; public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } }
repos\tutorials-master\json-modules\json-operations\src\main\java\com\baeldung\sorting\SolarEvent.java
1
请完成以下Java代码
public boolean isPartiallyPickedOrDelivered() { return packageable.getQtyPickedPlanned().signum() != 0 || packageable.getQtyPickedNotDelivered().signum() != 0 || packageable.getQtyPickedAndDelivered().signum() != 0; } public @NonNull ProductId getProductId() {return packageable.getProductId();} public @NonNull String getProductName() {return packageable.getProductName();} public @NonNull I_C_UOM getUOM() {return getQtyToDeliver().getUOM();} public @NonNull Quantity getQtyToDeliver() { return schedule != null ? schedule.getQtyToPick() : packageable.getQtyToDeliver(); } public @NonNull HUPIItemProductId getPackToHUPIItemProductId() {return packageable.getPackToHUPIItemProductId();} public @NonNull Quantity getQtyToPick() { return schedule != null
? schedule.getQtyToPick() : packageable.getQtyToPick(); } public @Nullable UomId getCatchWeightUomId() {return packageable.getCatchWeightUomId();} public @Nullable PPOrderId getPickFromOrderId() {return packageable.getPickFromOrderId();} public @Nullable ShipperId getShipperId() {return packageable.getShipperId();} public @NonNull AttributeSetInstanceId getAsiId() {return packageable.getAsiId();} public Optional<ShipmentAllocationBestBeforePolicy> getBestBeforePolicy() {return packageable.getBestBeforePolicy();} public @NonNull WarehouseId getWarehouseId() {return packageable.getWarehouseId();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageable.java
1
请完成以下Java代码
private boolean alreadyProcessed(NotificationRuleTrigger trigger, String deduplicationKey, boolean onlyLocalCache) { Long lastProcessedTs = localCache.get(deduplicationKey); if (lastProcessedTs == null && !onlyLocalCache) { Cache externalCache = getExternalCache(); if (externalCache != null) { lastProcessedTs = externalCache.get(deduplicationKey, Long.class); } else { log.warn("Sent notifications cache is not set up"); } } boolean alreadyProcessed = false; long deduplicationDuration = getDeduplicationDuration(trigger); if (lastProcessedTs != null) { long passed = System.currentTimeMillis() - lastProcessedTs; log.trace("Deduplicating trigger {} by key '{}'. Deduplication duration: {} ms, passed: {} ms", trigger.getType(), deduplicationKey, deduplicationDuration, passed); if (deduplicationDuration == 0 || passed <= deduplicationDuration) { alreadyProcessed = true; } } if (!alreadyProcessed) { lastProcessedTs = System.currentTimeMillis(); } localCache.put(deduplicationKey, lastProcessedTs); if (!onlyLocalCache) { if (!alreadyProcessed || deduplicationDuration == 0) { // if lastProcessedTs is changed or if deduplicating infinitely (so that cache value not removed by ttl) Cache externalCache = getExternalCache(); if (externalCache != null) { externalCache.put(deduplicationKey, lastProcessedTs); } } } return alreadyProcessed;
} public static String getDeduplicationKey(NotificationRuleTrigger trigger, NotificationRule rule) { return String.join("_", trigger.getDeduplicationKey(), rule.getDeduplicationKey()); } private long getDeduplicationDuration(NotificationRuleTrigger trigger) { return deduplicationDurations.computeIfAbsent(trigger.getType(), triggerType -> { return trigger.getDefaultDeduplicationDuration(); }); } private Cache getExternalCache() { return Optional.ofNullable(cacheManager) .map(cacheManager -> cacheManager.getCache(CacheConstants.SENT_NOTIFICATIONS_CACHE)) .orElse(null); } @Autowired public void setDeduplicationDurations(@Value("${notification_system.rules.deduplication_durations:}") String deduplicationDurationsStr) { this.deduplicationDurations = new ConcurrentHashMap<>(); PropertyUtils.getProps(deduplicationDurationsStr).forEach((triggerType, duration) -> { this.deduplicationDurations.put(NotificationRuleTriggerType.valueOf(triggerType), Long.parseLong(duration)); }); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\notification\DefaultNotificationDeduplicationService.java
1
请在Spring Boot框架中完成以下Java代码
public AppDeploymentQuery orderByDeploymentName() { return orderBy(AppDeploymentQueryProperty.DEPLOYMENT_NAME); } @Override public AppDeploymentQuery orderByTenantId() { return orderBy(AppDeploymentQueryProperty.DEPLOYMENT_TENANT_ID); } // results //////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getAppDeploymentEntityManager(commandContext).findDeploymentCountByQueryCriteria(this); } @Override public List<AppDeployment> executeList(CommandContext commandContext) { return CommandContextUtil.getAppDeploymentEntityManager(commandContext).findDeploymentsByQueryCriteria(this); } // getters //////////////////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public String getName() { return name; }
public String getNameLike() { return nameLike; } public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getKey() { return key; } public boolean isLatest() { return latest; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDeploymentQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public String getTitle() { return title; } public Instant getCreated() { return created; } public String getCreatedBy() { return createdBy; }
public String getAssignedTo() { return assignedTo; } public String getStatus() { return status; } public void setAssignedTo(final String assignedTo) { this.assignedTo = assignedTo; } public void setStatus(final String status) { this.status = status; } }
repos\tutorials-master\lightrun\lightrun-tasks-service\src\main\java\com\baeldung\tasksservice\adapters\repository\TaskRecord.java
2
请完成以下Java代码
protected Properties getConfig() { return config; } @Override public void setMonitor(IExporterMonitor monitor) { Check.assumeNotNull(monitor, "monitor not null"); this.monitor = monitor; } @Override public int getExportedRowCount() { return exportedRowCount.intValue(); } protected int incrementExportedRowCount() { return exportedRowCount.incrementAndGet(); } @Override public ExportStatus getExportStatus() { return exportStatus; } protected void setExportStatus(ExportStatus newStatus) { exportStatus = newStatus; } @Override public Throwable getError() { return error; } @Override public final void export(@NonNull final OutputStream out) { final IExportDataSource dataSource = getDataSource(); Check.assumeNotNull(dataSource, "dataSource not null"); Check.assume(ExportStatus.NotStarted.equals(getExportStatus()), "ExportStatus shall be " + ExportStatus.NotStarted + " and not {}", getExportStatus()); IExportDataDestination dataDestination = null; try { // Init dataDestination // NOTE: make sure we are doing this as first thing, because if anything fails, we need to close this "destination" dataDestination = createDataDestination(out); // Init status error = null; setExportStatus(ExportStatus.Running); monitor.exportStarted(this); while (dataSource.hasNext()) { final List<Object> values = dataSource.next(); // for (int i = 1; i <= 3000; i++) // debugging // { appendRow(dataDestination, values); incrementExportedRowCount(); // } }
} catch (Exception e) { final AdempiereException ex = new AdempiereException("Error while exporting line " + getExportedRowCount() + ": " + e.getLocalizedMessage(), e); error = ex; throw ex; } finally { close(dataSource); close(dataDestination); dataDestination = null; setExportStatus(ExportStatus.Finished); // Notify the monitor but discard all exceptions because we don't want to throw an "false" exception in finally block try { monitor.exportFinished(this); } catch (Exception e) { logger.error("Error while invoking monitor(finish): " + e.getLocalizedMessage(), e); } } logger.info("Exported " + getExportedRowCount() + " rows"); } protected abstract void appendRow(IExportDataDestination dataDestination, List<Object> values) throws IOException; protected abstract IExportDataDestination createDataDestination(OutputStream out) throws IOException; /** * Close {@link Closeable} object. * * NOTE: if <code>closeableObj</code> is not implementing {@link Closeable} or is null, nothing will happen * * @param closeableObj */ private static final void close(Object closeableObj) { if (closeableObj instanceof Closeable) { final Closeable closeable = (Closeable)closeableObj; try { closeable.close(); } catch (IOException e) { e.printStackTrace(); // NOPMD by tsa on 3/17/13 1:30 PM } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\AbstractExporter.java
1
请在Spring Boot框架中完成以下Java代码
protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedTaskIds() { final ProjectId projectId = getProjectId(); return getSelectedIncludedRecordIds(I_C_Project_Repair_Task.class) .stream() .map(taskRepoId -> ServiceRepairProjectTaskId.ofRepoId(projectId, taskRepoId)) .collect(ImmutableSet.toImmutableSet()); } protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedSparePartsTaskIds(final @NonNull IProcessPreconditionsContext context) { final ImmutableSet<ServiceRepairProjectTaskId> taskIds = getSelectedTaskIds(context); return projectService.retainIdsOfTypeSpareParts(taskIds); } protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedTaskIds(final @NonNull IProcessPreconditionsContext context) { final ProjectId projectId = ProjectId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); if (projectId == null) {
return ImmutableSet.of(); } return context.getSelectedIncludedRecords() .stream() .filter(recordRef -> I_C_Project_Repair_Task.Table_Name.equals(recordRef.getTableName())) .map(recordRef -> ServiceRepairProjectTaskId.ofRepoId(projectId, recordRef.getRecord_ID())) .collect(ImmutableSet.toImmutableSet()); } protected List<ServiceRepairProjectTask> getSelectedTasks(final @NonNull IProcessPreconditionsContext context) { return projectService.getTasksByIds(getSelectedTaskIds(context)); } protected List<ServiceRepairProjectTask> getSelectedTasks() { return projectService.getTasksByIds(getSelectedTaskIds()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\ServiceOrRepairProjectBasedProcess.java
2
请完成以下Java代码
public <T extends SimpleAsyncTaskExecutor> T build(Class<T> taskExecutorClass) { return configure(BeanUtils.instantiateClass(taskExecutorClass)); } /** * Configure the provided {@link SimpleAsyncTaskExecutor} instance using this builder. * @param <T> the type of task executor * @param taskExecutor the {@link SimpleAsyncTaskExecutor} to configure * @return the task executor instance * @see #build() * @see #build(Class) */ public <T extends SimpleAsyncTaskExecutor> T configure(T taskExecutor) { PropertyMapper map = PropertyMapper.get(); map.from(this.virtualThreads).to(taskExecutor::setVirtualThreads); map.from(this.threadNamePrefix).whenHasText().to(taskExecutor::setThreadNamePrefix); map.from(this.cancelRemainingTasksOnClose).to(taskExecutor::setCancelRemainingTasksOnClose); map.from(this.rejectTasksWhenLimitReached).to(taskExecutor::setRejectTasksWhenLimitReached); map.from(this.concurrencyLimit).to(taskExecutor::setConcurrencyLimit);
map.from(this.taskDecorator).to(taskExecutor::setTaskDecorator); map.from(this.taskTerminationTimeout).as(Duration::toMillis).to(taskExecutor::setTaskTerminationTimeout); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskExecutor)); } return taskExecutor; } private <T> Set<T> append(@Nullable Set<T> set, Iterable<? extends T> additions) { Set<T> result = new LinkedHashSet<>((set != null) ? set : Collections.emptySet()); additions.forEach(result::add); return Collections.unmodifiableSet(result); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\task\SimpleAsyncTaskExecutorBuilder.java
1
请完成以下Java代码
private void assertAuth() { userSession.assertLoggedIn(); final AdWindowId purchaseCandidatesWindowId = RecordWindowFinder.findAdWindowId(I_C_PurchaseCandidate.Table_Name).get(); if (!userSession.getUserRolePermissions().checkWindowPermission(purchaseCandidatesWindowId).hasWriteAccess()) { throw new AdempiereException("No read/write access to purchase candidates window"); } } @GetMapping public List<PurchaseCandidateReminder> getReminders() { assertAuth(); return reminderScheduler.getReminders(); } @PostMapping public synchronized void addReminder(@RequestBody final PurchaseCandidateReminder reminder) { assertAuth();
reminderScheduler.scheduleNotification(reminder); } @GetMapping("/nextDispatchTime") public ZonedDateTime getNextDispatchTime() { assertAuth(); return reminderScheduler.getNextDispatchTime(); } @PostMapping("/reinitialize") public List<PurchaseCandidateReminder> reinitialize() { assertAuth(); reminderScheduler.initialize(); return reminderScheduler.getReminders(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\purchasecandidate\reminder\PurchaseCandidateReminderSchedulerRestController.java
1
请完成以下Java代码
public void setAD_BusinessRule_ID (final int AD_BusinessRule_ID) { if (AD_BusinessRule_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_ID, AD_BusinessRule_ID); } @Override public int getAD_BusinessRule_ID() { return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setIsCreateWarningOnTarget (final boolean IsCreateWarningOnTarget) { set_Value (COLUMNNAME_IsCreateWarningOnTarget, IsCreateWarningOnTarget); } @Override public boolean isCreateWarningOnTarget() { return get_ValueAsBoolean(COLUMNNAME_IsCreateWarningOnTarget); } @Override public void setIsDebug (final boolean IsDebug) { set_Value (COLUMNNAME_IsDebug, IsDebug); } @Override public boolean isDebug() { return get_ValueAsBoolean(COLUMNNAME_IsDebug); } @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); } /** * Severity AD_Reference_ID=541949 * Reference name: Severity */ public static final int SEVERITY_AD_Reference_ID=541949; /** Notice = N */ public static final String SEVERITY_Notice = "N"; /** Error = E */ public static final String SEVERITY_Error = "E"; @Override public void setSeverity (final java.lang.String Severity)
{ set_Value (COLUMNNAME_Severity, Severity); } @Override public java.lang.String getSeverity() { return get_ValueAsString(COLUMNNAME_Severity); } @Override public org.compiere.model.I_AD_Val_Rule getValidation_Rule() { return get_ValueAsPO(COLUMNNAME_Validation_Rule_ID, org.compiere.model.I_AD_Val_Rule.class); } @Override public void setValidation_Rule(final org.compiere.model.I_AD_Val_Rule Validation_Rule) { set_ValueFromPO(COLUMNNAME_Validation_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, Validation_Rule); } @Override public void setValidation_Rule_ID (final int Validation_Rule_ID) { if (Validation_Rule_ID < 1) set_Value (COLUMNNAME_Validation_Rule_ID, null); else set_Value (COLUMNNAME_Validation_Rule_ID, Validation_Rule_ID); } @Override public int getValidation_Rule_ID() { return get_ValueAsInt(COLUMNNAME_Validation_Rule_ID); } @Override public void setWarning_Message_ID (final int Warning_Message_ID) { if (Warning_Message_ID < 1) set_Value (COLUMNNAME_Warning_Message_ID, null); else set_Value (COLUMNNAME_Warning_Message_ID, Warning_Message_ID); } @Override public int getWarning_Message_ID() { return get_ValueAsInt(COLUMNNAME_Warning_Message_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule.java
1
请在Spring Boot框架中完成以下Java代码
public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Component public class OrderPropertiesCommandLineRunner implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private OrderProperties orderProperties; @Override public void run(String... args) { logger.info("payTimeoutSeconds:" + orderProperties.getPayTimeoutSeconds()); logger.info("createFrequencySeconds:" + orderProperties.getCreateFrequencySeconds()); } } @Component public class ValueCommandLineRunner implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(getClass()); @Value("${order.pay-timeout-seconds}") private Integer payTimeoutSeconds; @Value("${order.create-frequency-seconds}") private Integer createFrequencySeconds; // @Value("${order.desc}") // private String desc; @Override public void run(String... args) { logger.info("payTimeoutSeconds:" + payTimeoutSeconds); logger.info("createFrequencySeconds:" + createFrequencySeconds); } } }
repos\SpringBoot-Labs-master\lab-43\lab-43-demo\src\main\java\cn\iocoder\springboot\lab43\propertydemo\Application.java
2
请完成以下Java代码
public class User implements Serializable ,Comparable{ private static final long serialVersionUID = -1205226416664488559L; private Integer id; private String username; private String password; public Integer getId() { return id; } public void setId(Integer 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; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } @Override public int compareTo(Object o) { User u= (User) o; return this.id.compareTo(u.id); } }
repos\SpringBootLearning-master\sharding-jdbc-example\sharding-jdbc-db-ms-tbl\src\main\java\com\forezp\shardingjdbcdbmstbl\entity\User.java
1
请在Spring Boot框架中完成以下Java代码
public class Customer { public static Customer ofOrNull(@Nullable final BPartnerId bPartnerId) { if (bPartnerId == null) { return null; } return of(bPartnerId); } @JsonCreator public static Customer of(@JsonProperty("bPartnerId") @NonNull final BPartnerId bPartnerId) { return new Customer(bPartnerId);
} BPartnerId bPartnerId; private Customer(BPartnerId bPartnerId) { this.bPartnerId = bPartnerId; } @JsonProperty("bPartnerId") public BPartnerId getBPartnerId() { return bPartnerId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\Customer.java
2
请完成以下Java代码
public java.math.BigDecimal getPaymentWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PaymentWriteOffAmt); if (bd == null) return BigDecimal.ZERO; return bd; } @Override public org.compiere.model.I_C_AllocationLine getReversalLine() { return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class); } @Override public void setReversalLine(org.compiere.model.I_C_AllocationLine ReversalLine) { set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class, ReversalLine); } /** Set Storno-Zeile. @param ReversalLine_ID Storno-Zeile */ @Override public void setReversalLine_ID (int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID)); } /** Get Storno-Zeile. @return Storno-Zeile */ @Override public int getReversalLine_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Abschreiben. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) { set_ValueNoCheck (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Abschreiben. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AllocationLine.java
1
请完成以下Java代码
public boolean isWithJobException() { return withJobException; } public String getLocale() { return locale; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } public boolean isNeedsProcessDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(HistoricProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName()); }
public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return rootScopeId; } public String getParentScopeId() { return parentScopeId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoricProcessInstanceQueryImpl.java
1
请完成以下Java代码
public List<Sentry> getSentries() { return sentries; } public List<SentryOnPart> getSentryOnParts() { return sentryOnParts; } public List<SentryIfPart> getSentryIfParts() { return sentryIfParts; } public List<PlanItem> getPlanItems() { return planItems; } public List<PlanItemDefinition> getPlanItemDefinitions() { return planItemDefinitions; } public List<CmmnDiShape> getDiShapes() { return diShapes;
} public List<CmmnDiEdge> getDiEdges() { return diEdges; } public GraphicInfo getCurrentLabelGraphicInfo() { return currentLabelGraphicInfo; } public void setCurrentLabelGraphicInfo(GraphicInfo labelGraphicInfo) { this.currentLabelGraphicInfo = labelGraphicInfo; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\ConversionHelper.java
1
请完成以下Java代码
public class HandleInstanceAlreadyExistsException { public static void generateUniqueClientIDUsingUUIDRandom() { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("key.serializer", StringSerializer.class); props.put("value.serializer", StringSerializer.class); String clientId = "my-producer-" + UUID.randomUUID(); props.setProperty("client.id", clientId); KafkaProducer<String, String> producer1 = new KafkaProducer<>(props); clientId = "my-producer-" + UUID.randomUUID(); props.setProperty("client.id", clientId); KafkaProducer<String, String> producer2 = new KafkaProducer<>(props); } public static void closeProducerProperlyBeforeReinstantiate() { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("client.id", "my-producer"); props.put("key.serializer", StringSerializer.class); props.put("value.serializer", StringSerializer.class); KafkaProducer<String, String> producer1 = new KafkaProducer<>(props); producer1.close(); producer1 = new KafkaProducer<>(props); }
public static void useUniqueObjectName() throws Exception { MBeanServer mBeanServer1 = ManagementFactory.getPlatformMBeanServer(); MBeanServer mBeanServer2 = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName1 = new ObjectName("kafka.server:type=KafkaMetrics,id=metric1"); ObjectName objectName2 = new ObjectName("kafka.server:type=KafkaMetrics,id=metric2"); MyMBean mBean1 = new MyMBean(); mBeanServer1.registerMBean(mBean1, objectName1); MyMBean mBean2 = new MyMBean(); mBeanServer2.registerMBean(mBean2, objectName2); } }
repos\tutorials-master\spring-kafka-3\src\main\java\com\baeldung\spring\kafka\kafkaexception\HandleInstanceAlreadyExistsException.java
1
请完成以下Java代码
public int getSubstitute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Substitute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gültig ab. @param ValidFrom Valid from including this date (first day) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Valid from including this date (first day) */ @Override public java.sql.Timestamp getValidFrom () {
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Valid to including this date (last day) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Valid to including this date (last day) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Substitute.java
1
请完成以下Java代码
private IDCache<PO> create(final ITableCacheConfig cacheConfig) { final String tableName = cacheConfig.getTableName(); final int expireMinutes = cacheConfig.getExpireMinutes(); final CacheMapType cacheMapType = cacheConfig.getCacheMapType(); final int initialCapacity = cacheConfig.getInitialCapacity(); int maxCapacity = cacheConfig.getMaxCapacity(); if (maxCapacity <= 0) { maxCapacity = initialCapacity; } return new IDCache<>(tableName, trxName, maxCapacity, expireMinutes, cacheMapType); } public void invalidateAll() { cachesByTableName.values().forEach(IDCache::reset); cachesByTableName.clear(); if (logger.isTraceEnabled()) { logger.trace("Cleared all caches for trx={} ", trxName); } } public void invalidateByTableName(final String tableName) { final IDCache<PO> cache = getByTableNameIfExists(tableName); if (cache == null) { return; } // Invalidate the cache cache.reset(); // Logging if (logger.isTraceEnabled()) { logger.trace("Cleared cache {} for tableName={}, trx={} ", cache.getCacheName(), tableName, trxName); } } public void invalidateByRecord(final TableRecordReference recordRef) { final String tableName = recordRef.getTableName();
final int recordId = recordRef.getRecord_ID(); // // Get table's cache map. final IDCache<PO> cache = getByTableNameIfExists(tableName); if (cache == null) { return; } // Invalidate the cache final boolean invalidated = cache.remove(recordId) != null; // Logging if (invalidated && logger.isTraceEnabled()) { logger.trace("Model removed from cache {}: record={}/{}, trx={} ", cache.getCacheName(), tableName, recordId, trxName); } } public void put(@NonNull final PO po, @NonNull final ITableCacheConfig cacheConfig) { // // Get table's cache map. // If does not exist, create one. final IDCache<PO> cache = getByTableNameOrCreate(cacheConfig); // // Add our PO to cache final int recordId = po.get_ID(); final PO poCopy = copyPO(po, trxName); if (poCopy == null) { logger.warn("Failed to add {} to cache because copy failed. Ignored.", po); return; } cache.put(recordId, poCopy); // Logging if (logger.isTraceEnabled()) { logger.trace("Model added to cache {}: {} ", cache.getCacheName(), poCopy); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\ModelCacheService.java
1
请完成以下Java代码
public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** FieldGroupType AD_Reference_ID=53000 */ public static final int FIELDGROUPTYPE_AD_Reference_ID=53000; /** Tab = T */ public static final String FIELDGROUPTYPE_Tab = "T"; /** Label = L */ public static final String FIELDGROUPTYPE_Label = "L"; /** Collapse = C */ public static final String FIELDGROUPTYPE_Collapse = "C"; /** Set Field Group Type. @param FieldGroupType Field Group Type */ public void setFieldGroupType (String FieldGroupType) { set_Value (COLUMNNAME_FieldGroupType, FieldGroupType); } /** Get Field Group Type. @return Field Group Type */ public String getFieldGroupType () { return (String)get_Value(COLUMNNAME_FieldGroupType); } /** Set Collapsed By Default. @param IsCollapsedByDefault Flag to set the initial state of collapsible field group. */ public void setIsCollapsedByDefault (boolean IsCollapsedByDefault) { set_Value (COLUMNNAME_IsCollapsedByDefault, Boolean.valueOf(IsCollapsedByDefault)); } /** Get Collapsed By Default. @return Flag to set the initial state of collapsible field group. */ public boolean isCollapsedByDefault () { Object oo = get_Value(COLUMNNAME_IsCollapsedByDefault); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_FieldGroup.java
1
请在Spring Boot框架中完成以下Java代码
public void markAsProcessed(final Set<PickingJobScheduleId> ids) { pickingJobScheduleRepository.updateByIds(ids, jobSchedule -> jobSchedule.toBuilder().processed(true).build()); } public Set<ShipmentScheduleId> getShipmentScheduleIdsWithAllJobSchedulesProcessedOrMissing(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) {return ImmutableSet.of();} final Map<ShipmentScheduleId, PickingJobScheduleCollection> jobSchedulesByShipmentScheduleId = stream(PickingJobScheduleQuery.builder().onlyShipmentScheduleIds(shipmentScheduleIds).build()) .collect(Collectors.groupingBy(PickingJobSchedule::getShipmentScheduleId, PickingJobScheduleCollection.collect())); final HashSet<ShipmentScheduleId> result = new HashSet<>(); for (final ShipmentScheduleId shipmentScheduleId : shipmentScheduleIds) { final PickingJobScheduleCollection jobSchedules = jobSchedulesByShipmentScheduleId.get(shipmentScheduleId); if (jobSchedules == null || jobSchedules.isAllProcessed()) { result.add(shipmentScheduleId); } } return result; } public Quantity getQtyRemainingToScheduleForPicking(@NonNull final ShipmentScheduleId shipmentScheduleId) {
final I_M_ShipmentSchedule shipmentSchedule = pickingJobShipmentScheduleService.getByIdAsRecord(shipmentScheduleId); final Quantity qtyToDeliver = pickingJobShipmentScheduleService.getQtyToDeliver(shipmentSchedule); final Quantity qtyScheduledForPicking = pickingJobShipmentScheduleService.getQtyScheduledForPicking(shipmentSchedule); return qtyToDeliver.subtract(qtyScheduledForPicking); } public void autoAssign(@NonNull final PickingJobScheduleAutoAssignRequest request) { PickingJobScheduleAutoAssignCommand.builder() .workplaceRepository(workplaceRepository) .pickingJobScheduleRepository(pickingJobScheduleRepository) .pickingJobShipmentScheduleService(pickingJobShipmentScheduleService) .sysConfigBL(sysConfigBL) .pickingJobProductService(pickingJobProductService) .request(request) .build() .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job_schedule\service\PickingJobScheduleService.java
2
请完成以下Java代码
public int getCreatedBy() { return po.getCreatedBy(); // getCreateddBy } /** * Get UpdatedBy * @return AD_User_ID */ public int getUpdatedBy() { return po.getUpdatedBy(); // getUpdatedBy } /************************************************************************** * Update Value or create new record. * To reload call load() - not updated * @return true if saved */ public boolean save() { return po.save(); // save } /** * Update Value or create new record. * To reload call load() - not updated * @param trxName transaction * @return true if saved */ public boolean save(String trxName) { return po.save(trxName); // save } /** * Is there a Change to be saved? * @return true if record changed */ public boolean is_Changed() { return po.is_Changed(); // is_Change } /** * Create Single/Multi Key Where Clause * @param withValues if true uses actual values otherwise ? * @return where clause */ public String get_WhereClause(boolean withValues) { return po.get_WhereClause(withValues); // getWhereClause } /************************************************************************** * Delete Current Record * @param force delete also processed records * @return true if deleted */ public boolean delete(boolean force) { return po.delete(force); // delete } /** * Delete Current Record * @param force delete also processed records * @param trxName transaction */ public boolean delete(boolean force, String trxName) { return po.delete(force, trxName); // delete }
/************************************************************************** * Lock it. * @return true if locked */ public boolean lock() { return po.lock(); // lock } /** * UnLock it * @return true if unlocked (false only if unlock fails) */ public boolean unlock(String trxName) { return po.unlock(trxName); // unlock } /** * Set Trx * @param trxName transaction */ public void set_TrxName(String trxName) { po.set_TrxName(trxName); // setTrx } /** * Get Trx * @return transaction */ public String get_TrxName() { return po.get_TrxName(); // getTrx } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\wrapper\AbstractPOWrapper.java
1
请完成以下Java代码
public UiExtensions scan(String... locations) throws IOException { List<UiExtension> extensions = new ArrayList<>(); for (String location : locations) { for (Resource resource : resolveAssets(location)) { String resourcePath = this.getResourcePath(location, resource); if (resourcePath != null && resource.isReadable()) { UiExtension extension = new UiExtension(resourcePath, location + resourcePath); log.debug("Found UiExtension {}", extension); extensions.add(extension); } } } return new UiExtensions(extensions); } private List<Resource> resolveAssets(String location) throws IOException { String widerLocation = toPattern(location); return Stream .concat(Arrays.stream(this.resolver.getResources(widerLocation + "**/*.js")), Arrays.stream(this.resolver.getResources(widerLocation + "**/*.css"))) .toList();
} private String toPattern(String location) { // replace the classpath pattern to search all locations and not just the first return location.replace("classpath:", "classpath*:"); } @Nullable private String getResourcePath(String location, Resource resource) throws IOException { String locationWithoutPrefix = location.replaceFirst("^[^:]+:", ""); Matcher m = Pattern.compile(Pattern.quote(locationWithoutPrefix) + "(.+)$") .matcher(resource.getURI().toString()); if (m.find()) { return m.group(1); } else { return null; } } }
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\extensions\UiExtensionsScanner.java
1
请完成以下Java代码
public Long getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link Long } * */ public void setVersion(Long value) { this.version = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public long getId() { if (id == null) { return 0L; } else { return id; }
} /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DependsOnType.java
1
请在Spring Boot框架中完成以下Java代码
public void uploadFiles(List<MultipartFile> files) throws IOException { uploadFiles(files, true); } /** * single file upload (MultipartFile) * * @param multipartFile MultipartFile * @throws IOException */ @Override public void uploadFile(MultipartFile multipartFile) throws IOException { gateway.upload(convert(multipartFile)); } @Override public String listFileNames(String dir) { return gateway.nlstFile(dir); } @Override public File getFile(String dir) { return null; } @Override public List<File> mgetFile(String dir) { return null; } @Override public boolean rmFile(String file) { return false; } @Override public boolean mv(String sourceFile, String targetFile) { return false; } @Override public File putFile(String dir) { return null; } @Override public List<File> mputFile(String dir) { return null; } @Override public String nlstFile(String dir) { return gateway.nlstFile(dir); } private static File convertInputStreamToFile(InputStream inputStream, String savePath) { OutputStream outputStream = null; File file = new File(savePath);
try { outputStream = new FileOutputStream(file); int read; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } log.info("convert InputStream to file done, savePath is : {}", savePath); } catch (IOException e) { log.error("error:", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { log.error("error:", e); } } } return file; } private static File convert(MultipartFile file) throws IOException { File convertFile = new File(file.getOriginalFilename()); convertFile.createNewFile(); FileOutputStream fos = new FileOutputStream(convertFile); fos.write(file.getBytes()); fos.close(); return convertFile; } }
repos\springboot-demo-master\sftp\src\main\java\com\et\sftp\service\impl\SftpServiceImpl.java
2
请完成以下Java代码
public User withRole(Role role) { this.role = role; return this; } @Override @SuppressWarnings("all") public int compareTo(User other) { return this.getName().compareTo(other.getName()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof User)) { return false; } User that = (User) obj; return this.getName().equals(that.getName()); } @Override public int hashCode() { int hashValue = 17; hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getName()); return hashValue;
} @Override public String toString() { return getName(); } public enum Role { CLUSTER_OPERATOR, DEVELOPER; public static Role of(String name) { return Arrays.stream(values()) .filter(role -> role.name().equalsIgnoreCase(String.valueOf(name).trim())) .findFirst() .orElse(null); } public boolean isClusterOperator() { return CLUSTER_OPERATOR.equals(this); } public boolean isDeveloper() { return DEVELOPER.equals(this); } @Override public String toString() { return name().toLowerCase(); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\support\User.java
1
请完成以下Java代码
public long size() { return rows.size(); } private static ImmutableMap<DocumentId, HUEditorRow> buildRowsByIdMap(final List<HUEditorRow> rows) { if (rows.isEmpty()) { return ImmutableMap.of(); } final ImmutableMap.Builder<DocumentId, HUEditorRow> rowsById = ImmutableMap.builder(); rows.forEach(row -> indexByIdRecursively(rowsById, row)); return rowsById.build(); } private static void indexByIdRecursively(final ImmutableMap.Builder<DocumentId, HUEditorRow> collector, final HUEditorRow row) { collector.put(row.getId(), row); row.getIncludedRows() .forEach(includedRow -> indexByIdRecursively(collector, includedRow)); } private static ImmutableMap<HUEditorRowId, HUEditorRowId> buildRowId2ParentIdMap(final List<HUEditorRow> rows) { if (rows.isEmpty()) {
return ImmutableMap.of(); } final ImmutableMap.Builder<HUEditorRowId, HUEditorRowId> rowId2parentId = ImmutableMap.builder(); rows.forEach(row -> buildRowId2ParentIdMap(rowId2parentId, row)); return rowId2parentId.build(); } private static void buildRowId2ParentIdMap(final ImmutableMap.Builder<HUEditorRowId, HUEditorRowId> rowId2parentId, final HUEditorRow parentRow) { final HUEditorRowId parentId = parentRow.getHURowId(); parentRow.getIncludedRows() .forEach(includedRow -> rowId2parentId.put(includedRow.getHURowId(), parentId)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuffer_FullyCached.java
1
请完成以下Java代码
public Builder jwkSetUrl(String jwkSetUrl) { return setting(ConfigurationSettingNames.Client.JWK_SET_URL, jwkSetUrl); } /** * Sets the {@link JwsAlgorithm JWS} algorithm that must be used for signing the * {@link Jwt JWT} used to authenticate the Client at the Token Endpoint for the * {@link ClientAuthenticationMethod#PRIVATE_KEY_JWT private_key_jwt} and * {@link ClientAuthenticationMethod#CLIENT_SECRET_JWT client_secret_jwt} * authentication methods. * @param authenticationSigningAlgorithm the {@link JwsAlgorithm JWS} algorithm * that must be used for signing the {@link Jwt JWT} used to authenticate the * Client at the Token Endpoint * @return the {@link Builder} for further configuration */ public Builder tokenEndpointAuthenticationSigningAlgorithm(JwsAlgorithm authenticationSigningAlgorithm) { return setting(ConfigurationSettingNames.Client.TOKEN_ENDPOINT_AUTHENTICATION_SIGNING_ALGORITHM, authenticationSigningAlgorithm); } /** * Sets the expected subject distinguished name associated to the client * {@code X509Certificate} received during client authentication when using the * {@code tls_client_auth} method. * @param x509CertificateSubjectDN the expected subject distinguished name * associated to the client {@code X509Certificate} received during client * authentication * @return the {@link Builder} for further configuration * @return the {@link Builder} for further configuration
*/ public Builder x509CertificateSubjectDN(String x509CertificateSubjectDN) { return setting(ConfigurationSettingNames.Client.X509_CERTIFICATE_SUBJECT_DN, x509CertificateSubjectDN); } /** * Builds the {@link ClientSettings}. * @return the {@link ClientSettings} */ @Override public ClientSettings build() { return new ClientSettings(getSettings()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\ClientSettings.java
1
请在Spring Boot框架中完成以下Java代码
public class PersonTemplateService implements PersonService { private static final String DESIGN_DOC = "person"; private CouchbaseTemplate template; @Autowired public void setCouchbaseTemplate(CouchbaseTemplate template) { this.template = template; } public Optional<Person> findOne(String id) { return Optional.of(template.findById(Person.class).one(id)); } public List<Person> findAll() { return template.findByQuery(Person.class).all(); } public List<Person> findByFirstName(String firstName) {
return template.findByQuery(Person.class).matching(where("firstName").is(firstName)).all(); } public List<Person> findByLastName(String lastName) { return template.findByQuery(Person.class).matching(where("lastName").is(lastName)).all(); } public void create(Person person) { person.setCreated(DateTime.now()); template.insertById(Person.class).one(person); } public void update(Person person) { person.setUpdated(DateTime.now()); template.removeById(Person.class).oneEntity(person); } public void delete(Person person) { template.removeById(Person.class).oneEntity(person); } }
repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\service\PersonTemplateService.java
2
请完成以下Java代码
public void callAfterLoad(final BiConsumer<IHUContext, List<IAllocationResult>> consumer) { addListener(new IHUTrxListener() { @Override public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults) { consumer.accept(huContext, loadResults); } }); } public void removeListener(final IHUTrxListener listener) { if (listener == null) { return; } listeners.remove(listener); } /** * * @param listener * @return true if given listener was already registered */ public boolean hasListener(final IHUTrxListener listener) { return listeners.contains(listener); } public List<IHUTrxListener> asList() { return new ArrayList<>(listeners); } public CompositeHUTrxListener copy() { final CompositeHUTrxListener copy = new CompositeHUTrxListener(); copy.listeners.addAll(listeners); return copy; } @Override public void trxLineProcessed(final IHUContext huContext, final I_M_HU_Trx_Line trxLine) { for (final IHUTrxListener listener : listeners) { listener.trxLineProcessed(huContext, trxLine); } } @Override public void huParentChanged(final I_M_HU hu, final I_M_HU_Item parentHUItemOld) { for (final IHUTrxListener listener : listeners) { listener.huParentChanged(hu, parentHUItemOld); } } @Override public void afterTrxProcessed(final IReference<I_M_HU_Trx_Hdr> trxHdrRef, final List<I_M_HU_Trx_Line> trxLines) { for (final IHUTrxListener listener : listeners) { listener.afterTrxProcessed(trxHdrRef, trxLines); } } @Override
public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults) { for (final IHUTrxListener listener : listeners) { listener.afterLoad(huContext, loadResults); } } @Override public void onUnloadLoadTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners) { listener.onUnloadLoadTransaction(huContext, unloadTrx, loadTrx); } } @Override public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners) { listener.onSplitTransaction(huContext, unloadTrx, loadTrx); } } @Override public String toString() { return "CompositeHUTrxListener [listeners=" + listeners + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CompositeHUTrxListener.java
1
请在Spring Boot框架中完成以下Java代码
public StaticResourceRequestMatcher excluding(Set<StaticResourceLocation> locations) { Assert.notNull(locations, "'locations' must not be null"); Set<StaticResourceLocation> subset = new LinkedHashSet<>(this.locations); subset.removeAll(locations); return new StaticResourceRequestMatcher(subset); } @Override protected void initialized(Supplier<DispatcherServletPath> dispatcherServletPath) { this.delegate = new OrRequestMatcher(getDelegateMatchers(dispatcherServletPath.get()).toList()); } private Stream<RequestMatcher> getDelegateMatchers(DispatcherServletPath dispatcherServletPath) { return getPatterns(dispatcherServletPath).map(PathPatternRequestMatcher.withDefaults()::matcher); } private Stream<String> getPatterns(DispatcherServletPath dispatcherServletPath) { return this.locations.stream() .flatMap(StaticResourceLocation::getPatterns) .map(dispatcherServletPath::getRelativePath); }
@Override protected boolean ignoreApplicationContext(WebApplicationContext applicationContext) { return hasServerNamespace(applicationContext, "management"); } @Override protected boolean matches(HttpServletRequest request, Supplier<DispatcherServletPath> context) { RequestMatcher delegate = this.delegate; Assert.state(delegate != null, "'delegate' must not be null"); return delegate.matches(request); } } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\web\servlet\StaticResourceRequest.java
2
请完成以下Java代码
public void setSubProducer_BPartner_ID (final int SubProducer_BPartner_ID) { if (SubProducer_BPartner_ID < 1) set_Value (COLUMNNAME_SubProducer_BPartner_ID, null); else set_Value (COLUMNNAME_SubProducer_BPartner_ID, SubProducer_BPartner_ID); } @Override public int getSubProducer_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_SubProducer_BPartner_ID); } /** * SubProducerBPartner_Value AD_Reference_ID=138 * Reference name: C_BPartner (Trx) */ public static final int SUBPRODUCERBPARTNER_VALUE_AD_Reference_ID=138; @Override public void setSubProducerBPartner_Value (final @Nullable java.lang.String SubProducerBPartner_Value) { set_Value (COLUMNNAME_SubProducerBPartner_Value, SubProducerBPartner_Value); } @Override public java.lang.String getSubProducerBPartner_Value() { return get_ValueAsString(COLUMNNAME_SubProducerBPartner_Value); } @Override public void setTE (final @Nullable java.lang.String TE) { set_Value (COLUMNNAME_TE, TE); } @Override public java.lang.String getTE() { return get_ValueAsString(COLUMNNAME_TE); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } @Override public void setWarehouseLocatorIdentifier (final @Nullable java.lang.String WarehouseLocatorIdentifier) { set_Value (COLUMNNAME_WarehouseLocatorIdentifier, WarehouseLocatorIdentifier); } @Override public java.lang.String getWarehouseLocatorIdentifier() { return get_ValueAsString(COLUMNNAME_WarehouseLocatorIdentifier); } @Override public void setWarehouseValue (final @Nullable java.lang.String WarehouseValue) { set_Value (COLUMNNAME_WarehouseValue, WarehouseValue); } @Override public java.lang.String getWarehouseValue() { return get_ValueAsString(COLUMNNAME_WarehouseValue); } @Override public void setX (final @Nullable java.lang.String X)
{ set_Value (COLUMNNAME_X, X); } @Override public java.lang.String getX() { return get_ValueAsString(COLUMNNAME_X); } @Override public void setX1 (final @Nullable java.lang.String X1) { set_Value (COLUMNNAME_X1, X1); } @Override public java.lang.String getX1() { return get_ValueAsString(COLUMNNAME_X1); } @Override public void setY (final @Nullable java.lang.String Y) { set_Value (COLUMNNAME_Y, Y); } @Override public java.lang.String getY() { return get_ValueAsString(COLUMNNAME_Y); } @Override public void setZ (final @Nullable java.lang.String Z) { set_Value (COLUMNNAME_Z, Z); } @Override public java.lang.String getZ() { return get_ValueAsString(COLUMNNAME_Z); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Inventory.java
1
请完成以下Java代码
public boolean isUserElement2Dim () { Object oo = get_Value(COLUMNNAME_IsUserElement2Dim); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Last Recalculated. @param LastRecalculated The time last recalculated. */ public void setLastRecalculated (Timestamp LastRecalculated) { set_Value (COLUMNNAME_LastRecalculated, LastRecalculated); } /** Get Last Recalculated. @return The time last recalculated. */ public Timestamp getLastRecalculated () { return (Timestamp)get_Value(COLUMNNAME_LastRecalculated); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Report Cube. @param PA_ReportCube_ID Define reporting cube for pre-calculation of summary accounting data. */ public void setPA_ReportCube_ID (int PA_ReportCube_ID) { if (PA_ReportCube_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportCube_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportCube_ID, Integer.valueOf(PA_ReportCube_ID)); }
/** Get Report Cube. @return Define reporting cube for pre-calculation of summary accounting data. */ public int getPA_ReportCube_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportCube_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportCube.java
1
请完成以下Java代码
public void setPrecision(CurrencyPrecision precision) { this.precision = precision; } public void setProductPrice(final I_M_Product product, final BigDecimal price) { productId2price.put(ProductId.ofRepoId(product.getM_Product_ID()), price); } @Override public boolean applies(IPricingContext pricingCtx, IPricingResult result) { return true; } @Override public void calculate(IPricingContext pricingCtx, IPricingResult result) { // // Check product price final ProductId productId = pricingCtx.getProductId(); BigDecimal price = productId2price.get(productId); if (price == null) { price = priceToReturn; }
result.setPriceLimit(price); result.setPriceList(price); result.setPriceStd(price); result.setPrecision(precision); result.setTaxCategoryId(TaxCategoryId.ofRepoId(100)); final I_C_UOM priceUOM = productId2priceUOM.get(productId); if (priceUOM != null) { result.setPriceUomId(UomId.ofRepoId(priceUOM.getC_UOM_ID())); } result.setCalculated(true); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\MockedPricingRule.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoryJobEntityManagerImpl extends JobInfoEntityManagerImpl<HistoryJobEntity, HistoryJobDataManager> implements HistoryJobEntityManager { private static final Logger LOGGER = LoggerFactory.getLogger(HistoryJobEntityManagerImpl.class); public HistoryJobEntityManagerImpl(JobServiceConfiguration jobServiceConfiguration, HistoryJobDataManager historyJobDataManager) { super(jobServiceConfiguration, historyJobDataManager); } @Override public void insert(HistoryJobEntity jobEntity, boolean fireCreateEvent) { doInsert(jobEntity, fireCreateEvent); } protected boolean doInsert(HistoryJobEntity jobEntity, boolean fireCreateEvent) { jobEntity.setCreateTime(getClock().getCurrentTime()); super.insert(jobEntity, fireCreateEvent); return true; } @Override public List<HistoryJob> findHistoryJobsByQueryCriteria(HistoryJobQueryImpl jobQuery) { return dataManager.findHistoryJobsByQueryCriteria(jobQuery); } @Override public long findHistoryJobCountByQueryCriteria(HistoryJobQueryImpl jobQuery) {
return dataManager.findHistoryJobCountByQueryCriteria(jobQuery); } @Override public void delete(HistoryJobEntity jobEntity) { super.delete(jobEntity, false); deleteByteArrayRef(jobEntity.getExceptionByteArrayRef()); deleteByteArrayRef(jobEntity.getAdvancedJobHandlerConfigurationByteArrayRef()); deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef()); // Send event FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, jobEntity), serviceConfiguration.getEngineName()); } } @Override public void deleteNoCascade(HistoryJobEntity historyJobEntity) { super.delete(historyJobEntity); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\HistoryJobEntityManagerImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class Issue { @JsonProperty("id") String id; @JsonProperty("html_url") String htmlUrl; @JsonProperty("number") Integer number; @JsonProperty("title") String title; @JsonProperty("labels") List<Label> labelList; @JsonProperty("state") String state; @JsonProperty("assignee") User assignee;
@JsonProperty("milestone") GithubMilestone githubMilestone; @JsonProperty("body") String body; @JsonProperty("pull_request") PullRequest pullRequest; public boolean isPullRequest() { return pullRequest != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.issue.tracking.github\src\main\java\de\metas\issue\tracking\github\api\v3\model\Issue.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteAllLocalTaskVariables(@ApiParam(name = "taskId") @PathVariable String taskId) { Task task = getTaskFromRequestWithoutAccessCheck(taskId); Collection<String> currentVariables = taskService.getVariablesLocal(task.getId()).keySet(); if (restApiInterceptor != null) { restApiInterceptor.deleteTaskVariables(task, currentVariables, RestVariableScope.LOCAL); } taskService.removeVariablesLocal(task.getId(), currentVariables); } protected void addGlobalVariables(Task task, Map<String, RestVariable> variableMap) { if (task.getScopeId() != null) { Map<String, Object> rawVariables = runtimeService.getVariables(task.getScopeId()); List<RestVariable> globalVariables = restResponseFactory.createRestVariables(rawVariables, task.getId(), CmmnRestResponseFactory.VARIABLE_TASK, RestVariableScope.GLOBAL); // Overlay global variables over local ones. In case they are present the values are not overridden, // since local variables get precedence over global ones at all times. for (RestVariable var : globalVariables) {
if (!variableMap.containsKey(var.getName())) { variableMap.put(var.getName(), var); } } } } protected void addLocalVariables(Task task, Map<String, RestVariable> variableMap) { Map<String, Object> rawVariables = taskService.getVariablesLocal(task.getId()); List<RestVariable> localVariables = restResponseFactory.createRestVariables(rawVariables, task.getId(), CmmnRestResponseFactory.VARIABLE_TASK, RestVariableScope.LOCAL); for (RestVariable var : localVariables) { variableMap.put(var.getName(), var); } } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskVariableCollectionResource.java
2
请在Spring Boot框架中完成以下Java代码
public net.shibboleth.shared.resource.Resource createRelativeResource(String relativePath) throws IOException { return new SpringResource(this.resource.createRelative(relativePath)); } @Override public String getFilename() { return this.resource.getFilename(); } @Override public String getDescription() { return this.resource.getDescription(); } } } private static final class CriteriaSetResolverWrapper extends MetadataResolverAdapter { CriteriaSetResolverWrapper(MetadataResolver metadataResolver) { super(metadataResolver);
} @Override EntityDescriptor resolveSingle(EntityIdCriterion entityId) throws Exception { return super.metadataResolver.resolveSingle(new CriteriaSet(entityId)); } @Override Iterable<EntityDescriptor> resolve(EntityRoleCriterion role) throws Exception { return super.metadataResolver.resolve(new CriteriaSet(role)); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\registration\OpenSaml5AssertingPartyMetadataRepository.java
2
请完成以下Java代码
private void sendClientRegistrationResponse(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { OidcClientRegistration clientRegistration = ((OidcClientRegistrationAuthenticationToken) authentication) .getClientRegistration(); ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); if (HttpMethod.POST.name().equals(request.getMethod())) { httpResponse.setStatusCode(HttpStatus.CREATED); } else { httpResponse.setStatusCode(HttpStatus.OK); } this.clientRegistrationHttpMessageConverter.write(clientRegistration, null, httpResponse); } private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException { OAuth2Error error = ((OAuth2AuthenticationException) authenticationException).getError(); HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
if (OAuth2ErrorCodes.INVALID_TOKEN.equals(error.getErrorCode())) { httpStatus = HttpStatus.UNAUTHORIZED; } else if (OAuth2ErrorCodes.INSUFFICIENT_SCOPE.equals(error.getErrorCode())) { httpStatus = HttpStatus.FORBIDDEN; } else if (OAuth2ErrorCodes.INVALID_CLIENT.equals(error.getErrorCode())) { httpStatus = HttpStatus.UNAUTHORIZED; } ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); httpResponse.setStatusCode(httpStatus); this.errorHttpResponseConverter.write(error, null, httpResponse); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\web\OidcClientRegistrationEndpointFilter.java
1
请完成以下Java代码
public void setC_Activities(final I_M_MovementLine movementLine) { final ActivityId productActivityId = Services.get(IProductActivityProvider.class).retrieveActivityForAcct( ClientId.ofRepoId(movementLine.getAD_Client_ID()), OrgId.ofRepoId(movementLine.getAD_Org_ID()), ProductId.ofRepoId(movementLine.getM_Product_ID())); final I_M_Locator locatorFrom = warehouseDAO.getLocatorByRepoId(movementLine.getM_Locator_ID()); final ActivityId activityFromId = getActivity(locatorFrom, productActivityId); movementLine.setC_ActivityFrom_ID(ActivityId.toRepoId(activityFromId)); final I_M_Locator locatorTo = warehouseDAO.getLocatorByRepoId(movementLine.getM_LocatorTo_ID()); final ActivityId activityToId = getActivity(locatorTo, productActivityId); movementLine.setC_Activity_ID(ActivityId.toRepoId(activityToId)); InterfaceWrapperHelper.save(movementLine); } /** * @return the activity from the warehouse, if it exists. Otherwise, return the defaultValue. */ private ActivityId getActivity(@NonNull final I_M_Locator locator, final ActivityId defaultActivityId) { final WarehouseId warehouseId = WarehouseId.ofRepoId(locator.getM_Warehouse_ID()); final I_M_Warehouse warehouse = warehouseDAO.getById(warehouseId); final ActivityId warehouseActivityId = ActivityId.ofRepoIdOrNull(warehouse.getC_Activity_ID()); return warehouseActivityId != null ? warehouseActivityId : defaultActivityId; } @Override public boolean isReversal(final I_M_Movement movement) { Check.assumeNotNull(movement, "movement not null"); // Check if we have a counter-part reversal document final int reversalId = movement.getReversal_ID(); if (reversalId <= 0) { return false; }
// Make sure this is the actual reversal and not the original document which was reversed // i.e. this document was created after the reversal (so Reversal_ID is less than this document's ID) final int movementId = movement.getM_Movement_ID(); //noinspection UnnecessaryLocalVariable final boolean reversal = movementId > reversalId; return reversal; } @Override public void complete(@NonNull final I_M_Movement movement) { documentBL.processEx(movement, IDocument.ACTION_Complete, IDocument.STATUS_Completed); } @Override public void voidMovement(final I_M_Movement movement) { documentBL.processEx(movement, IDocument.ACTION_Void, IDocument.STATUS_Reversed); } @Override public void save(@NonNull final I_M_Movement movement) { movementDAO.save(movement); } @Override public void save(@NonNull final I_M_MovementLine movementLine) { movementDAO.save(movementLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mmovement\api\impl\MovementBL.java
1
请完成以下Java代码
public class BankToCustomerDebitCreditNotificationV06 { @XmlElement(name = "GrpHdr", required = true) protected GroupHeader58 grpHdr; @XmlElement(name = "Ntfctn", required = true) protected List<AccountNotification12> ntfctn; @XmlElement(name = "SplmtryData") protected List<SupplementaryData1> splmtryData; /** * Gets the value of the grpHdr property. * * @return * possible object is * {@link GroupHeader58 } * */ public GroupHeader58 getGrpHdr() { return grpHdr; } /** * Sets the value of the grpHdr property. * * @param value * allowed object is * {@link GroupHeader58 } * */ public void setGrpHdr(GroupHeader58 value) { this.grpHdr = value; } /** * Gets the value of the ntfctn 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 ntfctn property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNtfctn().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AccountNotification12 } * *
*/ public List<AccountNotification12> getNtfctn() { if (ntfctn == null) { ntfctn = new ArrayList<AccountNotification12>(); } return this.ntfctn; } /** * Gets the value of the splmtryData 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 splmtryData property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSplmtryData().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SupplementaryData1 } * * */ public List<SupplementaryData1> getSplmtryData() { if (splmtryData == null) { splmtryData = new ArrayList<SupplementaryData1>(); } return this.splmtryData; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\BankToCustomerDebitCreditNotificationV06.java
1
请完成以下Spring Boot application配置
server.port=9093 server.address=127.0.0.1 # vulnerable configuration set 0: spring boot 1.0 - 1.4 # all spring boot versions 1.0 - 1.4 expose actuators by default without any parameters # no configuration required to expose them # safe configuration set 0: spring boot 1.0 - 1.4 #management.security.enabled=true # vulnerable configuration set 1: spring boot 1.5+ # spring boot 1.5+ requires management.security.enabled=false to expose sensitive actuators #management.security.enabled=false # safe configuration set 1: spring boot 1.5+ # when 'management.sec
urity.enabled=false' but all sensitive actuators explicitly disabled #management.security.enabled=false # vulnerable configuration set 2: spring boot 2+ #management.endpoints.web.exposure.include=* #management.endpoint.env.post.enabled=true
repos\SpringBootVulExploit-master\repository\springboot-eureka-xstream-rce\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public String getProcessDefinitionUrl() { return processDefinitionUrl; } public void setProcessDefinitionUrl(String processDefinitionUrl) { this.processDefinitionUrl = processDefinitionUrl; } @ApiModelProperty(example = "7") public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @ApiModelProperty(example = "http://localhost:8182/runtime/executions/7") public String getExecutionUrl() { return executionUrl; } public void setExecutionUrl(String executionUrl) { this.executionUrl = executionUrl; } @ApiModelProperty(example = "timer") public String getElementId() { return elementId; } public void setElementId(String elementId) { this.elementId = elementId; } @ApiModelProperty(example = "Timer task") public String getElementName() { return elementName; } public void setElementName(String elementName) { this.elementName = elementName; } @ApiModelProperty(example = "trigger-timer") public String getHandlerType() { return handlerType; } public void setHandlerType(String handlerType) { this.handlerType = handlerType; } @ApiModelProperty(example = "3") public Integer getRetries() { return retries; }
public void setRetries(Integer retries) { this.retries = retries; } @ApiModelProperty(example = "null") public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } @ApiModelProperty(example = "2023-06-04T22:05:05.474+0000") public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @ApiModelProperty(example = "node1") public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\JobResponse.java
2
请在Spring Boot框架中完成以下Java代码
public Result<?> getOpenApi(String apiAuthId) { List<OpenApi> openApis = openApiService.list(); if (CollectionUtil.isEmpty(openApis)) { return Result.error("接口不存在"); } List<OpenApiPermission> openApiPermissions = baseMapper.selectList(Wrappers.<OpenApiPermission>lambdaQuery().eq(OpenApiPermission::getApiAuthId, apiAuthId)); if (CollectionUtil.isNotEmpty(openApiPermissions)) { Map<String, OpenApi> openApiMap = openApis.stream().collect(Collectors.toMap(OpenApi::getId, o -> o)); for (OpenApiPermission openApiPermission : openApiPermissions) { OpenApi openApi = openApiMap.get(openApiPermission.getApiId()); if (openApi!=null) { openApi.setIfCheckBox("1"); } } } return Result.ok(openApis); }
@Override public void add(OpenApiPermission openApiPermission) { this.remove(Wrappers.<OpenApiPermission>lambdaQuery().eq(OpenApiPermission::getApiAuthId, openApiPermission.getApiAuthId())); List<String> list = Arrays.asList(openApiPermission.getApiId().split(",")); if (CollectionUtil.isNotEmpty(list)) { list.forEach(l->{ if (StrUtil.isNotEmpty(l)){ OpenApiPermission saveApiPermission = new OpenApiPermission(); saveApiPermission.setApiId(l); saveApiPermission.setApiAuthId(openApiPermission.getApiAuthId()); this.save(saveApiPermission); } }); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\service\impl\OpenApiPermissionServiceImpl.java
2
请完成以下Java代码
public class BpmnLabelImpl extends LabelImpl implements BpmnLabel { protected static AttributeReference<BpmnLabelStyle> labelStyleAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(BpmnLabel.class, BPMNDI_ELEMENT_BPMN_LABEL) .namespaceUri(BPMNDI_NS) .extendsType(Label.class) .instanceProvider(new ModelTypeInstanceProvider<BpmnLabel>() { public BpmnLabel newInstance(ModelTypeInstanceContext instanceContext) { return new BpmnLabelImpl(instanceContext); } }); labelStyleAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_LABEL_STYLE) .qNameAttributeReference(BpmnLabelStyle.class) .build();
typeBuilder.build(); } public BpmnLabelImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public BpmnLabelStyle getLabelStyle() { return labelStyleAttribute.getReferenceTargetElement(this); } public void setLabelStyle(BpmnLabelStyle labelStyle) { labelStyleAttribute.setReferenceTargetElement(this, labelStyle); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\bpmndi\BpmnLabelImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderedArticleLine {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" salesLineId: ").append(toIndentedString(salesLineId)).append("\n"); sb.append(" articleId: ").append(toIndentedString(articleId)).append("\n"); sb.append(" articleCustomerNumber: ").append(toIndentedString(articleCustomerNumber)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" duration: ").append(toIndentedString(duration)).append("\n"); sb.append(" isRentalEquipment: ").append(toIndentedString(isRentalEquipment)).append("\n"); sb.append(" isPrivateSale: ").append(toIndentedString(isPrivateSale)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}");
return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderedArticleLine.java
2
请在Spring Boot框架中完成以下Java代码
public class ServiceRepairProjectConsumptionSummary { @Value @Builder public static class GroupingKey { @NonNull ProjectId projectId; @NonNull ProductId productId; @NonNull UomId uomId; } @NonNull GroupingKey groupingKey; @NonNull Quantity qtyReserved; @NonNull Quantity qtyConsumed; public static GroupingKey extractGroupingKey(@NonNull final AddQtyToProjectTaskRequest request) { return GroupingKey.builder() .projectId(request.getTaskId().getProjectId()) .productId(request.getProductId()) .uomId(request.getUomId()) .build(); } public ServiceRepairProjectConsumptionSummary reduce(@NonNull final AddQtyToProjectTaskRequest request) {
Check.assumeEquals(groupingKey.getProjectId(), request.getTaskId().getProjectId(), "projectId not matching: {}, {}", this, request); return toBuilder() .qtyReserved(getQtyReserved().add(request.getQtyReserved())) .qtyConsumed(getQtyConsumed().add(request.getQtyConsumed())) .build(); } public ServiceRepairProjectConsumptionSummary combine(@NonNull final ServiceRepairProjectConsumptionSummary other) { Check.assumeEquals(groupingKey, other.groupingKey, "groupingKey not matching: {}, {}", this, other); return toBuilder() .qtyReserved(getQtyReserved().add(other.getQtyReserved())) .qtyConsumed(getQtyConsumed().add(other.getQtyConsumed())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\model\ServiceRepairProjectConsumptionSummary.java
2
请在Spring Boot框架中完成以下Java代码
public MessageSource<File> fileReadingMessageSource() { FileReadingMessageSource sourceReader = new FileReadingMessageSource(); sourceReader.setDirectory(new File(INPUT_DIR)); sourceReader.setFilter(new SimplePatternFileListFilter(FILE_PATTERN)); return sourceReader; } @ServiceActivator(inputChannel = "fileChannel") public void processFile(Message<File> message) throws IOException { securityUtil.logInAs("system"); File payload = message.getPayload(); logger.info(">>> Processing file: " + payload.getName()); String content = FileUtils.readFileToString(payload, "UTF-8"); SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH:mm:ss"); logger.info("> Processing content: " + content + " at " + formatter.format(new Date())); ProcessInstance processInstance = processRuntime.start( ProcessPayloadBuilder.start() .withProcessDefinitionKey("categorizeProcess") .withName("Processing Content: " + content) .withVariable("content", content) .build() ); logger.info(">>> Created Process Instance: " + processInstance); logger.info(">>> Deleting processed file: " + payload.getName()); payload.delete(); } @Bean public Connector processTextConnector() { return integrationContext -> { Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables(); String contentToProcess = (String) inBoundVariables.get("content"); // Logic Here to decide if content is approved or not if (contentToProcess.contains("activiti")) { logger.info("> Approving content: " + contentToProcess);
integrationContext.addOutBoundVariable("approved", true); } else { logger.info("> Discarding content: " + contentToProcess); integrationContext.addOutBoundVariable("approved", false); } return integrationContext; }; } @Bean public Connector tagTextConnector() { return integrationContext -> { String contentToTag = (String) integrationContext.getInBoundVariables().get("content"); contentToTag += " :) "; integrationContext.addOutBoundVariable("content", contentToTag); logger.info("Final Content: " + contentToTag); return integrationContext; }; } @Bean public Connector discardTextConnector() { return integrationContext -> { String contentToDiscard = (String) integrationContext.getInBoundVariables().get("content"); contentToDiscard += " :( "; integrationContext.addOutBoundVariable("content", contentToDiscard); logger.info("Final Content: " + contentToDiscard); return integrationContext; }; } }
repos\Activiti-develop\activiti-examples\activiti-api-spring-integration-example\src\main\java\org\activiti\examples\DemoApplication.java
2
请在Spring Boot框架中完成以下Java代码
public FilterRegistrationBean<CorsFilter> corsFilter() { // 创建 UrlBasedCorsConfigurationSource 配置源,类似 CorsRegistry 注册表 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 创建 CorsConfiguration 配置,相当于 CorsRegistration 注册信息 CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Collections.singletonList("*")); // 允许所有请求来源 config.setAllowCredentials(true); // 允许发送 Cookie config.addAllowedMethod("*"); // 允许所有请求 Method config.setAllowedHeaders(Collections.singletonList("*")); // 允许所有请求 Header // config.setExposedHeaders(Collections.singletonList("*")); // 允许所有响应 Header config.setMaxAge(1800L); // 有效期 1800 秒,2 小时 source.registerCorsConfiguration("/**", config); // 创建 FilterRegistrationBean 对象 FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>( new CorsFilter(source)); // 创建 CorsFilter 过滤器 bean.setOrder(0); // 设置 order 排序。这个顺序很重要哦,为避免麻烦请设置在最前 return bean; } // @Override // public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // // 增加 XML 消息转换器 // Jackson2ObjectMapperBuilder xmlBuilder = Jackson2ObjectMapperBuilder.xml(); // xmlBuilder.indentOutput(true); // converters.add(new MappingJackson2XmlHttpMessageConverter(xmlBuilder.build())); // } // @Override // public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // // 增加 XML 消息转换器 // Jackson2ObjectMapperBuilder xmlBuilder = Jackson2ObjectMapperBuilder.xml(); // xmlBuilder.indentOutput(true); // converters.add(new MappingJackson2XmlHttpMessageConverter(xmlBuilder.build())); // }
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // 创建 FastJsonHttpMessageConverter 对象 FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); // 自定义 FastJson 配置 FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setCharset(Charset.defaultCharset()); // 设置字符集 fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect); // 剔除循环引用 fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); // 设置支持的 MediaType fastJsonHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON_UTF8)); // 添加到 converters 中 converters.add(0, fastJsonHttpMessageConverter); // 注意,添加到最开头,放在 MappingJackson2XmlHttpMessageConverter 前面 } }
repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-02\src\main\java\cn\iocoder\springboot\lab23\springmvc\config\SpringMVCConfiguration.java
2
请完成以下Java代码
public String usingSize(Model model) { model.addAttribute("myList", getColors()); return "lists/size"; } @GetMapping("/isEmpty") public String usingIsEmpty(Model model) { model.addAttribute("myList", getColors()); return "lists/isEmpty"; } @GetMapping("/sort") public String usingSort(Model model) { model.addAttribute("myList", getColors()); model.addAttribute("reverse", Comparator.reverseOrder()); return "lists/sort"; }
private List<String> getColors() { List<String> colors = new ArrayList<>(); colors.add("green"); colors.add("yellow"); colors.add("red"); colors.add("blue"); return colors; } private List<String> getOtherColors() { List<String> colors = new ArrayList<>(); colors.add("green"); colors.add("blue"); return colors; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-2\src\main\java\com\baeldung\thymeleaf\lists\ListsController.java
1
请完成以下Java代码
public static DocumentFilter createFilter(@NonNull final Collection<HuId> huIds) { final HUIdsFilterData filterData = HUIdsFilterData.ofHUIds(huIds); return DocumentFilter.singleParameterFilter(FILTER_ID, FILTER_PARAM_Data, Operator.EQUAL, filterData); } public static DocumentFilter createFilter(@NonNull final IHUQueryBuilder huQuery) { final HUIdsFilterData filterData = HUIdsFilterData.ofHUQuery(huQuery); return DocumentFilter.singleParameterFilter(FILTER_ID, FILTER_PARAM_Data, Operator.EQUAL, filterData); } public static DocumentFilter createFilter(@NonNull final HUIdsFilterData filterData) { return DocumentFilter.singleParameterFilter(FILTER_ID, FILTER_PARAM_Data, Operator.EQUAL, filterData); } static HUIdsFilterData extractFilterData(@NonNull final DocumentFilter huIdsFilter) { if (isNotHUIdsFilter(huIdsFilter)) { throw new AdempiereException("Not an HUIds filter: " + huIdsFilter);
} final HUIdsFilterData huIdsFilterData = (HUIdsFilterData)huIdsFilter.getParameter(FILTER_PARAM_Data).getValue(); if (huIdsFilterData == null) { throw new AdempiereException("No " + HUIdsFilterData.class + " found for " + huIdsFilter); } return huIdsFilterData; } public static Optional<HUIdsFilterData> extractFilterData(@Nullable final DocumentFilterList filters) { return findExisting(filters).map(HUIdsFilterHelper::extractFilterData); } public static boolean isNotHUIdsFilter(final DocumentFilter filter) { return !FILTER_ID.equals(filter.getFilterId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterHelper.java
1
请完成以下Java代码
public Boolean convertFrom(final Object valueObj, final ExpressionContext options) { if (valueObj == null) { return null; } final Boolean defaultValue = null; return DisplayType.toBoolean(valueObj, defaultValue); } } private static final class NullExpression extends NullExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { public NullExpression(final Compiler<Boolean, BooleanStringExpression> compiler) { super(compiler); } } private static final class ConstantExpression extends ConstantExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { private ConstantExpression(final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final Boolean constantValue) { super(ExpressionContext.EMPTY, compiler, expressionStr, constantValue); } } private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { private SingleParameterExpression(final ExpressionContext context, final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final CtxName parameter) { super(context, compiler, expressionStr, parameter); } @Override
protected Boolean extractParameterValue(Evaluatee ctx) { return parameter.getValueAsBoolean(ctx); } } private static final class GeneralExpression extends GeneralExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { private GeneralExpression(final ExpressionContext context, final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks) { super(context, compiler, expressionStr, expressionChunks); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\BooleanStringExpressionSupport.java
1
请完成以下Java代码
public OAuth2AccessToken getAccessToken() { return this.accessToken; } /** * Returns the {@link OAuth2RefreshToken refresh token} credential granted. * @return the {@link OAuth2RefreshToken} */ public OAuth2RefreshToken getRefreshToken() { return this.refreshToken; } /** * Returns the scope(s) to request. * @return the scope(s) to request */ public Set<String> getScopes() { return this.scopes; } /** * Populate default parameters for the Refresh Token Grant.
* @param grantRequest the authorization grant request * @return a {@link MultiValueMap} of the parameters used in the OAuth 2.0 Access * Token Request body */ static MultiValueMap<String, String> defaultParameters(OAuth2RefreshTokenGrantRequest grantRequest) { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); if (!CollectionUtils.isEmpty(grantRequest.getScopes())) { parameters.set(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(grantRequest.getScopes(), " ")); } parameters.set(OAuth2ParameterNames.REFRESH_TOKEN, grantRequest.getRefreshToken().getTokenValue()); return parameters; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\endpoint\OAuth2RefreshTokenGrantRequest.java
1
请在Spring Boot框架中完成以下Java代码
public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @ApiModelProperty(example = "oneTaskProcess") public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } @ApiModelProperty(example = "myProcessInstanceName") public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "myBusinessKey") public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } @ApiModelProperty(example = "newOrderMessage") public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "tenant1") public String getTenantId() { return tenantId; } @ApiModelProperty(example = "overrideTenant1") public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; }
public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) { this.overrideDefinitionTenantId = overrideDefinitionTenantId; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getTransientVariables() { return transientVariables; } public void setTransientVariables(List<RestVariable> transientVariables) { this.transientVariables = transientVariables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getStartFormVariables() { return startFormVariables; } public void setStartFormVariables(List<RestVariable> startFormVariables) { this.startFormVariables = startFormVariables; } public String getOutcome() { return outcome; } public void setOutcome(String outcome) { this.outcome = outcome; } @JsonIgnore public boolean isTenantSet() { return tenantId != null && !StringUtils.isEmpty(tenantId); } // Added by Ryan Johnston public boolean getReturnVariables() { return returnVariables; } // Added by Ryan Johnston public void setReturnVariables(boolean returnVariables) { this.returnVariables = returnVariables; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceCreateRequest.java
2
请完成以下Java代码
final public I_C_BPartner importRecord(@NonNull final I_I_Pharma_BPartner importRecord) { final I_C_BPartner bpartner; if (importRecord.getC_BPartner_ID() <= 0) // Insert new BPartner { bpartner = createNewBPartner(importRecord); } else { bpartner = updateExistingBPartner(importRecord); } save(bpartner); importRecord.setC_BPartner(bpartner); return bpartner; } private I_C_BPartner createNewBPartner(@NonNull final I_I_Pharma_BPartner importRecord) { final I_C_BPartner bpartner = InterfaceWrapperHelper.newInstance(I_C_BPartner.class); bpartner.setAD_Org_ID(importRecord.getAD_Org_ID()); bpartner.setCompanyName(extractCompanyName(importRecord)); bpartner.setIsCompany(true); bpartner.setName(extractCompanyName(importRecord)); bpartner.setName2(importRecord.getb00name2()); bpartner.setName3(importRecord.getb00name3()); bpartner.setIFA_Manufacturer(importRecord.getb00adrnr()); bpartner.setDescription("IFA " + importRecord.getb00adrnr()); bpartner.setIsManufacturer(true); bpartner.setURL(importRecord.getb00homepag()); return bpartner; } private String extractCompanyName(@NonNull final I_I_Pharma_BPartner importRecord) { if (!Check.isEmpty(importRecord.getb00name1(), true)) { return importRecord.getb00name1(); } if (!Check.isEmpty(importRecord.getb00email(), true)) { return importRecord.getb00email(); }
if (!Check.isEmpty(importRecord.getb00email2(), true)) { return importRecord.getb00email2(); } return importRecord.getb00adrnr(); } private I_C_BPartner updateExistingBPartner(@NonNull final I_I_Pharma_BPartner importRecord) { final I_C_BPartner bpartner; bpartner = InterfaceWrapperHelper.create(importRecord.getC_BPartner(), I_C_BPartner.class); if (!Check.isEmpty(importRecord.getb00name1(), true)) { bpartner.setIsCompany(true); bpartner.setCompanyName(importRecord.getb00name1()); bpartner.setName(importRecord.getb00name1()); } if (!Check.isEmpty(importRecord.getb00name2())) { bpartner.setName2(importRecord.getb00name2()); } if (!Check.isEmpty(importRecord.getb00name3())) { bpartner.setName3(importRecord.getb00name3()); } if (!Check.isEmpty(importRecord.getb00adrnr())) { bpartner.setIFA_Manufacturer(importRecord.getb00adrnr()); bpartner.setDescription("IFA " + importRecord.getb00adrnr()); } bpartner.setIsManufacturer(true); if (!Check.isEmpty(importRecord.getb00homepag())) { bpartner.setURL(importRecord.getb00homepag()); } return bpartner; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\bpartner\IFABPartnerImportHelper.java
1
请完成以下Java代码
public static void usingCompletableFuture() throws InterruptedException, ExecutionException, Exception { CompletableFuture<Void> completableFuture = hello() .thenComposeAsync(hello -> mergeWorld(hello)) .thenAcceptAsync(helloWorld -> print(helloWorld)) .exceptionally( throwable -> { System.out.println(throwable.getCause()); return null; }); completableFuture.get(); } public static CompletableFuture<String> hello() { CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); return completableFuture; } public static CompletableFuture<String> mergeWorld(String s) { CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { return s + " World!"; }); return completableFuture;
} public static void print(String str) { CompletableFuture.runAsync(() -> System.out.println(str)); } private static void usingAsyncAwait() { try { String hello = await(hello()); String helloWorld = await(mergeWorld(hello)); await(CompletableFuture.runAsync(() -> print(helloWorld))); } catch (Exception e) { e.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\async\EAAsyncExample.java
1
请完成以下Java代码
public IQueryBuilderOrderByClause<ModelType> addColumn(String columnName) { orderByBuilder.addColumn(columnName); return this; } @Override public IQueryBuilderOrderByClause<ModelType> addColumn(ModelColumn<ModelType, ?> column) { orderByBuilder.addColumn(column); return this; } @Override public IQueryBuilderOrderByClause<ModelType> addColumnAscending(String columnName) { orderByBuilder.addColumnAscending(columnName); return this; } @Override public IQueryBuilderOrderByClause<ModelType> addColumnDescending(String columnName) { orderByBuilder.addColumnDescending(columnName); return this;
} @Override public IQueryBuilderOrderByClause<ModelType> addColumn(String columnName, Direction direction, Nulls nulls) { orderByBuilder.addColumn(columnName, direction, nulls); return this; } @Override public IQueryBuilderOrderByClause<ModelType> addColumn(ModelColumn<ModelType, ?> column, Direction direction, Nulls nulls) { orderByBuilder.addColumn(column, direction, nulls); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryBuilderOrderByClause.java
1
请完成以下Java代码
public BigDecimal toBigDecimalAssumingUOM(@NonNull final UomId uomId) { assertUOMOrSourceUOM(uomId); return getUomId().equals(uomId) ? toBigDecimal() : getSourceQty(); } public List<Quantity> spreadEqually(final int count) { if (count <= 0) { throw new AdempiereException("count shall be greater than zero, but it was " + count); } else if (count == 1) { return ImmutableList.of(this); } else // count > 1 { final ImmutableList.Builder<Quantity> result = ImmutableList.builder(); final Quantity qtyPerPart = divide(count); Quantity qtyRemainingToSpread = this;
for (int i = 1; i <= count; i++) { final boolean isLast = i == count; if (isLast) { result.add(qtyRemainingToSpread); } else { result.add(qtyPerPart); qtyRemainingToSpread = qtyRemainingToSpread.subtract(qtyPerPart); } } return result.build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantity.java
1
请完成以下Java代码
public class HttpServer { private int port; static Logger logger = LoggerFactory.getLogger(HttpServer.class); public HttpServer(int port) { this.port = port; } public static void main(String[] args) throws Exception { int port = args.length > 0 ? Integer.parseInt(args[0]) : 8080; new HttpServer(port).run(); } public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() {
@Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpRequestDecoder()); p.addLast(new HttpResponseEncoder()); p.addLast(new CustomHttpServerHandler()); } }); ChannelFuture f = b.bind(port) .sync(); f.channel() .closeFuture() .sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\http\server\HttpServer.java
1
请完成以下Java代码
public void setWorkingTime (int WorkingTime) { set_Value (COLUMNNAME_WorkingTime, Integer.valueOf(WorkingTime)); } /** Get Working Time. @return Workflow Simulation Execution Time */ @Override public int getWorkingTime () { Integer ii = (Integer)get_Value(COLUMNNAME_WorkingTime); if (ii == null) return 0; return ii.intValue(); } /** Set Yield %. @param Yield The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override
public void setYield (int Yield) { set_Value (COLUMNNAME_Yield, Integer.valueOf(Yield)); } /** Get Yield %. @return The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public int getYield () { Integer ii = (Integer)get_Value(COLUMNNAME_Yield); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Workflow.java
1
请完成以下Java代码
public class EntitiesRelatedDeviceIdAsyncLoader { public static ListenableFuture<DeviceId> findDeviceAsync( TbContext ctx, EntityId originator, DeviceRelationsQuery deviceRelationsQuery ) { var deviceService = ctx.getDeviceService(); var query = buildQuery(originator, deviceRelationsQuery); var devicesListFuture = deviceService.findDevicesByQuery(ctx.getTenantId(), query); return Futures.transformAsync(devicesListFuture, deviceList -> CollectionUtils.isNotEmpty(deviceList) ? Futures.immediateFuture(deviceList.get(0).getId()) : Futures.immediateFuture(null), ctx.getDbCallbackExecutor()); }
private static DeviceSearchQuery buildQuery(EntityId originator, DeviceRelationsQuery deviceRelationsQuery) { var query = new DeviceSearchQuery(); var parameters = new RelationsSearchParameters( originator, deviceRelationsQuery.getDirection(), deviceRelationsQuery.getMaxLevel(), deviceRelationsQuery.isFetchLastLevelOnly() ); query.setParameters(parameters); query.setRelationType(deviceRelationsQuery.getRelationType()); query.setDeviceTypes(deviceRelationsQuery.getDeviceTypes()); return query; } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\util\EntitiesRelatedDeviceIdAsyncLoader.java
1
请在Spring Boot框架中完成以下Java代码
public class Frequency { FrequencyType type; int everyNthWeek; ImmutableSet<DayOfWeek> onlyDaysOfWeek; int everyNthMonth; ImmutableSet<Integer> onlyDaysOfMonth; @Builder private Frequency( @NonNull final FrequencyType type, final int everyNthWeek, @Singular("onlyDayOfWeek") final Set<DayOfWeek> onlyDaysOfWeek, final int everyNthMonth, @Singular("onlyDayOfMonth") final Set<Integer> onlyDaysOfMonth) { this.type = type; if (type == FrequencyType.Weekly) { Check.assumeGreaterThanZero(everyNthWeek, "everyNthWeek"); this.everyNthWeek = everyNthWeek; this.onlyDaysOfWeek = ImmutableSet.copyOf(onlyDaysOfWeek); this.everyNthMonth = 1; this.onlyDaysOfMonth = ImmutableSet.of(); } else if (type == FrequencyType.Monthly) { this.everyNthWeek = 1; this.onlyDaysOfWeek = ImmutableSet.of(); Check.assumeGreaterThanZero(everyNthMonth, "everyNthMonth"); this.everyNthMonth = everyNthMonth; Check.assumeNotEmpty(onlyDaysOfMonth, "onlyDaysOfMonth is not empty"); this.onlyDaysOfMonth = ImmutableSet.copyOf(onlyDaysOfMonth); } else
{ throw new IllegalArgumentException("Unknow " + FrequencyType.class + ": " + type); } } public boolean isWeekly() { return type == FrequencyType.Weekly; } public boolean isMonthly() { return type == FrequencyType.Monthly; } public boolean isOnlySomeDaysOfTheWeek() { return !onlyDaysOfWeek.isEmpty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\Frequency.java
2
请完成以下Java代码
public List<DataSpec> getDataOutputs() { return dataOutputs; } public void setDataOutputs(List<DataSpec> dataOutputs) { this.dataOutputs = dataOutputs; } public List<String> getDataInputRefs() { return dataInputRefs; } public void setDataInputRefs(List<String> dataInputRefs) { this.dataInputRefs = dataInputRefs; } public List<String> getDataOutputRefs() { return dataOutputRefs; } public void setDataOutputRefs(List<String> dataOutputRefs) { this.dataOutputRefs = dataOutputRefs; } public IOSpecification clone() { IOSpecification clone = new IOSpecification();
clone.setValues(this); return clone; } public void setValues(IOSpecification otherSpec) { dataInputs = new ArrayList<DataSpec>(); if (otherSpec.getDataInputs() != null && !otherSpec.getDataInputs().isEmpty()) { for (DataSpec dataSpec : otherSpec.getDataInputs()) { dataInputs.add(dataSpec.clone()); } } dataOutputs = new ArrayList<DataSpec>(); if (otherSpec.getDataOutputs() != null && !otherSpec.getDataOutputs().isEmpty()) { for (DataSpec dataSpec : otherSpec.getDataOutputs()) { dataOutputs.add(dataSpec.clone()); } } dataInputRefs = new ArrayList<String>(otherSpec.getDataInputRefs()); dataOutputRefs = new ArrayList<String>(otherSpec.getDataOutputRefs()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\IOSpecification.java
1
请完成以下Java代码
public static String getTargetTelemetryKey(OtaPackageType type, OtaPackageKey key) { return getTelemetryKey("target_", type, key); } public static String getCurrentTelemetryKey(OtaPackageType type, OtaPackageKey key) { return getTelemetryKey("current_", type, key); } private static String getTelemetryKey(String prefix, OtaPackageType type, OtaPackageKey key) { return prefix + type.getKeyPrefix() + "_" + key.getValue(); } public static String getTelemetryKey(OtaPackageType type, OtaPackageKey key) { return type.getKeyPrefix() + "_" + key.getValue(); } public static OtaPackageId getOtaPackageId(HasOtaPackage entity, OtaPackageType type) { switch (type) { case FIRMWARE: return entity.getFirmwareId(); case SOFTWARE: return entity.getSoftwareId(); default:
log.warn("Unsupported ota package type: [{}]", type); return null; } } public static <T> T getByOtaPackageType(Supplier<T> firmwareSupplier, Supplier<T> softwareSupplier, OtaPackageType type) { switch (type) { case FIRMWARE: return firmwareSupplier.get(); case SOFTWARE: return softwareSupplier.get(); default: throw new RuntimeException("Unsupported OtaPackage type: " + type); } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\ota\OtaPackageUtil.java
1
请完成以下Java代码
public void afterPropertiesSet() { Assert.hasLength(this.realmName, "realmName must be specified"); Assert.hasLength(this.key, "key must be specified"); } @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { // compute a nonce (do not use remote IP address due to proxy farms) format of // nonce is: base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key)) long expiryTime = System.currentTimeMillis() + (this.nonceValiditySeconds * 1000); String signatureValue = DigestAuthUtils.md5Hex(expiryTime + ":" + this.key); String nonceValue = expiryTime + ":" + signatureValue; String nonceValueBase64 = new String(Base64.getEncoder().encode(nonceValue.getBytes())); // qop is quality of protection, as defined by RFC 2617. We do not use opaque due // to IE violation of RFC 2617 in not representing opaque on subsequent requests // in same session. String authenticateHeader = "Digest realm=\"" + this.realmName + "\", " + "qop=\"auth\", nonce=\"" + nonceValueBase64 + "\""; if (authException instanceof NonceExpiredException) { authenticateHeader = authenticateHeader + ", stale=\"true\""; } logger.debug(LogMessage.format("WWW-Authenticate header sent to user agent: %s", authenticateHeader)); response.addHeader("WWW-Authenticate", authenticateHeader); response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()); } public @Nullable String getKey() { return this.key; } public int getNonceValiditySeconds() { return this.nonceValiditySeconds; } public @Nullable String getRealmName() {
return this.realmName; } public void setKey(String key) { this.key = key; } public void setNonceValiditySeconds(int nonceValiditySeconds) { this.nonceValiditySeconds = nonceValiditySeconds; } public void setRealmName(String realmName) { this.realmName = realmName; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\www\DigestAuthenticationEntryPoint.java
1
请完成以下Java代码
public void setPlannedAmt (final BigDecimal PlannedAmt) { set_Value (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPriceActual (final @Nullable BigDecimal PriceActual) { set_Value (COLUMNNAME_PriceActual, PriceActual); } @Override public BigDecimal getPriceActual() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceActual); return bd != null ? bd : BigDecimal.ZERO; } /** * ProjInvoiceRule AD_Reference_ID=383 * Reference name: C_Project InvoiceRule */ public static final int PROJINVOICERULE_AD_Reference_ID=383; /** None = - */ public static final String PROJINVOICERULE_None = "-"; /** Committed Amount = C */ public static final String PROJINVOICERULE_CommittedAmount = "C"; /** Time&Material max Comitted = c */ public static final String PROJINVOICERULE_TimeMaterialMaxComitted = "c"; /** Time&Material = T */ public static final String PROJINVOICERULE_TimeMaterial = "T"; /** Product Quantity = P */ public static final String PROJINVOICERULE_ProductQuantity = "P"; @Override public void setProjInvoiceRule (final java.lang.String ProjInvoiceRule) { set_Value (COLUMNNAME_ProjInvoiceRule, ProjInvoiceRule); } @Override public java.lang.String getProjInvoiceRule() {
return get_ValueAsString(COLUMNNAME_ProjInvoiceRule); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStartDate (final @Nullable java.sql.Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } @Override public java.sql.Timestamp getStartDate() { return get_ValueAsTimestamp(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectPhase.java
1
请完成以下Java代码
private void setWeightFromLines(@NonNull final List<OrderId> orderIds) { orderBL.getByIds(orderIds) .forEach(order -> { orderBL.setWeightFromLines(order); saveRecord(order); }); } private void normalizeProductCodeFields(@NonNull I_M_Product record) { if (InterfaceWrapperHelper.isValueChanged(record, I_M_Product.COLUMNNAME_GTIN)) { final GTIN gtin = GTIN.ofNullableString(record.getGTIN());
productBL.setProductCodeFieldsFromGTIN(record, gtin); } // NOTE: syncing UPC to GTIN is not quite correct, but we have a lot of BPs which are relying on this logic else if (InterfaceWrapperHelper.isValueChanged(record, I_M_Product.COLUMNNAME_UPC)) { final GTIN gtin = GTIN.ofNullableString(record.getUPC()); productBL.setProductCodeFieldsFromGTIN(record, gtin); } else if (InterfaceWrapperHelper.isValueChanged(record, I_M_Product.COLUMNNAME_EAN13_ProductCode)) { final EAN13ProductCode ean13ProductCode = EAN13ProductCode.ofNullableString(record.getEAN13_ProductCode()); productBL.setProductCodeFieldsFromEAN13ProductCode(record, ean13ProductCode); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\model\interceptor\M_Product.java
1
请在Spring Boot框架中完成以下Java代码
class PropertiesRestClientHttpServiceGroupConfigurer implements RestClientHttpServiceGroupConfigurer { /** * The default order for the PropertiesRestClientHttpServiceGroupConfigurer. */ private static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 10; private final HttpServiceClientProperties properties; private final HttpClientSettingsPropertyMapper clientSettingsPropertyMapper; private final ClientHttpRequestFactoryBuilder<?> requestFactoryBuilder; PropertiesRestClientHttpServiceGroupConfigurer(@Nullable ClassLoader classLoader, HttpServiceClientProperties properties, @Nullable SslBundles sslBundles, ObjectProvider<ClientHttpRequestFactoryBuilder<?>> requestFactoryBuilder, @Nullable HttpClientSettings httpClientSettings) { this.properties = properties; this.clientSettingsPropertyMapper = new HttpClientSettingsPropertyMapper(sslBundles, httpClientSettings); this.requestFactoryBuilder = requestFactoryBuilder .getIfAvailable(() -> ClientHttpRequestFactoryBuilder.detect(classLoader)); } @Override public int getOrder() { return DEFAULT_ORDER; } @Override public void configureGroups(Groups<RestClient.Builder> groups) { groups.forEachClient(this::configureClient); } private void configureClient(HttpServiceGroup group, RestClient.Builder builder) { HttpClientProperties clientProperties = this.properties.get(group.name()); HttpClientSettings clientSettings = this.clientSettingsPropertyMapper.map(clientProperties);
builder.requestFactory(this.requestFactoryBuilder.build(clientSettings)); if (clientProperties != null) { PropertyMapper map = PropertyMapper.get(); map.from(clientProperties::getBaseUrl).whenHasText().to(builder::baseUrl); map.from(clientProperties::getDefaultHeader).as(this::putAllHeaders).to(builder::defaultHeaders); map.from(clientProperties::getApiversion) .as(ApiversionProperties::getDefaultVersion) .to(builder::defaultApiVersion); map.from(clientProperties::getApiversion) .as(ApiversionProperties::getInsert) .as(PropertiesApiVersionInserter::get) .to(builder::apiVersionInserter); } } private Consumer<HttpHeaders> putAllHeaders(Map<String, List<String>> defaultHeaders) { return (httpHeaders) -> httpHeaders.putAll(defaultHeaders); } }
repos\spring-boot-4.0.1\module\spring-boot-restclient\src\main\java\org\springframework\boot\restclient\autoconfigure\service\PropertiesRestClientHttpServiceGroupConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public class Author implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String genre; private int age; @OneToMany(cascade = CascadeType.ALL, mappedBy = "author", orphanRemoval = true) private List<Book> books = new ArrayList<>(); @OneToMany(cascade = CascadeType.ALL, mappedBy = "author", orphanRemoval = true) @Where(clause = "price <= 20") private List<Book> cheapBooks = new ArrayList<>(); @OneToMany(cascade = CascadeType.ALL, mappedBy = "author", orphanRemoval = true) @Where(clause = "price > 20") private List<Book> restOfBooks = new ArrayList<>(); public void addBook(Book book) { this.books.add(book); book.setAuthor(this); } public void removeBook(Book book) { book.setAuthor(null); this.books.remove(book); } public void removeBooks() { Iterator<Book> iterator = this.books.iterator(); while (iterator.hasNext()) { Book book = iterator.next(); book.setAuthor(null); iterator.remove(); } } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Book> getCheapBooks() { return cheapBooks; } public void setCheapBooks(List<Book> cheapBooks) { this.cheapBooks = cheapBooks; } public List<Book> getRestOfBooks() { return restOfBooks; } public void setRestOfBooks(List<Book> restOfBooks) { this.restOfBooks = restOfBooks; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFilterAssociation\src\main\java\com\bookstore\entity\Author.java
2
请在Spring Boot框架中完成以下Java代码
public class ViewRowIdsSelection { public static ViewRowIdsSelection of(@NonNull final ViewId viewId, final DocumentIdsSelection rowIds) { return new ViewRowIdsSelection(viewId, rowIds); } public static ViewRowIdsSelection of(@NonNull final ViewId viewId, final Set<String> rowIdsStringSet) { final DocumentIdsSelection rowIds = DocumentIdsSelection.ofStringSet(rowIdsStringSet); return of(viewId, rowIds); } public static ViewRowIdsSelection ofNullableStrings(final String viewIdStr, final String rowIdsListStr) { if (viewIdStr == null || viewIdStr.isEmpty()) { return null; } final ViewId viewId = ViewId.ofViewIdString(viewIdStr); final DocumentIdsSelection rowIds = DocumentIdsSelection.ofCommaSeparatedString(rowIdsListStr); return new ViewRowIdsSelection(viewId, rowIds); } public static ViewRowIdsSelection ofNullableStrings(String viewIdStr, Set<String> rowIdsStringSet) { if (viewIdStr == null || viewIdStr.isEmpty())
{ return null; } final ViewId viewId = ViewId.ofViewIdString(viewIdStr); final DocumentIdsSelection rowIds = DocumentIdsSelection.ofStringSet(rowIdsStringSet); return new ViewRowIdsSelection(viewId, rowIds); } ViewId viewId; DocumentIdsSelection rowIds; private ViewRowIdsSelection(@NonNull final ViewId viewId, final DocumentIdsSelection rowIds) { this.viewId = viewId; this.rowIds = rowIds != null ? rowIds : DocumentIdsSelection.EMPTY; } public boolean isEmpty() { return rowIds.isEmpty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowIdsSelection.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable String getReadFrom() { return this.readFrom; } public void setReadFrom(@Nullable String readFrom) { this.readFrom = readFrom; } public Pool getPool() { return this.pool; } public Cluster getCluster() { return this.cluster; } public static class Cluster { private final Refresh refresh = new Refresh(); public Refresh getRefresh() { return this.refresh; } public static class Refresh { /** * Whether to discover and query all cluster nodes for obtaining the * cluster topology. When set to false, only the initial seed nodes are * used as sources for topology discovery. */ private boolean dynamicRefreshSources = true; /** * Cluster topology refresh period. */ private @Nullable Duration period; /** * Whether adaptive topology refreshing using all available refresh * triggers should be used.
*/ private boolean adaptive; public boolean isDynamicRefreshSources() { return this.dynamicRefreshSources; } public void setDynamicRefreshSources(boolean dynamicRefreshSources) { this.dynamicRefreshSources = dynamicRefreshSources; } public @Nullable Duration getPeriod() { return this.period; } public void setPeriod(@Nullable Duration period) { this.period = period; } public boolean isAdaptive() { return this.adaptive; } public void setAdaptive(boolean adaptive) { this.adaptive = adaptive; } } } } }
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisProperties.java
2
请完成以下Java代码
private static class BatchToPrintCollector { private final HULabelConfigProvider labelConfigProvider; @Getter private final ArrayList<BatchToPrint> batches = new ArrayList<>(); private final HashSet<HuId> huIdsCollected = new HashSet<>(); private BatchToPrintCollector(final HULabelConfigProvider huLabelConfigProvider) { this.labelConfigProvider = huLabelConfigProvider; } public void addAllRecursive(@NonNull final List<HUToReport> hus) { for (final HUToReport hu : hus) { add(hu, labelConfigProvider.getLabelConfig(hu)); final HuUnitType huUnitType = hu.getHUUnitType(); if (huUnitType == HuUnitType.LU) { for (final HUToReport includedHU : hu.getIncludedHUs()) { add(includedHU, labelConfigProvider.getLabelConfig(includedHU)); } } } } public void add(@NonNull final HUToReport hu, @NonNull final HULabelConfig labelConfig) { // Don't add it if we already considered it if (!huIdsCollected.add(hu.getHUId())) { return; } final BatchToPrint lastBatch = !batches.isEmpty() ? batches.get(batches.size() - 1) : null; final BatchToPrint batch; if (lastBatch == null || !lastBatch.isMatching(labelConfig)) { batch = new BatchToPrint(labelConfig.getPrintFormatProcessId()); batches.add(batch); } else { batch = lastBatch; } batch.addHU(hu); } public void forEach(@NonNull final Consumer<BatchToPrint> action)
{ batches.forEach(action); } } @Getter private static class BatchToPrint { @NonNull private final AdProcessId printFormatProcessId; @NonNull private final ArrayList<HUToReport> hus = new ArrayList<>(); private BatchToPrint(final @NonNull AdProcessId printFormatProcessId) { this.printFormatProcessId = printFormatProcessId; } public boolean isMatching(@NonNull final HULabelConfig labelConfig) { return AdProcessId.equals(printFormatProcessId, labelConfig.getPrintFormatProcessId()); } public void addHU(@NonNull final HUToReport hu) { this.hus.add(hu); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\printReceivedHUQRCodes\PrintReceivedHUQRCodesActivityHandler.java
1
请完成以下Java代码
public static Optional<HUPIItemProductId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));} public static int toRepoId(@Nullable final HUPIItemProductId id) { return id != null ? id.getRepoId() : -1; } public static int toRepoIdVirtualToZero(@Nullable final HUPIItemProductId id) { return id != null && !id.isVirtualHU() ? id.getRepoId() : -1; } public static boolean isRegular(@Nullable final HUPIItemProductId id) { return id != null && id.isRegular(); } public static final HUPIItemProductId TEMPLATE_HU = new HUPIItemProductId(100); public static final HUPIItemProductId VIRTUAL_HU = new HUPIItemProductId(101); int repoId; private HUPIItemProductId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Item_Product_ID"); } @JsonValue @Override public int getRepoId()
{ return repoId; } public static boolean equals(@Nullable final HUPIItemProductId id1, @Nullable final HUPIItemProductId id2) { return Objects.equals(id1, id2); } public static HUPIItemProductId nullToVirtual(final HUPIItemProductId id) { return id != null ? id : VIRTUAL_HU; } public boolean isVirtualHU() { return isVirtualHU(repoId); } public static boolean isVirtualHU(final int repoId) { return repoId == VIRTUAL_HU.repoId; } public boolean isRegular() { return repoId != VIRTUAL_HU.repoId && repoId != TEMPLATE_HU.repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HUPIItemProductId.java
1
请在Spring Boot框架中完成以下Java代码
public class PurchaseCandidateRestController { private final ITrxManager trxManager = Services.get(ITrxManager.class); private final CreatePurchaseCandidatesService createPurchaseCandidatesService; private final EnqueuePurchaseCandidateService enqueuePurchaseCandidateService; private final PurchaseCandidatesStatusService purchaseCandidatesStatusService; public PurchaseCandidateRestController(final CreatePurchaseCandidatesService createPurchaseCandidatesService, final EnqueuePurchaseCandidateService enqueuePurchaseCandidateService, final PurchaseCandidatesStatusService purchaseCandidatesStatusService) { this.createPurchaseCandidatesService = createPurchaseCandidatesService; this.enqueuePurchaseCandidateService = enqueuePurchaseCandidateService; this.purchaseCandidatesStatusService = purchaseCandidatesStatusService; } @ApiOperation("Create new purchase order candidates") @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully created new purchase order candidate(s)"), @ApiResponse(code = 401, message = "You are not authorized to create new purchase order candidates"), @ApiResponse(code = 403, message = "Accessing a related resource is forbidden"), @ApiResponse(code = 422, message = "The request body could not be processed") }) @PostMapping(path = "/createCandidates", consumes = "application/json", produces = "application/json") public ResponseEntity<JsonPurchaseCandidateResponse> createCandidates(@RequestBody final JsonPurchaseCandidateCreateRequest request) { return ResponseEntity.ok(trxManager.call(ITrx.TRXNAME_ThreadInherited, () -> createCandidates0(request))); } private JsonPurchaseCandidateResponse createCandidates0(@RequestBody final JsonPurchaseCandidateCreateRequest request) { final ImmutableList<JsonPurchaseCandidate> candidates = request.getPurchaseCandidates()
.stream() .map(createPurchaseCandidatesService::createCandidate) .filter(Optional::isPresent) .map(Optional::get) .collect(ImmutableList.toImmutableList()); return JsonPurchaseCandidateResponse.builder() .purchaseCandidates(candidates) .build(); } @ApiOperation("Enqueues purchase candidates for creation of purchase orders") @PostMapping(path = "/enqueueForOrdering", consumes = "application/json", produces = "application/json") public ResponseEntity<String> enqueue(@RequestBody @NonNull final JsonPurchaseCandidatesRequest request) { enqueuePurchaseCandidateService.enqueue(request); return new ResponseEntity<>(HttpStatus.ACCEPTED); } @PutMapping(value = "/status", consumes = "application/json", produces = "application/json") public JsonPurchaseCandidateResponse status(@RequestBody final JsonPurchaseCandidatesRequest request) { return purchaseCandidatesStatusService.getStatusForPurchaseCandidates(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\order\PurchaseCandidateRestController.java
2
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }
public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\java\com\baeldung\customlogouthandler\user\User.java
1
请完成以下Java代码
public boolean isError() { return error != null; } public ResultType getResult() { if (result == null) { throw toException(); } return result; } public ErrorType getError() { if (error == null) { throw new AdempiereException("Not an error response: " + this); } return error; } public AdempiereException toException() { if (error == null)
{ throw new AdempiereException("Not an error response: " + this); } if (errorCause != null) { return AdempiereException.wrapIfNeeded(errorCause) .setParameter("error", error); } else { return new AdempiereException(error.toString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\PayPalClientResponse.java
1
请完成以下Java代码
private static final class ManagedAttributeInfo { private String key; private String description; private Method getter; private Method setter; private ManagedAttributeInfo(String key, String description) { this.key = key; this.description = description; } public String getKey() { return key; } public String getDescription() { return description; } public Method getGetter() { return getter; } public void setGetter(Method getter) { this.getter = getter; } public Method getSetter() { return setter; } public void setSetter(Method setter) { this.setter = setter; } @Override public String toString() { return "ManagedAttributeInfo: [" + key + " + getter: " + getter + ", setter: " + setter + "]"; } } private static final class ManagedOperationInfo {
private final String description; private final Method operation; private ManagedOperationInfo(String description, Method operation) { this.description = description; this.operation = operation; } public String getDescription() { return description; } public Method getOperation() { return operation; } @Override public String toString() { return "ManagedOperationInfo: [" + operation + "]"; } } private static final class MBeanAttributesAndOperations { private Map<String, ManagedAttributeInfo> attributes; private Set<ManagedOperationInfo> operations; } }
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\MBeanInfoAssembler.java
1
请完成以下Java代码
public TbQueueProducer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> getTbEdgeEventsMsgProducer() { return toEdgeEvents; } @Override public TbQueueProducer<TbProtoQueueMsg<ToUsageStatsServiceMsg>> getTbUsageStatsMsgProducer() { return toUsageStats; } @Override public TbQueueProducer<TbProtoQueueMsg<ToVersionControlServiceMsg>> getTbVersionControlMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Rule Engine!"); } @Override
public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> getHousekeeperMsgProducer() { return toHousekeeper; } @Override public TbQueueProducer<TbProtoQueueMsg<ToCalculatedFieldMsg>> getCalculatedFieldsMsgProducer() { return toCalculatedFields; } @Override public TbQueueProducer<TbProtoQueueMsg<ToCalculatedFieldNotificationMsg>> getCalculatedFieldsNotificationsMsgProducer() { return toCalculatedFieldNotifications; } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\TbRuleEngineProducerProvider.java
1
请完成以下Java代码
public void setTitle(String title) { this.title = title; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getBrand() { return brand; }
public void setBrand(String brand) { this.brand = brand; } @Override public String toString() { return "MerchandiseEntity{" + "id=" + id + ", title='" + title + '\'' + ", price=" + price + ", brand='" + brand + '\'' + '}'; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\boot\domain\MerchandiseEntity.java
1
请完成以下Java代码
public class User { private String email; private Double rating; private boolean active; public User() { } public User(String email, Double rating, boolean active) { this.email = email; this.rating = rating; this.active = active; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Double getRating() { return rating; } public void setRating(Double rating) { this.rating = rating; } public boolean isActive() {
return active; } public void setActive(boolean active) { this.active = active; } @Override public String toString() { return "User{" + "email='" + email + '\'' + ", rating=" + rating + ", active=" + active + '}'; } }
repos\Spring-Boot-Advanced-Projects-main\springboot2-jms-activemq\src\main\java\net\alanbinu\springboot\jms\User.java
1
请完成以下Java代码
public void registered(SchedulerDriver schedulerDriver, Protos.FrameworkID frameworkID, Protos.MasterInfo masterInfo) { } @Override public void reregistered(SchedulerDriver schedulerDriver, Protos.MasterInfo masterInfo) { } @Override public void resourceOffers(SchedulerDriver schedulerDriver, List<Offer> list) { for (Offer offer : list) { List<TaskInfo> tasks = new ArrayList<TaskInfo>(); Protos.TaskID taskId = Protos.TaskID.newBuilder().setValue(Integer.toString(launchedTasks++)).build(); System.out.println("Launching printHelloWorld " + taskId.getValue() + " Hello World Java"); TaskInfo printHelloWorld = TaskInfo .newBuilder() .setName("printHelloWorld " + taskId.getValue()) .setTaskId(taskId) .setSlaveId(offer.getSlaveId()) .addResources( Protos.Resource.newBuilder().setName("cpus").setType(Protos.Value.Type.SCALAR) .setScalar(Protos.Value.Scalar.newBuilder().setValue(1))) .addResources( Protos.Resource.newBuilder().setName("mem").setType(Protos.Value.Type.SCALAR) .setScalar(Protos.Value.Scalar.newBuilder().setValue(128))) .setExecutor(ExecutorInfo.newBuilder(helloWorldExecutor)).build(); List<OfferID> offerIDS = new ArrayList<>(); offerIDS.add(offer.getId()); tasks.add(printHelloWorld); schedulerDriver.declineOffer(offer.getId()); schedulerDriver.launchTasks(offerIDS, tasks); } } @Override public void offerRescinded(SchedulerDriver schedulerDriver, OfferID offerID) {
} @Override public void statusUpdate(SchedulerDriver schedulerDriver, Protos.TaskStatus taskStatus) { } @Override public void frameworkMessage(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, byte[] bytes) { } @Override public void disconnected(SchedulerDriver schedulerDriver) { } @Override public void slaveLost(SchedulerDriver schedulerDriver, Protos.SlaveID slaveID) { } @Override public void executorLost(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, int i) { } @Override public void error(SchedulerDriver schedulerDriver, String s) { } }
repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\mesos\schedulers\HelloWorldScheduler.java
1
请在Spring Boot框架中完成以下Java代码
public class StudentJdbcTemplateRepository { private final JdbcTemplate jdbcTemplate; public StudentJdbcTemplateRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } static class StudentRowMapper implements RowMapper<Student> { @Override public Student mapRow(ResultSet rs, int rowNum) throws SQLException { var student = new Student(); student.setId(rs.getLong("id")); student.setName(rs.getString("name")); student.setPassportNumber(rs.getString("passport_number")); return student; } } public List<Student> findAll() { return jdbcTemplate.query(StudentQueries.getAllStudents(), new StudentRowMapper()); } public Student findById(long id) { return jdbcTemplate.queryForObject(StudentQueries.getAllStudentsById(), new BeanPropertyRowMapper<>(Student.class), id);
} public void deleteById(long id) { jdbcTemplate.update(StudentQueries.getDeleteStudentById(), id); } public int insert(Student student) { return jdbcTemplate.update(StudentQueries.getInsertStudent(), student.getId(), student.getName(), student.getPassportNumber()); } public int update(Student student) { return jdbcTemplate.update(StudentQueries.getUpdateStudent(), student.getName(), student.getPassportNumber(), student.getId()); } }
repos\spring-boot-examples-master\spring-boot-2-jdbc-with-h2\src\main\java\com\in28minutes\springboot\jdbc\h2\example\student\StudentJdbcTemplateRepository.java
2
请完成以下Java代码
public class SystemRuleEntity implements RuleEntity { private Long id; private String app; private String ip; private Integer port; private Double highestSystemLoad; private Long avgRt; private Long maxThread; private Double qps; private Double highestCpuUsage; private Date gmtCreate; private Date gmtModified; public static SystemRuleEntity fromSystemRule(String app, String ip, Integer port, SystemRule rule) { SystemRuleEntity entity = new SystemRuleEntity(); entity.setApp(app); entity.setIp(ip); entity.setPort(port); entity.setHighestSystemLoad(rule.getHighestSystemLoad()); entity.setHighestCpuUsage(rule.getHighestCpuUsage()); entity.setAvgRt(rule.getAvgRt()); entity.setMaxThread(rule.getMaxThread()); entity.setQps(rule.getQps()); return entity; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } public Double getHighestSystemLoad() { return highestSystemLoad; } public void setHighestSystemLoad(Double highestSystemLoad) { this.highestSystemLoad = highestSystemLoad; } public Long getAvgRt() { return avgRt; } public void setAvgRt(Long avgRt) { this.avgRt = avgRt; } public Long getMaxThread() { return maxThread;
} public void setMaxThread(Long maxThread) { this.maxThread = maxThread; } public Double getQps() { return qps; } public void setQps(Double qps) { this.qps = qps; } public Double getHighestCpuUsage() { return highestCpuUsage; } public void setHighestCpuUsage(Double highestCpuUsage) { this.highestCpuUsage = highestCpuUsage; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public SystemRule toRule() { SystemRule rule = new SystemRule(); rule.setHighestSystemLoad(highestSystemLoad); rule.setAvgRt(avgRt); rule.setMaxThread(maxThread); rule.setQps(qps); rule.setHighestCpuUsage(highestCpuUsage); return rule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\SystemRuleEntity.java
1
请完成以下Java代码
public static Optional<MediatedCommissionConfig> castOrEmpty(@NonNull final CommissionConfig commissionConfig) { if (commissionConfig instanceof MediatedCommissionConfig) { return Optional.of((MediatedCommissionConfig)commissionConfig); } return Optional.empty(); } public static boolean isInstance(@NonNull final CommissionConfig commissionConfig) { return commissionConfig instanceof MediatedCommissionConfig; } @Override @NonNull public CommissionType getCommissionType() { return CommissionType.MEDIATED_COMMISSION; } @Override public MediatedCommissionContract getContractFor(@NonNull final BPartnerId contractualBPartnerId) { if (contractualBPartnerId.equals(mediatedCommissionContract.getContractOwnerBPartnerId())) { return mediatedCommissionContract; }
return null; } @Override @NonNull public ProductId getCommissionProductId() { return commissionProductId; } @NonNull public MediatedCommissionSettingsId getId() { return mediatedCommissionSettingsLineId.getMediatedCommissionSettingsId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\mediated\algorithm\MediatedCommissionConfig.java
1
请在Spring Boot框架中完成以下Java代码
public final void setMessageNo(final String messageNo) { this.messageNo = messageNo; } public final String getContractValue() { return contractValue; } public final void setContractValue(final String contractValue) { this.contractValue = contractValue; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (contractValue == null ? 0 : contractValue.hashCode()); result = prime * result + (messageNo == null ? 0 : messageNo.hashCode()); result = prime * result + (partner == null ? 0 : partner.hashCode()); result = prime * result + (record == null ? 0 : record.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final T100 other = (T100)obj; if (contractValue == null) { if (other.contractValue != null) { return false; } } else if (!contractValue.equals(other.contractValue)) { return false; } if (messageNo == null) { if (other.messageNo != null) { return false; } } else if (!messageNo.equals(other.messageNo)) { return false; }
if (partner == null) { if (other.partner != null) { return false; } } else if (!partner.equals(other.partner)) { return false; } if (record == null) { if (other.record != null) { return false; } } else if (!record.equals(other.record)) { return false; } return true; } @Override public String toString() { return "T100 [record=" + record + ", partner=" + partner + ", messageNo=" + messageNo + ", contractValue=" + contractValue + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\compudata\T100.java
2
请完成以下Java代码
public PaymentAllocationContext build() { return new PaymentAllocationContext(this); } public Builder setAD_Org_ID(final int AD_Org_ID) { this.AD_Org_ID = AD_Org_ID; return this; } public Builder setC_BPartner_ID(final int bpartnerId) { C_BPartner_ID = bpartnerId; return this; } public Builder setC_Currency_ID(final int C_Currency_ID) { this.C_Currency_ID = C_Currency_ID; return this; } public Builder setMultiCurrency(final boolean multiCurrency) { this.multiCurrency = multiCurrency; return this; } public Builder setDate(final Date date) { this.date = date; return this; } /** * @param allowedWriteOffTypes allowed write-off types, in the same order they were enabled */ public Builder setAllowedWriteOffTypes(final Set<InvoiceWriteOffAmountType> allowedWriteOffTypes) { this.allowedWriteOffTypes.clear(); if (allowedWriteOffTypes != null) { this.allowedWriteOffTypes.addAll(allowedWriteOffTypes); } return this; }
public Builder addAllowedWriteOffType(final InvoiceWriteOffAmountType allowedWriteOffType) { Check.assumeNotNull(allowedWriteOffType, "allowedWriteOffType not null"); allowedWriteOffTypes.add(allowedWriteOffType); return this; } public Builder setWarningsConsumer(final IProcessor<Exception> warningsConsumer) { this.warningsConsumer = warningsConsumer; return this; } public Builder setDocumentIdsToIncludeWhenQuering(final Multimap<AllocableDocType, Integer> documentIds) { this.documentIds = documentIds; return this; } public Builder setFilter_Payment_ID(int filter_Payment_ID) { this.filterPaymentId = filter_Payment_ID; return this; } public Builder setFilter_POReference(String filterPOReference) { this.filterPOReference = filterPOReference; return this; } public Builder allowPurchaseSalesInvoiceCompensation(final boolean allowPurchaseSalesInvoiceCompensation) { this.allowPurchaseSalesInvoiceCompensation = allowPurchaseSalesInvoiceCompensation; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentAllocationContext.java
1
请完成以下Java代码
public Map<String, Object> getCaseVariables() { Map<String, Object> variables = new HashMap<>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } @Override public List<HistoricVariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new HistoricVariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } public String getLocalizedName() { return localizedName; } @Override public void setLocalizedName(String localizedName) { this.localizedName = localizedName; } @Override public String getCaseDefinitionKey() { return caseDefinitionKey; } @Override public void setCaseDefinitionKey(String caseDefinitionKey) { this.caseDefinitionKey = caseDefinitionKey; } @Override public String getCaseDefinitionName() { return caseDefinitionName; } @Override public void setCaseDefinitionName(String caseDefinitionName) { this.caseDefinitionName = caseDefinitionName;
} @Override public Integer getCaseDefinitionVersion() { return caseDefinitionVersion; } @Override public void setCaseDefinitionVersion(Integer caseDefinitionVersion) { this.caseDefinitionVersion = caseDefinitionVersion; } @Override public String getCaseDefinitionDeploymentId() { return caseDefinitionDeploymentId; } @Override public void setCaseDefinitionDeploymentId(String caseDefinitionDeploymentId) { this.caseDefinitionDeploymentId = caseDefinitionDeploymentId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricCaseInstance[id=").append(id) .append(", caseDefinitionId=").append(caseDefinitionId); if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricCaseInstanceEntityImpl.java
1
请完成以下Java代码
String encodeUsingDigits(final long value, char[] digits) { if (value == 0) { return String.valueOf(digits[0]); } final int base = digits.length; final StringBuilder buf = new StringBuilder(); long currentValue = value; while (currentValue > 0) { final int remainder = (int)(currentValue % base); currentValue = currentValue / base; buf.append(digits[remainder]); } return buf.reverse().toString(); }
public void setRandomUUIDSource(@NonNull final Supplier<String> newRandomUUIDSource) { randomUUIDSource = newRandomUUIDSource; } public void reset() { nextViewId.set(1); randomUUIDSource = null; } public String createRandomUUID() { return coalesceSuppliers(randomUUIDSource, DEFAULT_RANDOM_UUID_SOURCE); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\lang\UIDStringUtil.java
1
请完成以下Java代码
private void executeInvokeScriptedExportConversionAction( @NonNull final ExternalSystemScriptedExportConversionConfig config, final int recordId) { final int configTableId = tableDAO.retrieveTableId(I_ExternalSystem_Config_ScriptedExportConversion.Table_Name); try { trxManager.runAfterCommit(() -> { ProcessInfo.builder() .setCtx(getCtx()) .setRecord(configTableId, config.getId().getRepoId()) .setAD_ProcessByClassname(InvokeScriptedExportConversionAction.class.getName()) .addParameter(PARAM_EXTERNAL_REQUEST, COMMAND_CONVERT_MESSAGE_FROM_METASFRESH) .addParameter(PARAM_CHILD_CONFIG_ID, config.getId().getRepoId()) .addParameter(PARAM_Record_ID, recordId) .buildAndPrepareExecution() .executeSync(); }); }
catch (final Exception e) { log.warn(InvokeScriptedExportConversionAction.class.getName() + " process failed for Config ID {}, Record ID: {}", config.getId(), recordId, e); } } private String getTableName() { return tableName; } private boolean isDocument() { return isDocument; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedexportconversion\interceptor\ExternalSystemScriptedExportConversionInterceptor.java
1
请完成以下Java代码
public ResponseEntity<Book> extractData(ClientHttpResponse response) throws IOException { // extract required data from response return null; } } ); // Could also use some factory methods in RestTemplate for // the request callback and/or response extractor Book book = new Book( "Reactive Spring", "Josh Long", 2020); response = restTemplate.execute( "https://api.bookstore.com", HttpMethod.POST, restTemplate.httpEntityCallback(book), restTemplate.responseEntityExtractor(Book.class)
); } private static class Book { String title; String author; int yearPublished; public Book(String title, String author, int yearPublished) { this.title = title; this.author = author; this.yearPublished = yearPublished; } } }
repos\tutorials-master\spring-web-modules\spring-resttemplate-2\src\main\java\com\baeldung\resttemplate\json\methods\RestTemplateMethodsApplication.java
1
请完成以下Java代码
public java.math.BigDecimal getEMURate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_EMURate); if (bd == null) return Env.ZERO; return bd; } /** Set EMU Member. @param IsEMUMember This currency is member if the European Monetary Union */ @Override public void setIsEMUMember (boolean IsEMUMember) { set_Value (COLUMNNAME_IsEMUMember, Boolean.valueOf(IsEMUMember)); } /** Get EMU Member. @return This currency is member if the European Monetary Union */ @Override public boolean isEMUMember () { Object oo = get_Value(COLUMNNAME_IsEMUMember); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set The Euro Currency. @param IsEuro This currency is the Euro */ @Override public void setIsEuro (boolean IsEuro) { set_Value (COLUMNNAME_IsEuro, Boolean.valueOf(IsEuro)); } /** Get The Euro Currency. @return This currency is the Euro */ @Override public boolean isEuro () { Object oo = get_Value(COLUMNNAME_IsEuro); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set ISO Währungscode. @param ISO_Code Three letter ISO 4217 Code of the Currency */ @Override public void setISO_Code (java.lang.String ISO_Code) { set_Value (COLUMNNAME_ISO_Code, ISO_Code); } /** Get ISO Währungscode.
@return Three letter ISO 4217 Code of the Currency */ @Override public java.lang.String getISO_Code () { return (java.lang.String)get_Value(COLUMNNAME_ISO_Code); } /** Set Round Off Factor. @param RoundOffFactor Used to Round Off Payment Amount */ @Override public void setRoundOffFactor (java.math.BigDecimal RoundOffFactor) { set_Value (COLUMNNAME_RoundOffFactor, RoundOffFactor); } /** Get Round Off Factor. @return Used to Round Off Payment Amount */ @Override public java.math.BigDecimal getRoundOffFactor () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RoundOffFactor); if (bd == null) return Env.ZERO; return bd; } /** Set Standardgenauigkeit. @param StdPrecision Rule for rounding calculated amounts */ @Override public void setStdPrecision (int StdPrecision) { set_Value (COLUMNNAME_StdPrecision, Integer.valueOf(StdPrecision)); } /** Get Standardgenauigkeit. @return Rule for rounding calculated amounts */ @Override public int getStdPrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_StdPrecision); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Currency.java
1
请完成以下Java代码
public String getContentType(final I_AD_Archive archive) { // NOTE: at this moment we are storing only PDFs return "application/pdf"; } @Override public byte[] getBinaryData(final I_AD_Archive archive) { return archiveStorageFactory.getArchiveStorage(archive).getBinaryData(archive); } @Override public void setBinaryData(final I_AD_Archive archive, final byte[] data) { archiveStorageFactory.getArchiveStorage(archive).setBinaryData(archive, data); } @Override public InputStream getBinaryDataAsStream(final I_AD_Archive archive) { return archiveStorageFactory.getArchiveStorage(archive).getBinaryDataAsStream(archive); } @Override public Optional<AdArchive> getLastArchive( @NonNull final TableRecordReference reference) { return getLastArchiveRecord(reference).map(this::toAdArchive); } @Override public Optional<I_AD_Archive> getLastArchiveRecord( @NonNull final TableRecordReference reference) { final IArchiveDAO archiveDAO = Services.get(IArchiveDAO.class); final List<I_AD_Archive> lastArchives = archiveDAO.retrieveLastArchives(Env.getCtx(), reference, QueryLimit.ONE);
if (lastArchives.isEmpty()) { return Optional.empty(); } else { return Optional.of(lastArchives.get(0)); } } @Override public Optional<Resource> getLastArchiveBinaryData( @NonNull final TableRecordReference reference) { return getLastArchive(reference).map(AdArchive::getArchiveDataAsResource); } @Override public void updatePrintedRecords(final ImmutableSet<ArchiveId> ids, final UserId userId) { archiveDAO.updatePrintedRecords(ids, userId); } private AdArchive toAdArchive(final I_AD_Archive record) { return AdArchive.builder() .id(ArchiveId.ofRepoId(record.getAD_Archive_ID())) .archiveData(getBinaryData(record)) .contentType(getContentType(record)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveBL.java
1
请完成以下Java代码
public int getM_QualityInsp_LagerKonf_Version_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Anzahl Waschproben. @param NumberOfQualityInspections Aus der hier festgelegte Anzahl an Waschproben ergibt sich der Akonto-Prozentsatz pro einzelner Waschprobe */ @Override public void setNumberOfQualityInspections (int NumberOfQualityInspections) { set_Value (COLUMNNAME_NumberOfQualityInspections, Integer.valueOf(NumberOfQualityInspections)); } /** Get Anzahl Waschproben. @return Aus der hier festgelegte Anzahl an Waschproben ergibt sich der Akonto-Prozentsatz pro einzelner Waschprobe */ @Override public int getNumberOfQualityInspections () { Integer ii = (Integer)get_Value(COLUMNNAME_NumberOfQualityInspections); if (ii == null) return 0; return ii.intValue(); } /** Set Schwelle % für Entsorgungskosten. @param Percentage_Scrap_Treshhold Schwelle % für Entsorgungskosten */ @Override public void setPercentage_Scrap_Treshhold (java.math.BigDecimal Percentage_Scrap_Treshhold) { set_Value (COLUMNNAME_Percentage_Scrap_Treshhold, Percentage_Scrap_Treshhold); } /** Get Schwelle % für Entsorgungskosten. @return Schwelle % für Entsorgungskosten */ @Override public java.math.BigDecimal getPercentage_Scrap_Treshhold () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percentage_Scrap_Treshhold); if (bd == null) return Env.ZERO; return bd; } /** Set Entsorgungskosten pro Einheit. @param Scrap_Fee_Amt_Per_UOM Entsorgungskosten pro Einheit */ @Override public void setScrap_Fee_Amt_Per_UOM (java.math.BigDecimal Scrap_Fee_Amt_Per_UOM) { set_Value (COLUMNNAME_Scrap_Fee_Amt_Per_UOM, Scrap_Fee_Amt_Per_UOM); } /** Get Entsorgungskosten pro Einheit. @return Entsorgungskosten pro Einheit */ @Override public java.math.BigDecimal getScrap_Fee_Amt_Per_UOM () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Scrap_Fee_Amt_Per_UOM); if (bd == null) return Env.ZERO; return bd; } /** Set Gültig ab.
@param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf_Version.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_IMP_Processor_Type[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Import Processor Type. @param IMP_Processor_Type_ID Import Processor Type */ public void setIMP_Processor_Type_ID (int IMP_Processor_Type_ID) { if (IMP_Processor_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_IMP_Processor_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_IMP_Processor_Type_ID, Integer.valueOf(IMP_Processor_Type_ID)); } /** Get Import Processor Type. @return Import Processor Type */ public int getIMP_Processor_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_IMP_Processor_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Java Class. @param JavaClass Java Class */ public void setJavaClass (String JavaClass) { set_Value (COLUMNNAME_JavaClass, JavaClass); } /** Get Java Class. @return Java Class */ public String getJavaClass () { return (String)get_Value(COLUMNNAME_JavaClass); }
/** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_IMP_Processor_Type.java
1