instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
protected IAttributeStorage getAttributeStorageForModel(final ModelType model)
{
final ArrayKey key = mkKey(model);
try
{
final IAttributeStorage result = key2storage.get(key, () -> {
final AttributeStorageType storage = createAttributeStorage(model);
Check.assumeNotNull(storage, "storage not null");
// Add listeners to our storage
addListenersToAttributeStorage(storage);
return storage;
});
if (result != null)
{
result.assertNotDisposed();
}
return result;
}
catch (final Exception e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
/**
|
* Create attribute storage for underlying model
*
* @return attribute storage
*/
protected abstract AttributeStorageType createAttributeStorage(final ModelType model);
@Override
public void flush()
{
getHUAttributesDAO().flush();
}
/**
* Method called when an {@link IAttributeStorage} is removed from cache.
* <p>
* If needed you could do some cleanup work like, {@link #removeListenersFromAttributeStorage(IAttributeStorage)}, destroy it etc.
*/
protected void onAttributeStorageRemovedFromCache(final AttributeStorageType attributeStorage)
{
// nothing on this level
}
@Override
protected void toString(final ToStringHelper stringHelper)
{
// NOTE: avoid printing the whole map because it might get to HU storages that also print factory, leading to recursive calls of the toString.
stringHelper.add("storages#", key2storage.size());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AbstractModelAttributeStorageFactory.java
| 1
|
请完成以下Java代码
|
public class PMM_PurchaseCandidate
{
public static final transient PMM_PurchaseCandidate instance = new PMM_PurchaseCandidate();
private PMM_PurchaseCandidate()
{
super();
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void onDelete(final I_PMM_PurchaseCandidate candidate)
{
// NOTE: prevent deletion mainly because PMM_QtyReport_Event is fetching the QtyPromised_Old from there...
// If we really want to allow deleting, we will have to trigger an event to update the PMM_Balance
throw new AdempiereException("Deleting candidates is not allowed");
|
}
@CalloutMethod(columnNames = I_PMM_PurchaseCandidate.COLUMNNAME_QtyToOrder_TU)
public void onQtyToOrderTUChanged_UI(final I_PMM_PurchaseCandidate candidate)
{
Services.get(IPMMPurchaseCandidateBL.class).updateQtyToOrderFromQtyToOrderTU(candidate);
}
@CalloutMethod(columnNames = I_PMM_PurchaseCandidate.COLUMNNAME_M_HU_PI_Item_Product_Override_ID)
public void onM_HU_PI_Item_Product_Override_Changed(final I_PMM_PurchaseCandidate candidate)
{
// Task FRESH-265: Make sure the QtyToOrder also updates on M_HU_PI_Item_Product override
Services.get(IPMMPurchaseCandidateBL.class).updateQtyToOrderFromQtyToOrderTU(candidate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\interceptor\PMM_PurchaseCandidate.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return "DateTrunc-" + trunc;
}
/**
* Convert {@link TimeUtil}.TRUNC_* values to their correspondent TRUNC db function parameter
*
* @param trunc
* @return
*/
private static String getTruncSql(final String trunc)
{
if (TimeUtil.TRUNC_DAY.equals(trunc))
{
return "DD";
}
else if (TimeUtil.TRUNC_WEEK.equals(trunc))
{
return "WW";
}
else if (TimeUtil.TRUNC_MONTH.equals(trunc))
{
return "MM";
}
else if (TimeUtil.TRUNC_YEAR.equals(trunc))
{
return "Y";
}
else if (TimeUtil.TRUNC_QUARTER.equals(trunc))
{
return "Q";
}
else
{
throw new IllegalArgumentException("Invalid date truncate option: " + trunc);
}
}
@Override
public @NonNull String getColumnSql(final @NonNull String columnName)
{
if (truncSql == null)
{
return columnName;
}
// TODO: optimization: instead of using TRUNC we shall use BETWEEN and precalculated values because:
// * using BETWEEN is INDEX friendly
// * using functions is not INDEX friendly at all and if we have an index on this date column, the index won't be used
final String columnSqlNew = "TRUNC(" + columnName + ", " + DB.TO_STRING(truncSql) + ")";
return columnSqlNew;
}
@Override
public String getValueSql(final Object value, final List<Object> params)
{
final String valueSql;
if (value instanceof ModelColumnNameValue<?>)
{
final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value;
valueSql = modelValue.getColumnName();
}
else
{
valueSql = "?";
|
params.add(value);
}
if (truncSql == null)
{
return valueSql;
}
// note: cast is needed for postgresql, else you get "ERROR: function trunc(unknown, unknown) is not unique"
return "TRUNC(?::timestamp, " + DB.TO_STRING(truncSql) + ")";
}
/**
* @deprecated Please use {@link #convertValue(java.util.Date)}
*/
@Nullable
@Override
@Deprecated
public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model)
{
return convertValue(TimeUtil.asTimestamp(value));
}
public java.util.Date convertValue(final java.util.Date date)
{
if (date == null)
{
return null;
}
return TimeUtil.trunc(date, trunc);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DateTruncQueryFilterModifier.java
| 1
|
请完成以下Java代码
|
public final class ProductionMaterialComparator implements Comparator<IProductionMaterial>
{
public static final ProductionMaterialComparator instance = new ProductionMaterialComparator();
private ProductionMaterialComparator()
{
super();
}
public boolean equals(final IProductionMaterial pm1, final IProductionMaterial pm2)
{
final int cmp = compare(pm1, pm2);
return cmp == 0;
}
@Override
public int compare(final IProductionMaterial pm1, final IProductionMaterial pm2)
{
if (pm1 == pm2)
{
return 0;
}
if (pm1 == null)
{
return -1;
}
if (pm2 == null)
{
return +1;
}
//
// Compare Types
{
final ProductionMaterialType type1 = pm1.getType();
final ProductionMaterialType type2 = pm2.getType();
final int cmp = type1.compareTo(type2);
if (cmp != 0)
{
return cmp;
}
}
//
// Compare Product
{
final int productId1 = pm1.getM_Product().getM_Product_ID();
final int productId2 = pm2.getM_Product().getM_Product_ID();
if (productId1 != productId2)
{
return productId1 - productId2;
}
}
//
// Compare Qty
{
final BigDecimal qty1 = pm1.getQty();
final BigDecimal qty2 = pm2.getQty();
final int cmp = qty1.compareTo(qty2);
if (cmp != 0)
|
{
return cmp;
}
}
//
// Compare UOM
{
final int uomId1 = pm1.getC_UOM().getC_UOM_ID();
final int uomId2 = pm2.getC_UOM().getC_UOM_ID();
if (uomId1 != uomId2)
{
return uomId1 - uomId2;
}
}
//
// Compare QM_QtyDeliveredPercOfRaw
{
final BigDecimal qty1 = pm1.getQM_QtyDeliveredPercOfRaw();
final BigDecimal qty2 = pm2.getQM_QtyDeliveredPercOfRaw();
final int cmp = qty1.compareTo(qty2);
if (cmp != 0)
{
return cmp;
}
}
//
// Compare QM_QtyDeliveredPercOfRaw
{
final BigDecimal qty1 = pm1.getQM_QtyDeliveredAvg();
final BigDecimal qty2 = pm2.getQM_QtyDeliveredAvg();
final int cmp = qty1.compareTo(qty2);
if (cmp != 0)
{
return cmp;
}
}
//
// If we reach this point, they are equal
return 0;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ProductionMaterialComparator.java
| 1
|
请完成以下Java代码
|
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 Prefix.
@param Prefix
Prefix before the sequence number
*/
public void setPrefix (String Prefix)
{
set_Value (COLUMNNAME_Prefix, Prefix);
}
/** Get Prefix.
@return Prefix before the sequence number
*/
public String getPrefix ()
{
return (String)get_Value(COLUMNNAME_Prefix);
}
/** Set Start No.
@param StartNo
Starting number/position
*/
public void setStartNo (int StartNo)
{
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo));
}
/** Get Start No.
@return Starting number/position
*/
|
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suffix.
@param Suffix
Suffix after the number
*/
public void setSuffix (String Suffix)
{
set_Value (COLUMNNAME_Suffix, Suffix);
}
/** Get Suffix.
@return Suffix after the number
*/
public String getSuffix ()
{
return (String)get_Value(COLUMNNAME_Suffix);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtl.java
| 1
|
请完成以下Java代码
|
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Double getSortNo() {
return sortNo;
}
public void setSortNo(Double sortNo) {
this.sortNo = sortNo;
}
public Integer getMenuType() {
return menuType;
}
public void setMenuType(Integer menuType) {
this.menuType = menuType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isRoute() {
return route;
}
public void setRoute(boolean route) {
this.route = route;
}
public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
|
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPerms() {
return perms;
}
public void setPerms(String perms) {
this.perms = perms;
}
public boolean getIsLeaf() {
return isLeaf;
}
public void setIsLeaf(boolean isLeaf) {
this.isLeaf = isLeaf;
}
public String getPermsType() {
return permsType;
}
public void setPermsType(String permsType) {
this.permsType = permsType;
}
public java.lang.String getStatus() {
return status;
}
public void setStatus(java.lang.String status) {
this.status = status;
}
/*update_begin author:wuxianquan date:20190908 for:get set方法 */
public boolean isInternalOrExternal() {
return internalOrExternal;
}
public void setInternalOrExternal(boolean internalOrExternal) {
this.internalOrExternal = internalOrExternal;
}
/*update_end author:wuxianquan date:20190908 for:get set 方法 */
public boolean isHideTab() {
return hideTab;
}
public void setHideTab(boolean hideTab) {
this.hideTab = hideTab;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java
| 1
|
请完成以下Java代码
|
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;
}
public List<SysRole> getRoles() {
return roles;
}
public void setRoles(List<SysRole> roles) {
this.roles = roles;
}
public String getRawPassword() {
return rawPassword;
}
public void setRawPassword(String rawPassword) {
this.rawPassword = rawPassword;
}
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
}
|
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isEnabled() {
return true;
}
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public void setGrantedAuthorities(List<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
}
}
|
repos\springBoot-master\springboot-springSecurity2\src\main\java\com\us\example\domain\SysUser.java
| 1
|
请完成以下Java代码
|
public class EngineInfoResponse {
@ApiModelProperty(example = "default")
private String name;
@ApiModelProperty(example = "file://flowable/flowable.cfg.xml")
private String resourceUrl;
@ApiModelProperty(example = "null")
private String exception;
@ApiModelProperty(example = "6.3.1")
private String version;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getResourceUrl() {
return resourceUrl;
}
public void setResourceUrl(String resourceUrl) {
this.resourceUrl = resourceUrl;
}
|
public String getException() {
return exception;
}
public void setException(String exception) {
this.exception = exception;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
|
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\api\EngineInfoResponse.java
| 1
|
请完成以下Java代码
|
protected final ProcessPreconditionsResolution checkPreconditionsApplicable_SingleSelectedRow()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
else if (!selectedRowIds.isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected final PackageableView getView()
{
return PackageableView.cast(super.getView());
}
@Override
protected final PackageableRow getSingleSelectedRow()
{
return PackageableRow.cast(super.getSingleSelectedRow());
}
@Override
|
protected final Stream<PackageableRow> streamSelectedRows()
{
return super.streamSelectedRows()
.map(PackageableRow::cast);
}
protected final ShipmentScheduleLockRequest createLockRequest(final PackageableRow row)
{
return ShipmentScheduleLockRequest.builder()
.shipmentScheduleIds(row.getShipmentScheduleIds())
.lockType(ShipmentScheduleLockType.PICKING)
.lockedBy(getLoggedUserId())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\process\PackageablesViewBasedProcess.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public T get(TenantId tenantId) {
return cache.getAndPutInTransaction(tenantId, () -> {
AdminSettings adminSettings = adminSettingsService.findAdminSettingsByTenantIdAndKey(tenantId, settingsKey);
if (adminSettings != null) {
try {
return JacksonUtil.convertValue(adminSettings.getJsonValue(), clazz);
} catch (Exception e) {
throw new RuntimeException("Failed to load " + settingsKey + " settings!", e);
}
}
return null;
}, true);
}
public T save(TenantId tenantId, T settings) {
AdminSettings adminSettings = adminSettingsService.findAdminSettingsByTenantIdAndKey(tenantId, settingsKey);
if (adminSettings == null) {
adminSettings = new AdminSettings();
adminSettings.setKey(settingsKey);
adminSettings.setTenantId(tenantId);
}
|
adminSettings.setJsonValue(JacksonUtil.valueToTree(settings));
AdminSettings savedAdminSettings = adminSettingsService.saveAdminSettings(tenantId, adminSettings);
T savedSettings;
try {
savedSettings = JacksonUtil.convertValue(savedAdminSettings.getJsonValue(), clazz);
} catch (Exception e) {
throw new RuntimeException("Failed to load auto commit settings!", e);
}
//API calls to adminSettingsService are not in transaction, so we can simply evict the cache.
cache.evict(tenantId);
return savedSettings;
}
public boolean delete(TenantId tenantId) {
boolean result = adminSettingsService.deleteAdminSettingsByTenantIdAndKey(tenantId, settingsKey);
cache.evict(tenantId);
return result;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\TbAbstractVersionControlSettingsService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class GrpcServerSecurityAutoConfiguration {
/**
* The interceptor for handling security related exceptions such as {@link AuthenticationException} and
* {@link AccessDeniedException}.
*
* @return The exceptionTranslatingServerInterceptor bean.
*/
@Bean
@ConditionalOnMissingBean
public ExceptionTranslatingServerInterceptor exceptionTranslatingServerInterceptor() {
return new ExceptionTranslatingServerInterceptor();
}
/**
* The security interceptor that handles the authentication of requests.
*
* @param authenticationManager The authentication manager used to verify the credentials.
* @param authenticationReader The authentication reader used to extract the credentials from the call.
* @return The authenticatingServerInterceptor bean.
*/
@Bean
@ConditionalOnMissingBean(AuthenticatingServerInterceptor.class)
public DefaultAuthenticatingServerInterceptor authenticatingServerInterceptor(
final AuthenticationManager authenticationManager,
final GrpcAuthenticationReader authenticationReader) {
return new DefaultAuthenticatingServerInterceptor(authenticationManager, authenticationReader);
}
|
/**
* The security interceptor that handles the authorization of requests.
*
* @param accessDecisionManager The access decision manager used to check the requesting user.
* @param securityMetadataSource The source for the security metadata (access constraints).
* @return The authorizationCheckingServerInterceptor bean.
*/
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean({AccessDecisionManager.class, GrpcSecurityMetadataSource.class})
public AuthorizationCheckingServerInterceptor authorizationCheckingServerInterceptor(
final AccessDecisionManager accessDecisionManager,
final GrpcSecurityMetadataSource securityMetadataSource) {
return new AuthorizationCheckingServerInterceptor(accessDecisionManager, securityMetadataSource);
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\autoconfigure\GrpcServerSecurityAutoConfiguration.java
| 2
|
请完成以下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_M_ProductDownload[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Download URL.
@param DownloadURL
URL of the Download files
*/
public void setDownloadURL (String DownloadURL)
{
set_Value (COLUMNNAME_DownloadURL, DownloadURL);
}
/** Get Download URL.
@return URL of the Download files
*/
public String getDownloadURL ()
{
return (String)get_Value(COLUMNNAME_DownloadURL);
}
/** Set Product Download.
@param M_ProductDownload_ID
Product downloads
*/
public void setM_ProductDownload_ID (int M_ProductDownload_ID)
{
if (M_ProductDownload_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductDownload_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductDownload_ID, Integer.valueOf(M_ProductDownload_ID));
}
/** Get Product Download.
@return Product downloads
*/
public int getM_ProductDownload_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductDownload_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
|
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set 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_M_ProductDownload.java
| 1
|
请完成以下Java代码
|
public List<Deployer> getDeployers() {
return deployers;
}
public void setDeployers(List<Deployer> deployers) {
this.deployers = deployers;
}
public DeploymentCache<ProcessDefinitionCacheEntry> getProcessDefinitionCache() {
return processDefinitionCache;
}
public void setProcessDefinitionCache(DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache) {
this.processDefinitionCache = processDefinitionCache;
}
public ProcessDefinitionInfoCache getProcessDefinitionInfoCache() {
return processDefinitionInfoCache;
}
public void setProcessDefinitionInfoCache(ProcessDefinitionInfoCache processDefinitionInfoCache) {
this.processDefinitionInfoCache = processDefinitionInfoCache;
}
public DeploymentCache<Object> getKnowledgeBaseCache() {
return knowledgeBaseCache;
}
public void setKnowledgeBaseCache(DeploymentCache<Object> knowledgeBaseCache) {
this.knowledgeBaseCache = knowledgeBaseCache;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
|
}
public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
public ProcessDefinitionEntityManager getProcessDefinitionEntityManager() {
return processDefinitionEntityManager;
}
public void setProcessDefinitionEntityManager(ProcessDefinitionEntityManager processDefinitionEntityManager) {
this.processDefinitionEntityManager = processDefinitionEntityManager;
}
public DeploymentEntityManager getDeploymentEntityManager() {
return deploymentEntityManager;
}
public void setDeploymentEntityManager(DeploymentEntityManager deploymentEntityManager) {
this.deploymentEntityManager = deploymentEntityManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\deploy\DeploymentManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public UpdateProcessDefinitionSuspensionStateBuilderImpl processDefinitionWithoutTenantId() {
this.processDefinitionTenantId = null;
this.isTenantIdSet = true;
return this;
}
@Override
public UpdateProcessDefinitionSuspensionStateBuilderImpl processDefinitionTenantId(String tenantId) {
ensureNotNull("tenantId", tenantId);
this.processDefinitionTenantId = tenantId;
this.isTenantIdSet = true;
return this;
}
@Override
public void activate() {
validateParameters();
ActivateProcessDefinitionCmd command = new ActivateProcessDefinitionCmd(this);
commandExecutor.execute(command);
}
@Override
public void suspend() {
validateParameters();
SuspendProcessDefinitionCmd command = new SuspendProcessDefinitionCmd(this);
commandExecutor.execute(command);
}
protected void validateParameters() {
ensureOnlyOneNotNull("Need to specify either a process instance id or a process definition key.", processDefinitionId, processDefinitionKey);
if(processDefinitionId != null && isTenantIdSet) {
throw LOG.exceptionUpdateSuspensionStateForTenantOnlyByProcessDefinitionKey();
}
ensureNotNull("commandExecutor", commandExecutor);
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
|
public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isIncludeProcessInstances() {
return includeProcessInstances;
}
public Date getExecutionDate() {
return executionDate;
}
public String getProcessDefinitionTenantId() {
return processDefinitionTenantId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\UpdateProcessDefinitionSuspensionStateBuilderImpl.java
| 2
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setExternal_Request (final String External_Request)
{
set_Value (COLUMNNAME_External_Request, External_Request);
}
@Override
public String getExternal_Request()
{
return get_ValueAsString(COLUMNNAME_External_Request);
}
@Override
public I_ExternalSystem_Config getExternalSystem_Config()
{
return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class);
}
@Override
public void setExternalSystem_Config(final I_ExternalSystem_Config ExternalSystem_Config)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class, ExternalSystem_Config);
}
@Override
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public void setExternalSystem_RuntimeParameter_ID (final int ExternalSystem_RuntimeParameter_ID)
{
if (ExternalSystem_RuntimeParameter_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_RuntimeParameter_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_ExternalSystem_RuntimeParameter_ID, ExternalSystem_RuntimeParameter_ID);
}
@Override
public int getExternalSystem_RuntimeParameter_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_RuntimeParameter_ID);
}
@Override
public void setName (final String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final @Nullable String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_RuntimeParameter.java
| 1
|
请完成以下Java代码
|
public class AssociationValidator extends ValidatorImpl {
@Override
public void validate(BpmnModel bpmnModel, List<ValidationError> errors) {
// Global associations
Collection<Artifact> artifacts = bpmnModel.getGlobalArtifacts();
if (artifacts != null) {
for (Artifact artifact : artifacts) {
if (artifact instanceof Association) {
validate(null, (Association) artifact, errors);
}
}
}
// Process associations
for (Process process : bpmnModel.getProcesses()) {
artifacts = process.getArtifacts();
|
for (Artifact artifact : artifacts) {
if (artifact instanceof Association) {
validate(process, (Association) artifact, errors);
}
}
}
}
protected void validate(Process process, Association association, List<ValidationError> errors) {
if (StringUtils.isEmpty(association.getSourceRef())) {
addError(errors, Problems.ASSOCIATION_INVALID_SOURCE_REFERENCE, process, association);
}
if (StringUtils.isEmpty(association.getTargetRef())) {
addError(errors, Problems.ASSOCIATION_INVALID_TARGET_REFERENCE, process, association);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\impl\AssociationValidator.java
| 1
|
请完成以下Java代码
|
public void setRequestID (final java.lang.String RequestID)
{
set_Value (COLUMNNAME_RequestID, RequestID);
}
@Override
public java.lang.String getRequestID()
{
return get_ValueAsString(COLUMNNAME_RequestID);
}
@Override
public void setRequestMessage (final @Nullable java.lang.String RequestMessage)
{
set_Value (COLUMNNAME_RequestMessage, RequestMessage);
}
@Override
public java.lang.String getRequestMessage()
{
|
return get_ValueAsString(COLUMNNAME_RequestMessage);
}
@Override
public void setResponseMessage (final @Nullable java.lang.String ResponseMessage)
{
set_Value (COLUMNNAME_ResponseMessage, ResponseMessage);
}
@Override
public java.lang.String getResponseMessage()
{
return get_ValueAsString(COLUMNNAME_ResponseMessage);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Log.java
| 1
|
请完成以下Java代码
|
public String toString() {
return "BatchEntity{" +
"batchHandler=" + batchJobHandler +
", id='" + id + '\'' +
", type='" + type + '\'' +
", size=" + totalJobs +
", jobCreated=" + jobsCreated +
", batchJobsPerSeed=" + batchJobsPerSeed +
", invocationsPerBatchJob=" + invocationsPerBatchJob +
", seedJobDefinitionId='" + seedJobDefinitionId + '\'' +
", monitorJobDefinitionId='" + seedJobDefinitionId + '\'' +
", batchJobDefinitionId='" + batchJobDefinitionId + '\'' +
", configurationId='" + configuration.getByteArrayId() + '\'' +
'}';
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
|
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
if (seedJobDefinitionId != null) {
referenceIdAndClass.put(seedJobDefinitionId, JobDefinitionEntity.class);
}
if (batchJobDefinitionId != null) {
referenceIdAndClass.put(batchJobDefinitionId, JobDefinitionEntity.class);
}
if (monitorJobDefinitionId != null) {
referenceIdAndClass.put(monitorJobDefinitionId, JobDefinitionEntity.class);
}
return referenceIdAndClass;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchEntity.java
| 1
|
请完成以下Java代码
|
public boolean isAsync() {
return async;
}
public void setAsync(boolean async) {
this.async = async;
}
public Map<String, CaseElement> getAllCaseElements() {
return allCaseElements;
}
public void setAllCaseElements(Map<String, CaseElement> allCaseElements) {
this.allCaseElements = allCaseElements;
}
public <T extends PlanItemDefinition> List<T> findPlanItemDefinitionsOfType(Class<T> type) {
return planModel.findPlanItemDefinitionsOfType(type, true);
}
public ReactivateEventListener getReactivateEventListener() {
return reactivateEventListener;
|
}
public void setReactivateEventListener(ReactivateEventListener reactivateEventListener) {
this.reactivateEventListener = reactivateEventListener;
}
@Override
public List<FlowableListener> getLifecycleListeners() {
return this.lifecycleListeners;
}
@Override
public void setLifecycleListeners(List<FlowableListener> lifecycleListeners) {
this.lifecycleListeners = lifecycleListeners;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Case.java
| 1
|
请完成以下Java代码
|
private boolean isDebugModeEnabled()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_DEBUG, false);
}
/**
* Gets the EMail TO address to be used when sending mails.
* If present, this address will be used to send all emails to a particular address instead of actual email addresses.
*
* @return email address or null
*/
@Nullable
private InternetAddress getDebugMailToAddressOrNull()
{
final Properties ctx = Env.getCtx();
final String emailStr = StringUtils.trimBlankToNull(
sysConfigBL.getValue(SYSCONFIG_DebugMailTo,
null, // defaultValue
Env.getAD_Client_ID(ctx),
Env.getAD_Org_ID(ctx))
);
if (Check.isEmpty(emailStr, true) || emailStr.equals("-"))
{
return null;
}
try
{
return new InternetAddress(emailStr, true);
}
catch (final Exception ex)
{
logger.warn("Invalid debug email address provided by sysconfig {}: {}. Returning null.", SYSCONFIG_DebugMailTo, emailStr, ex);
|
return null;
}
}
public void send(final EMail email)
{
final EMailSentStatus sentStatus = email.send();
sentStatus.throwIfNotOK();
}
public MailTextBuilder newMailTextBuilder(@NonNull final MailTemplate mailTemplate)
{
return MailTextBuilder.newInstance(mailTemplate);
}
public MailTextBuilder newMailTextBuilder(final MailTemplateId mailTemplateId)
{
final MailTemplate mailTemplate = mailTemplatesRepo.getById(mailTemplateId);
return newMailTextBuilder(mailTemplate);
}
public void test(@NonNull final TestMailRequest request)
{
TestMailCommand.builder()
.mailService(this)
.request(request)
.build()
.execute();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\MailService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<String> roleTreeKeys(String roleIds) {
List<RoleMenu> roleMenus = roleMenuService.list(Wrappers.<RoleMenu>query().lambda().in(RoleMenu::getRoleId, Func.toLongList(roleIds)));
return roleMenus.stream().map(roleMenu -> Func.toStr(roleMenu.getMenuId())).collect(Collectors.toList());
}
@Override
public List<String> dataScopeTreeKeys(String roleIds) {
List<RoleScope> roleScopes = roleScopeService.list(Wrappers.<RoleScope>query().lambda().in(RoleScope::getRoleId, Func.toLongList(roleIds)));
return roleScopes.stream().map(roleScope -> Func.toStr(roleScope.getScopeId())).collect(Collectors.toList());
}
@Override
public List<Kv> authRoutes(BladeUser user) {
if (Func.isEmpty(user)) {
return null;
}
List<MenuDTO> routes = baseMapper.authRoutes(Func.toLongList(user.getRoleId()));
List<Kv> list = new ArrayList<>();
|
routes.forEach(route -> list.add(Kv.init().set(route.getPath(), Kv.init().set("authority", Func.toStrArray(route.getAlias())))));
return list;
}
@Override
public List<MenuVO> grantTopTree(BladeUser user) {
return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantTopTree() : baseMapper.grantTopTreeByRole(Func.toLongList(user.getRoleId())));
}
@Override
public List<String> topTreeKeys(String topMenuIds) {
List<TopMenuSetting> settings = topMenuSettingService.list(Wrappers.<TopMenuSetting>query().lambda().in(TopMenuSetting::getTopMenuId, Func.toLongList(topMenuIds)));
return settings.stream().map(setting -> Func.toStr(setting.getMenuId())).collect(Collectors.toList());
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\MenuServiceImpl.java
| 2
|
请完成以下Java代码
|
public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workPackage, final String localTrxName)
{
// use the workpackge's ctx. It contains the client, org and user that created the queu-block this package belongs to
final Properties localCtx = InterfaceWrapperHelper.getCtx(workPackage);
final List<I_C_Invoice_Candidate> candidatesOfPackage = queueDAO.retrieveAllItems(workPackage, I_C_Invoice_Candidate.class);
try (final IAutoCloseable ignored = invoiceCandBL.setUpdateProcessInProgress())
{
// At this line, we used to update invalid ICs, but that's not needed anymore,
// because we made sure that this is done by the respective invoice-candidate-processor.
// Generate invoices from them
final UserNotificationsInvoiceGenerateResult createInvoiceResults = new UserNotificationsInvoiceGenerateResult(getInvoiceGenerateResult())
.setNotificationRecipientUserId(UserId.ofRepoId(workPackage.getCreatedBy())); // Events shall be sent to workpackage creator
invoiceCandBL.generateInvoices()
.setContext(localCtx, localTrxName)
.setCollector(createInvoiceResults)
.setInvoicingParams(getInvoicingParams())
.setIgnoreInvoiceSchedule(true) // we don't need to check for the invoice schedules because ICs that would be skipped here would already have been skipped on enqueue time.
.generateInvoices(candidatesOfPackage.iterator());
// Log invoices generation result
final String createInvoiceResultsSummary = createInvoiceResults.getSummary(localCtx);
logger.info(createInvoiceResultsSummary);
Loggables.addLog(createInvoiceResultsSummary);
// invalidate them all at once
invoiceCandDAO.invalidateCands(candidatesOfPackage);
}
//
// After invoices were generated, schedule another update invalid workpackage to update any remaining invoice candidates.
|
// This is a workaround and we do that because our testers reported that randomly, when we do mass invoicing,
// sometimes there are some invoice candidates invalidated.
final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(getC_Queue_WorkPackage().getC_Async_Batch_ID());
invoiceCandUpdateSchedulerService.scheduleForUpdate(InvoiceCandUpdateSchedulerRequest.of(localCtx, localTrxName, asyncBatchId));
return Result.SUCCESS;
}
/**
* @return invoice generate result/collector; never returns null
*/
public final IInvoiceGenerateResult getInvoiceGenerateResult()
{
return _result;
}
@Override
public String toString()
{
return String.format("InvoiceCandWorkpackageProcessor [result=%s, queueDAO=%s, invoiceCandBL=%s, invoiceCandDAO=%s, workPackageBL=%s]",
_result, queueDAO, invoiceCandBL, invoiceCandDAO, workPackageBL);
}
private IInvoicingParams getInvoicingParams()
{
if (_invoicingParams == null)
{
_invoicingParams = new InvoicingParams(getParameters());
}
return _invoicingParams;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\async\spi\impl\InvoiceCandWorkpackageProcessor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setName(String name) {
this.name = name;
}
public void setFields(Set<String> fields) {
this.fields = fields;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public boolean isAll() {
return all;
}
public void setAll(boolean all) {
this.all = all;
}
/**
* 判断是否有相同字段
*
* @param fieldControlString
* @return
*/
public boolean isAllFieldsValid(String fieldControlString) {
//如果白名单中没有配置字段,则返回false
String[] controlFields = fieldControlString.split(",");
if (oConvertUtils.isEmpty(fieldControlString)) {
|
return false;
}
for (String queryField : fields) {
if (oConvertUtils.isIn(queryField, controlFields)) {
log.warn("字典表白名单校验,表【" + name + "】中字段【" + queryField + "】无权限查询");
return false;
}
}
return true;
}
@Override
public String toString() {
return "QueryTable{" +
"name='" + name + '\'' +
", alias='" + alias + '\'' +
", fields=" + fields +
", all=" + all +
'}';
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\firewall\SqlInjection\SysDictTableWhite.java
| 2
|
请完成以下Java代码
|
public class ExpressionBasedPreInvocationAdvice implements PreInvocationAuthorizationAdvice {
private MethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
@Override
public boolean before(Authentication authentication, MethodInvocation mi, PreInvocationAttribute attr) {
PreInvocationExpressionAttribute preAttr = (PreInvocationExpressionAttribute) attr;
EvaluationContext ctx = this.expressionHandler.createEvaluationContext(authentication, mi);
Expression preFilter = preAttr.getFilterExpression();
Expression preAuthorize = preAttr.getAuthorizeExpression();
if (preFilter != null) {
Object filterTarget = findFilterTarget(preAttr.getFilterTarget(), ctx, mi);
this.expressionHandler.filter(filterTarget, preFilter, ctx);
}
return (preAuthorize != null) ? ExpressionUtils.evaluateAsBoolean(preAuthorize, ctx) : true;
}
private Object findFilterTarget(String filterTargetName, EvaluationContext ctx, MethodInvocation invocation) {
Object filterTarget = null;
if (filterTargetName.length() > 0) {
filterTarget = ctx.lookupVariable(filterTargetName);
Assert.notNull(filterTarget,
() -> "Filter target was null, or no argument with name " + filterTargetName + " found in method");
|
}
else if (invocation.getArguments().length == 1) {
Object arg = invocation.getArguments()[0];
if (arg.getClass().isArray() || arg instanceof Collection<?>) {
filterTarget = arg;
}
Assert.notNull(filterTarget, () -> "A PreFilter expression was set but the method argument type"
+ arg.getClass() + " is not filterable");
}
else if (invocation.getArguments().length > 1) {
throw new IllegalArgumentException(
"Unable to determine the method argument for filtering. Specify the filter target.");
}
Assert.isTrue(!filterTarget.getClass().isArray(),
"Pre-filtering on array types is not supported. Using a Collection will solve this problem");
return filterTarget;
}
public void setExpressionHandler(MethodSecurityExpressionHandler expressionHandler) {
this.expressionHandler = expressionHandler;
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\access\expression\method\ExpressionBasedPreInvocationAdvice.java
| 1
|
请完成以下Java代码
|
private String extractFileName(final @NonNull PrintingData printingData)
{
final boolean includeSystemTimeMS = sysConfigBL.getBooleanValue(
SYSCONFIG_STORE_PDF_INCLUDE_SYSTEM_TIME_MS_IN_FILENAME,
true /*defaultValue*/,
ClientId.METASFRESH.getRepoId(),
printingData.getOrgId().getRepoId());
final StringBuilder result = new StringBuilder();
if (includeSystemTimeMS)
{
result
.append(SystemTime.millis())
.append("_");
}
return FileUtil.stripIllegalCharacters(result
.append(printingData.getDocumentFileName())
.toString());
}
@NonNull
private String getBaseDirectory(final @NonNull PrintingData printingData)
{
final String sysconfigDirectory = sysConfigBL.getValue(SYSCONFIG_STORE_PDF_BASE_DIRECTORY, ClientId.METASFRESH.getRepoId(), printingData.getOrgId().getRepoId());
if (Check.isNotBlank(sysconfigDirectory))
{
return sysconfigDirectory;
}
final String tempDir = System.getProperty("java.io.tmpdir");
logger.debug("AD_SysConfig {} is not set; -> use temp-dir {} as base directory", SYSCONFIG_STORE_PDF_BASE_DIRECTORY, tempDir);
return tempDir;
}
private void createDirectories(@NonNull final Path path)
{
try
{
Files.createDirectories(path);
}
catch (final IOException e)
{
throw new AdempiereException("IOException trying to create output directory", e)
.setParameter("path", path);
}
}
private ImmutableMultimap<Path, PrintingSegment> extractAndAssignPaths(
@NonNull final String baseDirectory,
@NonNull final PrintingData printingData)
{
final ImmutableMultimap.Builder<Path, PrintingSegment> path2Segments = new ImmutableMultimap.Builder<>();
for (final PrintingSegment segment : printingData.getSegments())
|
{
final HardwarePrinter printer = segment.getPrinter();
if (!OutputType.Store.equals(printer.getOutputType()))
{
logger.debug("Printer with id={} has outputType={}; -> skipping it", printer.getId().getRepoId(), printer.getOutputType());
continue;
}
final Path path;
if (segment.getTrayId() != null)
{
final HardwareTray tray = printer.getTray(segment.getTrayId());
path = Paths.get(baseDirectory,
FileUtil.stripIllegalCharacters(printer.getName()),
FileUtil.stripIllegalCharacters(tray.getTrayNumber() + "-" + tray.getName()));
}
else
{
path = Paths.get(baseDirectory,
FileUtil.stripIllegalCharacters(printer.getName()));
}
path2Segments.put(path, segment);
}
return path2Segments.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingDataToPDFFileStorer.java
| 1
|
请完成以下Java代码
|
protected void restoreModelWhenSnapshotIsMissing(final I_M_HU model)
{
throw new HUException("Cannot restore " + model + " because snapshot is missing");
}
@Override
protected int getModelId(final I_M_HU_Snapshot modelSnapshot)
{
return modelSnapshot.getM_HU_ID();
}
@Override
protected I_M_HU getModel(final I_M_HU_Snapshot modelSnapshot)
{
return modelSnapshot.getM_HU();
}
@Override
protected Map<Integer, I_M_HU_Snapshot> retrieveModelSnapshotsByParent(final I_M_HU_Item huItem)
{
return query(I_M_HU_Snapshot.class)
.addEqualsFilter(I_M_HU_Snapshot.COLUMN_M_HU_Item_Parent_ID, huItem.getM_HU_Item_ID())
.addEqualsFilter(I_M_HU_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId())
.create()
.map(I_M_HU_Snapshot.class, snapshot2ModelIdFunction);
}
@Override
protected Map<Integer, I_M_HU> retrieveModelsByParent(I_M_HU_Item huItem)
{
return query(I_M_HU.class)
.addEqualsFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, huItem.getM_HU_Item_ID())
.create()
.mapById(I_M_HU.class);
}
/**
* Recursively collect all M_HU_IDs and M_HU_Item_IDs starting from <code>startHUIds</code> to the bottom, including those too.
*
* @param startHUIds
* @param huIdsCollector
* @param huItemIdsCollector
*/
protected final void collectHUAndItemIds(final Set<Integer> startHUIds, final Set<Integer> huIdsCollector, final Set<Integer> huItemIdsCollector)
{
|
Set<Integer> huIdsToCheck = new HashSet<>(startHUIds);
while (!huIdsToCheck.isEmpty())
{
huIdsCollector.addAll(huIdsToCheck);
final Set<Integer> huItemIds = retrieveM_HU_Item_Ids(huIdsToCheck);
huItemIdsCollector.addAll(huItemIds);
final Set<Integer> includedHUIds = retrieveIncludedM_HUIds(huItemIds);
huIdsToCheck = new HashSet<>(includedHUIds);
huIdsToCheck.removeAll(huIdsCollector);
}
}
private final Set<Integer> retrieveM_HU_Item_Ids(final Set<Integer> huIds)
{
if (huIds.isEmpty())
{
return Collections.emptySet();
}
final List<Integer> huItemIdsList = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU_Item.class, getContext())
.addInArrayOrAllFilter(I_M_HU_Item.COLUMN_M_HU_ID, huIds)
.create()
.listIds();
return new HashSet<>(huItemIdsList);
}
private final Set<Integer> retrieveIncludedM_HUIds(final Set<Integer> huItemIds)
{
if (huItemIds.isEmpty())
{
return Collections.emptySet();
}
final List<Integer> huIdsList = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU.class, getContext())
.addInArrayOrAllFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, huItemIds)
.create()
.listIds();
return new HashSet<>(huIdsList);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_SnapshotHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int getMigrationLastSeqNo(final I_AD_Migration migration)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(migration);
final String trxName = InterfaceWrapperHelper.getTrxName(migration);
final BigDecimal maxSeqNo = new TypedSqlQuery<I_AD_Migration>(ctx, I_AD_Migration.class, null, trxName)
.aggregate(I_AD_Migration.COLUMNNAME_SeqNo, Aggregate.MAX);
return maxSeqNo.intValue();
}
@Override
public int getMigrationStepLastSeqNo(final I_AD_MigrationStep step)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(step);
final String trxName = InterfaceWrapperHelper.getTrxName(step);
final String whereClause = I_AD_MigrationStep.COLUMNNAME_AD_Migration_ID + "=?";
final BigDecimal maxSeqNo = new TypedSqlQuery<I_AD_MigrationStep>(ctx, I_AD_MigrationStep.class, whereClause, trxName)
.setParameters(step.getAD_Migration_ID())
.aggregate(I_AD_MigrationStep.COLUMNNAME_SeqNo, Aggregate.MAX);
return maxSeqNo.intValue();
}
|
@Override
public List<I_AD_MigrationData> retrieveMigrationData(final I_AD_MigrationStep step)
{
if (step == null || step.getAD_MigrationStep_ID() <= 0)
{
return new ArrayList<I_AD_MigrationData>();
}
final Properties ctx = InterfaceWrapperHelper.getCtx(step);
final String trxName = InterfaceWrapperHelper.getTrxName(step);
final String where = I_AD_MigrationData.COLUMNNAME_AD_MigrationStep_ID + "=?";
final List<I_AD_MigrationData> result = new TypedSqlQuery<I_AD_MigrationData>(ctx, I_AD_MigrationData.class, where, trxName)
.setParameters(step.getAD_MigrationStep_ID())
.setOrderBy(I_AD_MigrationData.COLUMNNAME_AD_MigrationData_ID)
.setOnlyActiveRecords(true)
.list(I_AD_MigrationData.class);
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\service\impl\MigrationDAO.java
| 2
|
请完成以下Java代码
|
public void actionPerformed(ActionEvent e)
{
// log.trace( "ADialogDialog.actionPerformed - " + e);
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
{
m_returnCode = A_OK;
dispose();
}
else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL) || e.getSource() == mEnd)
{
m_returnCode = A_CANCEL;
dispose();
}
else if (e.getSource() == mPreference)
{
if (Env.getUserRolePermissions().isShowPreference())
{
final Preference p = new Preference(null, 0);
p.setVisible(true);
}
}
}
/**
* Get Return Code
*
* @return return code ({@link #A_OK}, {@link #A_CANCEL}, {@link #A_CLOSE})
*/
public int getReturnCode()
{
return m_returnCode;
} // getReturnCode
/**
* Sets initial answer (i.e. button that will be preselected by default).
*
* Please note that this is not the default answer that will be returned by {@link #getReturnCode()} if user does nothing (i.e. closes the window).
* It is just the preselectated button.
*
* @param initialAnswer {@link #A_OK}, {@link #A_CANCEL}.
*/
public void setInitialAnswer(final int initialAnswer)
{
// If the inial answer did not actual changed, do nothing
if (this._initialAnswer == initialAnswer)
{
return;
}
//
// Configure buttons accelerator (KeyStroke) and RootPane's default button
final JRootPane rootPane = getRootPane();
final CButton okButton = confirmPanel.getOKButton();
final AppsAction okAction = (AppsAction)okButton.getAction();
final CButton cancelButton = confirmPanel.getCancelButton();
final AppsAction cancelAction = (AppsAction)cancelButton.getAction();
if (initialAnswer == A_OK)
{
okAction.setDefaultAccelerator();
cancelAction.setDefaultAccelerator();
rootPane.setDefaultButton(okButton);
|
}
else if (initialAnswer == A_CANCEL)
{
// NOTE: we need to set the OK's Accelerator keystroke to null because in most of the cases it is "Enter"
// and we want to prevent user for hiting ENTER by mistake
okAction.setAccelerator(null);
cancelAction.setDefaultAccelerator();
rootPane.setDefaultButton(cancelButton);
}
else
{
throw new IllegalArgumentException("Unknown inital answer: " + initialAnswer);
}
//
// Finally, set the new inial answer
this._initialAnswer = initialAnswer;
}
public int getInitialAnswer()
{
return this._initialAnswer;
}
/**
* Request focus on inital answer.
*/
private void focusInitialAnswerButton()
{
final CButton defaultButton;
if (_initialAnswer == A_OK)
{
defaultButton = confirmPanel.getOKButton();
}
else if (_initialAnswer == A_CANCEL)
{
defaultButton = confirmPanel.getCancelButton();
}
else
{
return;
}
defaultButton.requestFocusInWindow();
}
} // ADialogDialog
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ADialogDialog.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_R_Request getR_Request() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_R_Request_ID, org.compiere.model.I_R_Request.class);
}
@Override
public void setR_Request(org.compiere.model.I_R_Request R_Request)
{
set_ValueFromPO(COLUMNNAME_R_Request_ID, org.compiere.model.I_R_Request.class, R_Request);
}
/** Set Aufgabe.
@param R_Request_ID
Request from a Business Partner or Prospect
*/
@Override
public void setR_Request_ID (int R_Request_ID)
{
if (R_Request_ID < 1)
set_Value (COLUMNNAME_R_Request_ID, null);
else
set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID));
}
/** Get Aufgabe.
@return Request from a Business Partner or Prospect
*/
@Override
public int getR_Request_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Betreff.
@param Subject
Mail Betreff
*/
@Override
public void setSubject (java.lang.String Subject)
{
set_Value (COLUMNNAME_Subject, Subject);
}
/** Get Betreff.
@return Mail Betreff
*/
@Override
public java.lang.String getSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_Subject);
}
@Override
public org.compiere.model.I_AD_User getTo_User() throws RuntimeException
|
{
return get_ValueAsPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setTo_User(org.compiere.model.I_AD_User To_User)
{
set_ValueFromPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class, To_User);
}
/** Set To User.
@param To_User_ID To User */
@Override
public void setTo_User_ID (int To_User_ID)
{
if (To_User_ID < 1)
set_Value (COLUMNNAME_To_User_ID, null);
else
set_Value (COLUMNNAME_To_User_ID, Integer.valueOf(To_User_ID));
}
/** Get To User.
@return To User */
@Override
public int getTo_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_To_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Mail.java
| 1
|
请完成以下Java代码
|
public void setTaxAmt (java.math.BigDecimal TaxAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt);
}
/** Get Steuerbetrag.
@return Tax Amount for a document
*/
@Override
public java.math.BigDecimal getTaxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Bezugswert.
@param TaxBaseAmt
Base for calculating the tax amount
|
*/
@Override
public void setTaxBaseAmt (java.math.BigDecimal TaxBaseAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt);
}
/** Get Bezugswert.
@return Base for calculating the tax amount
*/
@Override
public java.math.BigDecimal getTaxBaseAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxBaseAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclarationLine.java
| 1
|
请完成以下Java代码
|
public TbMsgProcessingStackItem pop() {
if (stack == null || stack.isEmpty()) {
return null;
}
return stack.removeLast();
}
public static TbMsgProcessingCtx fromProto(MsgProtos.TbMsgProcessingCtxProto ctx) {
int ruleNodeExecCounter = ctx.getRuleNodeExecCounter();
if (ctx.getStackCount() > 0) {
LinkedList<TbMsgProcessingStackItem> stack = new LinkedList<>();
for (MsgProtos.TbMsgProcessingStackItemProto item : ctx.getStackList()) {
stack.add(TbMsgProcessingStackItem.fromProto(item));
}
return new TbMsgProcessingCtx(ruleNodeExecCounter, stack);
} else {
|
return new TbMsgProcessingCtx(ruleNodeExecCounter);
}
}
public MsgProtos.TbMsgProcessingCtxProto toProto() {
var ctxBuilder = MsgProtos.TbMsgProcessingCtxProto.newBuilder();
ctxBuilder.setRuleNodeExecCounter(ruleNodeExecCounter.get());
if (stack != null) {
for (TbMsgProcessingStackItem item : stack) {
ctxBuilder.addStack(item.toProto());
}
}
return ctxBuilder.build();
}
}
|
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsgProcessingCtx.java
| 1
|
请完成以下Java代码
|
public void setPayPal_ClientSecret (final java.lang.String PayPal_ClientSecret)
{
set_Value (COLUMNNAME_PayPal_ClientSecret, PayPal_ClientSecret);
}
@Override
public java.lang.String getPayPal_ClientSecret()
{
return get_ValueAsString(COLUMNNAME_PayPal_ClientSecret);
}
@Override
public void setPayPal_Config_ID (final int PayPal_Config_ID)
{
if (PayPal_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_PayPal_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PayPal_Config_ID, PayPal_Config_ID);
}
@Override
public int getPayPal_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_PayPal_Config_ID);
}
@Override
public org.compiere.model.I_R_MailText getPayPal_PayerApprovalRequest_MailTemplate()
{
return get_ValueAsPO(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, org.compiere.model.I_R_MailText.class);
}
@Override
public void setPayPal_PayerApprovalRequest_MailTemplate(final org.compiere.model.I_R_MailText PayPal_PayerApprovalRequest_MailTemplate)
{
set_ValueFromPO(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, org.compiere.model.I_R_MailText.class, PayPal_PayerApprovalRequest_MailTemplate);
}
@Override
public void setPayPal_PayerApprovalRequest_MailTemplate_ID (final int PayPal_PayerApprovalRequest_MailTemplate_ID)
{
if (PayPal_PayerApprovalRequest_MailTemplate_ID < 1)
set_Value (COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, null);
else
set_Value (COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, PayPal_PayerApprovalRequest_MailTemplate_ID);
}
@Override
public int getPayPal_PayerApprovalRequest_MailTemplate_ID()
{
return get_ValueAsInt(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID);
}
@Override
public void setPayPal_PaymentApprovedCallbackUrl (final @Nullable java.lang.String PayPal_PaymentApprovedCallbackUrl)
{
set_Value (COLUMNNAME_PayPal_PaymentApprovedCallbackUrl, PayPal_PaymentApprovedCallbackUrl);
|
}
@Override
public java.lang.String getPayPal_PaymentApprovedCallbackUrl()
{
return get_ValueAsString(COLUMNNAME_PayPal_PaymentApprovedCallbackUrl);
}
@Override
public void setPayPal_Sandbox (final boolean PayPal_Sandbox)
{
set_Value (COLUMNNAME_PayPal_Sandbox, PayPal_Sandbox);
}
@Override
public boolean isPayPal_Sandbox()
{
return get_ValueAsBoolean(COLUMNNAME_PayPal_Sandbox);
}
@Override
public void setPayPal_WebUrl (final @Nullable java.lang.String PayPal_WebUrl)
{
set_Value (COLUMNNAME_PayPal_WebUrl, PayPal_WebUrl);
}
@Override
public java.lang.String getPayPal_WebUrl()
{
return get_ValueAsString(COLUMNNAME_PayPal_WebUrl);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Config.java
| 1
|
请完成以下Java代码
|
public class HelloWorldMain {
public static void main(String[] args) {
String path = System.getProperty("user.dir")
+ "/target/libraries2-1.0.0-SNAPSHOT.jar";
CommandInfo.URI uri = CommandInfo.URI.newBuilder().setValue(path).setExtract(false).build();
String helloWorldCommand = "java -cp libraries2-1.0.0-SNAPSHOT.jar com.baeldung.mesos.executors.HelloWorldExecutor";
CommandInfo commandInfoHelloWorld = CommandInfo.newBuilder().setValue(helloWorldCommand).addUris(uri)
.build();
ExecutorInfo executorHelloWorld = ExecutorInfo.newBuilder()
.setExecutorId(Protos.ExecutorID.newBuilder().setValue("HelloWorldExecutor"))
.setCommand(commandInfoHelloWorld).setName("Hello World (Java)").setSource("java").build();
FrameworkInfo.Builder frameworkBuilder = FrameworkInfo.newBuilder().setFailoverTimeout(120000)
|
.setUser("")
.setName("Hello World Framework (Java)");
frameworkBuilder.setPrincipal("test-framework-java");
MesosSchedulerDriver driver = new MesosSchedulerDriver(new HelloWorldScheduler(executorHelloWorld), frameworkBuilder.build(), args[0]);
int status = driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1;
// Ensure that the driver process terminates.
driver.stop();
System.exit(status);
}
}
|
repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\mesos\HelloWorldMain.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ResourceProductService implements IResourceProductService
{
@Override
public ResourceType getResourceTypeById(final ResourceTypeId resourceTypeId)
{
return Services.get(IResourceDAO.class).getResourceTypeById(resourceTypeId);
}
@Override
public ResourceType getResourceTypeByResourceId(final ResourceId resourceId)
{
return Services.get(IResourceDAO.class).getResourceTypeByResourceId(resourceId);
}
@Override
public I_M_Product getProductByResourceId(@NonNull final ResourceId resourceId)
{
final IProductDAO productsRepo = Services.get(IProductDAO.class);
final ProductId productId = productsRepo.getProductIdByResourceId(resourceId);
return productsRepo.getById(productId);
}
@Override
public ProductId getProductIdByResourceId(final ResourceId resourceId)
{
final IProductDAO productsRepo = Services.get(IProductDAO.class);
return productsRepo.getProductIdByResourceId(resourceId);
|
}
@Override
public TemporalUnit getResourceTemporalUnit(final ResourceId resourceId)
{
final ProductId resourceProductId = getProductIdByResourceId(resourceId);
final I_C_UOM uom = Services.get(IProductBL.class).getStockUOM(resourceProductId);
return UOMUtil.toTemporalUnit(uom);
}
@Override
public I_C_UOM getResoureUOM(final ResourceId resourceId)
{
final I_M_Product product = Services.get(IResourceProductService.class).getProductByResourceId(resourceId);
return Services.get(IProductBL.class).getStockUOM(product);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\impl\ResourceProductService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class InMemoryTokenRepositoryImpl implements PersistentTokenRepository {
private final Map<String, PersistentRememberMeToken> seriesTokens = new HashMap<>();
@Override
public synchronized void createNewToken(PersistentRememberMeToken token) {
PersistentRememberMeToken current = this.seriesTokens.get(token.getSeries());
if (current != null) {
throw new DataIntegrityViolationException("Series Id '" + token.getSeries() + "' already exists!");
}
this.seriesTokens.put(token.getSeries(), token);
}
@Override
public synchronized void updateToken(String series, String tokenValue, Date lastUsed) {
PersistentRememberMeToken token = getTokenForSeries(series);
if (token == null) {
throw new IllegalArgumentException("Token for series '" + series + "' does not exist");
}
PersistentRememberMeToken newToken = new PersistentRememberMeToken(token.getUsername(), series, tokenValue,
new Date());
|
// Store it, overwriting the existing one.
this.seriesTokens.put(series, newToken);
}
@Override
public synchronized @Nullable PersistentRememberMeToken getTokenForSeries(String seriesId) {
return this.seriesTokens.get(seriesId);
}
@Override
public synchronized void removeUserTokens(String username) {
Iterator<String> series = this.seriesTokens.keySet().iterator();
while (series.hasNext()) {
String seriesId = series.next();
PersistentRememberMeToken token = this.seriesTokens.get(seriesId);
if (token != null && username.equals(token.getUsername())) {
series.remove();
}
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\InMemoryTokenRepositoryImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public CustomUser loadUserDetail(String username) {
return userRoleRepository.loadUserByUserName(username);
}
@PreFilter("filterObject != authentication.principal.username")
public String joinUsernames(List<String> usernames) {
return usernames.stream().collect(Collectors.joining(";"));
}
@PreFilter(value = "filterObject != authentication.principal.username", filterTarget = "usernames")
public String joinUsernamesAndRoles(List<String> usernames, List<String> roles) {
return usernames.stream().collect(Collectors.joining(";")) + ":" + roles.stream().collect(Collectors.joining(";"));
}
@PostFilter("filterObject != authentication.principal.username")
public List<String> getAllUsernamesExceptCurrent() {
return userRoleRepository.getAllUsernames();
|
}
@IsViewer
public String getUsername4() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
@PreAuthorize("#username == authentication.principal.username")
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser securedLoadUserDetail(String username) {
return userRoleRepository.loadUserByUserName(username);
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\methodsecurity\service\UserRoleService.java
| 2
|
请完成以下Java代码
|
private void showOrgChangeModalIfNeeded(final @NonNull I_C_BPartner_Location bpLocation, final LocationId newLocationId, @Nullable final LocationId oldLocationId)
{
if (Execution.isCurrentExecutionAvailable()
&& isAskForOrgChangeOnRegionChange())
{
final I_C_Location newLocation = locationDAO.getById(newLocationId);
final PostalId newPostalId = PostalId.ofRepoIdOrNull(newLocation.getC_Postal_ID());
if (newPostalId == null)
{
// nothing to do
return;
}
final I_C_Location oldLocation = oldLocationId != null ? locationDAO.getById(oldLocationId) : null;
final PostalId oldPostalId = oldLocationId == null ? null : PostalId.ofRepoIdOrNull(oldLocation.getC_Postal_ID());
if (newPostalId.equals(oldPostalId))
{
// nothing to do
return;
}
final I_C_Postal newPostalRecord = locationDAO.getPostalById(newPostalId);
final I_C_Postal oldPostalRecord = oldPostalId == null ? null : locationDAO.getPostalById(oldPostalId);
if (oldPostalRecord == null ||
newPostalRecord.getAD_Org_InCharge_ID() != oldPostalRecord.getAD_Org_InCharge_ID())
{
Execution.getCurrent().requestFrontendToTriggerAction(moveToAnotherOrgTriggerAction(bpLocation));
}
|
}
}
private JSONTriggerAction moveToAnotherOrgTriggerAction(final @NonNull I_C_BPartner_Location bpLocation)
{
return JSONTriggerAction.startProcess(
getMoveToAnotherOrgProcessId(),
getBPartnerDocumentPath(bpLocation));
}
private boolean isAskForOrgChangeOnRegionChange()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_AskForOrgChangeOnRegionChange, false);
}
private ProcessId getMoveToAnotherOrgProcessId()
{
final AdProcessId adProcessId = adProcessDAO.retrieveProcessIdByClass(C_BPartner_MoveToAnotherOrg_PostalChange.class);
return ProcessId.ofAD_Process_ID(adProcessId);
}
private DocumentPath getBPartnerDocumentPath(@NonNull final I_C_BPartner_Location bpLocation)
{
return documentZoomIntoService.getDocumentPath(DocumentZoomIntoInfo.of(I_C_BPartner.Table_Name, bpLocation.getC_BPartner_ID()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bpartner\interceptor\C_BPartner_Location.java
| 1
|
请完成以下Java代码
|
public String getGeom() {
return geom;
}
public void setGeom(String geom) {
this.geom = geom;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
|
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
public boolean isAppendWrite() {
return appendWrite;
}
public void setAppendWrite(boolean appendWrite) {
this.appendWrite = appendWrite;
}
}
|
repos\springboot-demo-master\GeoTools\src\main\java\com\et\geotools\pojos\ShpInfo.java
| 1
|
请完成以下Java代码
|
public class ExecuteJobCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(ExecuteJobCmd.class);
protected String jobId;
public ExecuteJobCmd(String jobId) {
this.jobId = jobId;
}
public Object execute(CommandContext commandContext) {
if (jobId == null) {
throw new ActivitiIllegalArgumentException("jobId and job is null");
}
Job job = commandContext.getJobEntityManager().findById(jobId);
if (job == null) {
throw new JobNotFoundException(jobId);
}
if (log.isDebugEnabled()) {
log.debug("Executing job {}", job.getId());
}
executeInternal(commandContext, job);
return null;
}
|
protected void executeInternal(CommandContext commandContext, Job job) {
commandContext.addCloseListener(
new FailedJobListener(commandContext.getProcessEngineConfiguration().getCommandExecutor(), job)
);
try {
commandContext.getJobManager().execute(job);
} catch (Throwable exception) {
// Finally, Throw the exception to indicate the ExecuteJobCmd failed
throw new ActivitiException("Job " + jobId + " failed", exception);
}
}
public String getJobId() {
return jobId;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\ExecuteJobCmd.java
| 1
|
请完成以下Java代码
|
public List<HistoricIncidentDto> getOpenHistoricIncidents(@QueryParam("createdAfter") String createdAfterAsString,
@QueryParam("createdAt") String createdAtAsString,
@QueryParam("maxResults") int maxResults) {
Date createdAfter = dateConverter.convertQueryParameterToType(createdAfterAsString);
Date createdAt = dateConverter.convertQueryParameterToType(createdAtAsString);
maxResults = ensureValidMaxResults(maxResults);
ProcessEngineConfigurationImpl config =
(ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration();
List<HistoricIncidentEntity> historicIncidents =
config.getOptimizeService().getOpenHistoricIncidents(createdAfter, createdAt, maxResults);
List<HistoricIncidentDto> result = new ArrayList<>();
for (HistoricIncident instance : historicIncidents) {
HistoricIncidentDto dto = HistoricIncidentDto.fromHistoricIncident(instance);
result.add(dto);
}
return result;
}
@GET
@Path("/decision-instance")
public List<HistoricDecisionInstanceDto> getHistoricDecisionInstances(@QueryParam("evaluatedAfter") String evaluatedAfterAsString,
@QueryParam("evaluatedAt") String evaluatedAtAsString,
@QueryParam("maxResults") int maxResults) {
Date evaluatedAfter = dateConverter.convertQueryParameterToType(evaluatedAfterAsString);
Date evaluatedAt = dateConverter.convertQueryParameterToType(evaluatedAtAsString);
maxResults = ensureValidMaxResults(maxResults);
ProcessEngineConfigurationImpl config =
(ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration();
List<HistoricDecisionInstance> historicDecisionInstances =
|
config.getOptimizeService().getHistoricDecisionInstances(evaluatedAfter, evaluatedAt, maxResults);
List<HistoricDecisionInstanceDto> resultList = new ArrayList<>();
for (HistoricDecisionInstance historicDecisionInstance : historicDecisionInstances) {
HistoricDecisionInstanceDto dto =
HistoricDecisionInstanceDto.fromHistoricDecisionInstance(historicDecisionInstance);
resultList.add(dto);
}
return resultList;
}
protected int ensureValidMaxResults(int givenMaxResults) {
return givenMaxResults > 0 ? givenMaxResults : Integer.MAX_VALUE;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\optimize\OptimizeRestService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MainRowBucketId
{
@NonNull ProductId productId;
@NonNull LocalDate date;
private MainRowBucketId(
@NonNull final ProductId productId,
@NonNull final LocalDate date)
{
this.productId = productId;
this.date = date;
}
public static MainRowBucketId createInstanceForCockpitRecord(
@NonNull final I_MD_Cockpit dataRecord)
{
return new MainRowBucketId(
ProductId.ofRepoId(dataRecord.getM_Product_ID()),
TimeUtil.asLocalDate(dataRecord.getDateGeneral()));
}
public static MainRowBucketId createInstanceForStockRecord(
@NonNull final I_MD_Stock stockRecord,
@NonNull final LocalDate date)
{
|
return new MainRowBucketId(
ProductId.ofRepoId(stockRecord.getM_Product_ID()),
date);
}
@NonNull
public static MainRowBucketId createInstanceForQuantitiesRecord(
@NonNull final ProductWithDemandSupply qtyRecord,
@NonNull final LocalDate date)
{
return new MainRowBucketId(qtyRecord.getProductId(), date);
}
public static MainRowBucketId createPlainInstance(@NonNull final ProductId productId, @NonNull final LocalDate date)
{
return new MainRowBucketId(productId, date);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\rowfactory\MainRowBucketId.java
| 2
|
请完成以下Java代码
|
public List<PlanItem> getExitDependencies() {
return exitDependencies;
}
public void setExitDependencies(List<PlanItem> exitDependencies) {
this.exitDependencies = exitDependencies;
}
public List<PlanItem> getEntryDependentPlanItems() {
return entryDependentPlanItems;
}
public void setEntryDependentPlanItems(List<PlanItem> entryDependentPlanItems) {
this.entryDependentPlanItems = entryDependentPlanItems;
}
public void addEntryDependentPlanItem(PlanItem planItem) {
Optional<PlanItem> planItemWithSameId = entryDependentPlanItems.stream().filter(p -> p.getId().equals(planItem.getId())).findFirst();
if (!planItemWithSameId.isPresent()) {
entryDependentPlanItems.add(planItem);
}
}
public List<PlanItem> getExitDependentPlanItems() {
return exitDependentPlanItems;
}
public void setExitDependentPlanItems(List<PlanItem> exitDependentPlanItems) {
this.exitDependentPlanItems = exitDependentPlanItems;
}
public void addExitDependentPlanItem(PlanItem planItem) {
Optional<PlanItem> planItemWithSameId = exitDependentPlanItems.stream().filter(p -> p.getId().equals(planItem.getId())).findFirst();
if (!planItemWithSameId.isPresent()) {
exitDependentPlanItems.add(planItem);
}
}
public List<PlanItem> getAllDependentPlanItems() {
List<PlanItem> allDependentPlanItems = new ArrayList<>(entryDependentPlanItems.size() + exitDependentPlanItems.size());
allDependentPlanItems.addAll(entryDependentPlanItems);
|
allDependentPlanItems.addAll(exitDependentPlanItems);
return allDependentPlanItems;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("PlanItem");
if (getName() != null) {
stringBuilder.append(" '").append(getName()).append("'");
}
stringBuilder.append(" (id: ");
stringBuilder.append(getId());
if (getPlanItemDefinition() != null) {
stringBuilder.append(", definitionId: ").append(getPlanItemDefinition().getId());
}
stringBuilder.append(")");
return stringBuilder.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\PlanItem.java
| 1
|
请完成以下Java代码
|
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
return "/home.html";
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
|
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
|
repos\tutorials-master\spring-web-modules\spring-static-resources\src\main\java\com\baeldung\security\MySimpleUrlAuthenticationSuccessHandler.java
| 1
|
请完成以下Java代码
|
public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) {
switch (ruleIndex) {
case 2:
return expr_sempred((ExprContext)_localctx, predIndex);
}
return true;
}
private boolean expr_sempred(ExprContext _localctx, int predIndex) {
switch (predIndex) {
case 0:
return precpred(_ctx, 5);
case 1:
return precpred(_ctx, 4);
}
return true;
}
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\r-\4\2\t\2\4\3\t"+
"\3\4\4\t\4\3\2\6\2\n\n\2\r\2\16\2\13\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+
"\3\5\3\27\n\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\5\4 \n\4\3\4\3\4\3\4\3\4\3\4"+
"\3\4\7\4(\n\4\f\4\16\4+\13\4\3\4\2\3\6\5\2\4\6\2\4\3\2\6\7\3\2\b\t\2\60"+
"\2\t\3\2\2\2\4\26\3\2\2\2\6\37\3\2\2\2\b\n\5\4\3\2\t\b\3\2\2\2\n\13\3"+
|
"\2\2\2\13\t\3\2\2\2\13\f\3\2\2\2\f\3\3\2\2\2\r\16\5\6\4\2\16\17\7\f\2"+
"\2\17\27\3\2\2\2\20\21\7\n\2\2\21\22\7\3\2\2\22\23\5\6\4\2\23\24\7\f\2"+
"\2\24\27\3\2\2\2\25\27\7\f\2\2\26\r\3\2\2\2\26\20\3\2\2\2\26\25\3\2\2"+
"\2\27\5\3\2\2\2\30\31\b\4\1\2\31 \7\13\2\2\32 \7\n\2\2\33\34\7\4\2\2\34"+
"\35\5\6\4\2\35\36\7\5\2\2\36 \3\2\2\2\37\30\3\2\2\2\37\32\3\2\2\2\37\33"+
"\3\2\2\2 )\3\2\2\2!\"\f\7\2\2\"#\t\2\2\2#(\5\6\4\b$%\f\6\2\2%&\t\3\2\2"+
"&(\5\6\4\7\'!\3\2\2\2\'$\3\2\2\2(+\3\2\2\2)\'\3\2\2\2)*\3\2\2\2*\7\3\2"+
"\2\2+)\3\2\2\2\7\13\26\37\')";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}
|
repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\LabeledExprParser.java
| 1
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final MInvoice invoice = new MInvoice(getCtx(), p_C_Invoice_ID, get_TrxName());
recalculateTax(invoice);
//
return "@ProcessOK@";
}
public static void recalculateTax(final MInvoice invoice)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final I_C_BPartner partner = bpartnerDAO.getById(invoice.getC_BPartner_ID());
//
// Delete accounting /UnPost
MPeriod.testPeriodOpen(invoice.getCtx(), invoice.getDateAcct(), invoice.getC_DocType_ID(), invoice.getAD_Org_ID());
|
Services.get(IFactAcctDAO.class).deleteForDocument(invoice);
//
// Update Invoice
invoice.calculateTaxTotal();
invoice.setPosted(false);
invoice.saveEx();
// FRESH-152 Update bpartner stats
Services.get(IBPartnerStatisticsUpdater.class)
.updateBPartnerStatistics(BPartnerStatisticsUpdateRequest.builder()
.bpartnerId(partner.getC_BPartner_ID())
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\eevolution\process\InvoiceCalculateTax.java
| 1
|
请完成以下Java代码
|
public void setC_Location_ID (int C_Location_ID)
{
if (C_Location_ID < 1)
set_Value (COLUMNNAME_C_Location_ID, null);
else
set_Value (COLUMNNAME_C_Location_ID, Integer.valueOf(C_Location_ID));
}
/** Get Anschrift.
@return Adresse oder Anschrift
*/
@Override
public int getC_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
|
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_Allotment.java
| 1
|
请完成以下Java代码
|
private ImmutableMap<Optional<PaymentTermId>, IInvoiceLineRW> mapUniqueIInvoiceLineRWPerPaymentTerm(@NonNull final List<IInvoiceCandAggregate> lines)
{
final List<IInvoiceLineRW> invoiceLinesRW = new ArrayList<>();
lines.forEach(lineAgg -> invoiceLinesRW.addAll(lineAgg.getAllLines()));
return invoiceLinesRW.stream()
.collect(GuavaCollectors.toImmutableMapByKey(line -> PaymentTermId.optionalOfRepoId(line.getC_PaymentTerm_ID())));
}
private void setDocTypeInvoiceId(@NonNull final InvoiceHeaderImpl invoiceHeader)
{
final boolean invoiceIsSOTrx = invoiceHeader.isSOTrx();
final boolean isTakeDocTypeFromPool = invoiceHeader.isTakeDocTypeFromPool();
final DocTypeId docTypeIdToBeUsed;
final Optional<DocTypeId> docTypeInvoiceId = invoiceHeader.getDocTypeInvoiceId();
if (docTypeInvoiceId.isPresent() && !isTakeDocTypeFromPool)
{
docTypeIdToBeUsed = docTypeInvoiceId.get();
}
else if (invoiceHeader.getDocTypeInvoicingPoolId().isPresent())
{
final DocTypeInvoicingPool docTypeInvoicingPool = docTypeInvoicingPoolService.getById(invoiceHeader.getDocTypeInvoicingPoolId().get());
|
final Money totalAmt = invoiceHeader.calculateTotalNetAmtFromLines();
docTypeIdToBeUsed = docTypeInvoicingPool.getDocTypeId(totalAmt);
final I_C_DocType docTypeToBeUsedRecord = docTypeBL.getById(docTypeIdToBeUsed);
Check.assume(invoiceIsSOTrx == docTypeToBeUsedRecord.isSOTrx(), "InvoiceHeader's IsSOTrx={} shall match document type {}", invoiceIsSOTrx, docTypeToBeUsedRecord);
}
else
{
docTypeIdToBeUsed = null;
}
invoiceHeader.setDocTypeInvoiceId(docTypeIdToBeUsed);
}
private Optional<DocTypeInvoicingPool> getDocTypeInvoicingPool(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType docTypeInvoice = docTypeBL.getByIdInTrx(docTypeId);
return Optional.ofNullable(DocTypeInvoicingPoolId.ofRepoIdOrNull(docTypeInvoice.getC_DocType_Invoicing_Pool_ID()))
.map(docTypeInvoicingPoolService::getById);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\AggregationEngine.java
| 1
|
请完成以下Java代码
|
public static JSONClosableMode ofClosableMode(@NonNull final ClosableMode closableMode)
{
switch (closableMode)
{
case ALWAYS_OPEN:
return ALWAYS_OPEN;
case INITIALLY_CLOSED:
return INITIALLY_CLOSED;
case INITIALLY_OPEN:
return INITIALLY_OPEN;
default:
throw new AdempiereException("Unexpected closableMode=" + closableMode);
}
}
}
@JsonProperty("title")
@JsonInclude(Include.NON_EMPTY)
private final String title;
@JsonProperty("description")
@JsonInclude(Include.NON_EMPTY)
private final String description;
@JsonProperty("uiStyle")
@JsonInclude(Include.NON_EMPTY)
private final String uiStyle;
@JsonProperty("columns")
@JsonInclude(Include.NON_EMPTY)
@Getter
private final List<JSONDocumentLayoutColumn> columns;
@JsonProperty("closableMode")
@JsonInclude(Include.NON_EMPTY)
private final JSONClosableMode closableMode;
private JSONDocumentLayoutSection(
final DocumentLayoutSectionDescriptor section,
final JSONDocumentLayoutOptions options)
{
this.title = extractTitle(section, options);
this.uiStyle = section.getUiStyle();
this.description = section.getDescription(options.getAdLanguage()).trim();
this.columns = JSONDocumentLayoutColumn.ofList(section.getColumns(), options);
this.closableMode = JSONClosableMode.ofClosableMode(section.getClosableMode());
}
@Nullable
private static String extractTitle(
@NonNull final DocumentLayoutSectionDescriptor section,
@NonNull final JSONDocumentLayoutOptions options)
{
if (CaptionMode.DISPLAY.equals(section.getCaptionMode()))
{
return section.getCaption(options.getAdLanguage()).trim();
}
else if (CaptionMode.DISPLAY_IN_ADV_EDIT.equals(section.getCaptionMode()))
{
|
if (options.isShowAdvancedFields())
{
return section.getCaption(options.getAdLanguage()).trim();
}
else
{
return null;
}
}
else if (CaptionMode.DONT_DISPLAY.equals(section.getCaptionMode()))
{
return null;
}
throw new AdempiereException("Unexpected captionMode=" + section.getCaptionMode())
.appendParametersToMessage()
.setParameter("documentLayoutSectionDescriptor", section);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("columns", columns)
.toString();
}
Stream<JSONDocumentLayoutElement> streamInlineTabElements()
{
return getColumns().stream().flatMap(JSONDocumentLayoutColumn::streamInlineTabElements);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayoutSection.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static Set<X509Certificate> getTrustedCerts(KeyStore ks, boolean trustsOnly) {
Set<X509Certificate> set = new HashSet<>();
try {
for (Enumeration<String> e = ks.aliases(); e.hasMoreElements(); ) {
String alias = e.nextElement();
if (ks.isCertificateEntry(alias)) {
Certificate cert = ks.getCertificate(alias);
if (cert instanceof X509Certificate) {
if (trustsOnly) {
// is CA certificate
if (((X509Certificate) cert).getBasicConstraints()>=0) {
set.add((X509Certificate) cert);
}
} else {
set.add((X509Certificate) cert);
}
}
} else if (ks.isKeyEntry(alias)) {
Certificate[] certs = ks.getCertificateChain(alias);
if ((certs != null) && (certs.length > 0) &&
(certs[0] instanceof X509Certificate)) {
if (trustsOnly) {
|
for (Certificate cert : certs) {
// is CA certificate
if (((X509Certificate) cert).getBasicConstraints()>=0) {
set.add((X509Certificate) cert);
}
}
} else {
set.add((X509Certificate)certs[0]);
}
}
}
}
} catch (KeyStoreException ignored) {}
return Collections.unmodifiableSet(set);
}
}
|
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\config\ssl\AbstractSslCredentials.java
| 2
|
请完成以下Java代码
|
private int getSequenceId(@NonNull final ProductCategoryId productCategoryId)
{
return productCategoryId2AD_Sequence_ID.getOrLoad(
productCategoryId,
() -> extractSequenceId(productCategoryId, new HashSet<>()));
}
private int extractSequenceId(
@NonNull final ProductCategoryId productCategoryId,
@NonNull final Set<ProductCategoryId> seenIds)
{
final I_M_Product_Category productCategory = loadOutOfTrx(productCategoryId, I_M_Product_Category.class);
final int adSequenceId = productCategory.getAD_Sequence_ProductValue_ID();
if (adSequenceId > 0)
{
// return our result
return adSequenceId;
}
|
if (productCategory.getM_Product_Category_Parent_ID() > 0)
{
final ProductCategoryId productCategoryParentId = ProductCategoryId.ofRepoId(productCategory.getM_Product_Category_Parent_ID());
// first, guard against a loop
if (!seenIds.add(productCategoryParentId))
{
// there is no AD_Sequence_ID for us
return -1;
}
// recurse
return extractSequenceId(productCategoryParentId, seenIds);
}
// there is no AD_Sequence_ID for us
return -1;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\sequence\ProductValueSequenceProvider.java
| 1
|
请完成以下Java代码
|
public Collection<DocumentFilterDescriptor> getAll()
{
return filtersById.values();
}
@Override
public DocumentFilterDescriptor getByFilterIdOrNull(final String filterId)
{
return filtersById.get(filterId);
}
@Override
public DocumentFilter unwrap(final @NonNull JSONDocumentFilter jsonFilter)
{
if (ProductBarcode_FilterId.equals(jsonFilter.getFilterId()))
{
return unwrapProductBarcodeFilter(jsonFilter);
}
else
{
return DocumentFilterDescriptorsProvider.super.unwrap(jsonFilter);
}
}
private DocumentFilter unwrapProductBarcodeFilter(@NonNull final JSONDocumentFilter jsonFilter)
{
final DocumentFilter filter = DocumentFilterDescriptorsProvider.super.unwrap(jsonFilter);
final String barcode = filter.getParameterValueAsString(PARAM_Barcode);
if (barcode == null || Check.isBlank(barcode))
{
return filter;
}
final ProductBarcodeFilterData data = createData(barcode).orElse(null);
if (data != null)
{
return filter.toBuilder()
.addInternalParameter(DocumentFilterParam.ofNameEqualsValue(PARAM_Data, data))
.build();
}
else
{
return filter;
}
}
public final Optional<ProductBarcodeFilterData> createData(@NonNull final String barcode)
{
//
// Pick the first matcher
for (final ProductBarcodeFilterDataFactory factory : productDataFactories)
{
final Optional<ProductBarcodeFilterData> data = factory.createData(services, barcode, ClientId.METASFRESH);
if (data.isPresent())
{
return data;
}
}
|
return Optional.empty();
}
private ImmutableList<ProductBarcodeFilterDataFactory> getProductBarcodeFilterDataFactories()
{
return ImmutableList.of(
// Check if given barcode is a product UPC or M_Product.Value
new UPCProductBarcodeFilterDataFactory(),
// Check if given barcode is a SSCC18 of an existing HU
new SSCC18ProductBarcodeFilterDataFactory(),
// Check if given barcode is an HU internal barcode
new HUBarcodeFilterDataFactory());
}
public static Optional<ProductBarcodeFilterData> extractProductBarcodeFilterData(@NonNull final DocumentFilter filter)
{
if (!ProductBarcode_FilterId.equals(filter.getFilterId()))
{
throw new AdempiereException("Invalid filterId " + filter.getFilterId() + ". Expected: " + ProductBarcode_FilterId);
}
return Optional.ofNullable(filter.getParameterValueAs(PARAM_Data));
}
public static Optional<ProductBarcodeFilterData> extractProductBarcodeFilterData(@NonNull final IView view)
{
return view.getFilters()
.stream()
.filter(filter -> ProductBarcode_FilterId.equals(filter.getFilterId()))
.findFirst()
.flatMap(PackageableFilterDescriptorProvider::extractProductBarcodeFilterData);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\filters\PackageableFilterDescriptorProvider.java
| 1
|
请完成以下Java代码
|
public List<String> getEntryPoints() {
return entryPoints;
}
public void setEntryPoints(List<String> entryPoints) {
this.entryPoints = entryPoints;
}
public boolean isEnableSecureCookie() {
return enableSecureCookie;
}
public void setEnableSecureCookie(boolean enableSecureCookie) {
this.enableSecureCookie = enableSecureCookie;
}
public boolean isEnableSameSiteCookie() {
return enableSameSiteCookie;
}
public void setEnableSameSiteCookie(boolean enableSameSiteCookie) {
this.enableSameSiteCookie = enableSameSiteCookie;
}
public String getSameSiteCookieOption() {
return sameSiteCookieOption;
}
public void setSameSiteCookieOption(String sameSiteCookieOption) {
this.sameSiteCookieOption = sameSiteCookieOption;
}
public String getSameSiteCookieValue() {
return sameSiteCookieValue;
}
public void setSameSiteCookieValue(String sameSiteCookieValue) {
this.sameSiteCookieValue = sameSiteCookieValue;
}
public String getCookieName() {
return cookieName;
}
public void setCookieName(String cookieName) {
this.cookieName = cookieName;
}
public Map<String, String> getInitParams() {
Map<String, String> initParams = new HashMap<>();
if (StringUtils.isNotBlank(targetOrigin)) {
initParams.put("targetOrigin", targetOrigin);
}
if (denyStatus != null) {
initParams.put("denyStatus", denyStatus.toString());
}
if (StringUtils.isNotBlank(randomClass)) {
initParams.put("randomClass", randomClass);
}
if (!entryPoints.isEmpty()) {
initParams.put("entryPoints", StringUtils.join(entryPoints, ","));
}
|
if (enableSecureCookie) { // only add param if it's true; default is false
initParams.put("enableSecureCookie", String.valueOf(enableSecureCookie));
}
if (!enableSameSiteCookie) { // only add param if it's false; default is true
initParams.put("enableSameSiteCookie", String.valueOf(enableSameSiteCookie));
}
if (StringUtils.isNotBlank(sameSiteCookieOption)) {
initParams.put("sameSiteCookieOption", sameSiteCookieOption);
}
if (StringUtils.isNotBlank(sameSiteCookieValue)) {
initParams.put("sameSiteCookieValue", sameSiteCookieValue);
}
if (StringUtils.isNotBlank(cookieName)) {
initParams.put("cookieName", cookieName);
}
return initParams;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("targetOrigin=" + targetOrigin)
.add("denyStatus='" + denyStatus + '\'')
.add("randomClass='" + randomClass + '\'')
.add("entryPoints='" + entryPoints + '\'')
.add("enableSecureCookie='" + enableSecureCookie + '\'')
.add("enableSameSiteCookie='" + enableSameSiteCookie + '\'')
.add("sameSiteCookieOption='" + sameSiteCookieOption + '\'')
.add("sameSiteCookieValue='" + sameSiteCookieValue + '\'')
.add("cookieName='" + cookieName + '\'')
.toString();
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\CsrfProperties.java
| 1
|
请完成以下Java代码
|
public void setVersion (java.lang.String Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.lang.String getVersion ()
{
return (java.lang.String)get_Value(COLUMNNAME_Version);
}
/** Set WebUIServletListener Class.
@param WebUIServletListenerClass
Optional class to execute custom code on WebUI startup; A declared class needs to implement IWebUIServletListener
|
*/
@Override
public void setWebUIServletListenerClass (java.lang.String WebUIServletListenerClass)
{
set_Value (COLUMNNAME_WebUIServletListenerClass, WebUIServletListenerClass);
}
/** Get WebUIServletListener Class.
@return Optional class to execute custom code on WebUI startup; A declared class needs to implement IWebUIServletListener
*/
@Override
public java.lang.String getWebUIServletListenerClass ()
{
return (java.lang.String)get_Value(COLUMNNAME_WebUIServletListenerClass);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_EntityType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CostsRevaluationResult
{
@NonNull CurrentCostBeforeEvaluation currentCostBeforeEvaluation;
@NonNull @Singular ImmutableList<CostDetailAdjustment> costDetailAdjustments;
@NonNull CurrentCostAfterEvaluation currentCostAfterEvaluation;
//
//
//
@Value
public static class CurrentCostBeforeEvaluation
{
@NonNull Quantity qty;
@NonNull CostAmount costPriceOld;
@NonNull CostAmount costPriceNew;
@Builder
private CurrentCostBeforeEvaluation(
@NonNull final Quantity qty,
@NonNull final CostAmount costPriceOld,
@NonNull final CostAmount costPriceNew)
{
CostAmount.assertCurrencyMatching(costPriceOld, costPriceNew);
|
this.qty = qty;
this.costPriceOld = costPriceOld;
this.costPriceNew = costPriceNew;
}
}
@Value
@Builder
public static class CurrentCostAfterEvaluation
{
@NonNull Quantity qty;
@NonNull CostAmount costPriceComputed;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostsRevaluationResult.java
| 2
|
请完成以下Java代码
|
public String[] segment(String text)
{
if (text.length() == 0) return new String[0];
char[] charArray = text.toCharArray();
CharTable.normalization(charArray);
// 先拆成字
List<int[]> atomList = new LinkedList<int[]>();
int start = 0;
int end = charArray.length;
int offsetAtom = start;
byte preType = CharType.get(charArray[offsetAtom]);
byte curType;
while (++offsetAtom < end)
{
curType = CharType.get(charArray[offsetAtom]);
if (preType == CharType.CT_CHINESE)
{
atomList.add(new int[]{start, offsetAtom - start});
start = offsetAtom;
}
else if (curType != preType)
{
// 浮点数识别
if (charArray[offsetAtom] == '.' && preType == CharType.CT_NUM)
{
while (++offsetAtom < end)
{
curType = CharType.get(charArray[offsetAtom]);
if (curType != CharType.CT_NUM) break;
}
}
if (preType == CharType.CT_NUM || preType == CharType.CT_LETTER) atomList.add(new int[]{start, offsetAtom - start});
start = offsetAtom;
}
preType = curType;
}
if (offsetAtom == end)
|
if (preType == CharType.CT_NUM || preType == CharType.CT_LETTER) atomList.add(new int[]{start, offsetAtom - start});
if (atomList.isEmpty()) return new String[0];
// 输出
String[] termArray = new String[atomList.size() - 1];
Iterator<int[]> iterator = atomList.iterator();
int[] pre = iterator.next();
int p = -1;
while (iterator.hasNext())
{
int[] cur = iterator.next();
termArray[++p] = new StringBuilder(pre[1] + cur[1]).append(charArray, pre[0], pre[1]).append(charArray, cur[0], cur[1]).toString();
pre = cur;
}
return termArray;
}
// public static void main(String args[])
// {
// BigramTokenizer bws = new BigramTokenizer();
// String[] result = bws.segment("@hankcs你好,广阔的世界2016!\u0000\u0000\t\n\r\n慶祝Coding worlds!");
// for (String str : result)
// {
// System.out.println(str);
// }
// }
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\tokenizers\BigramTokenizer.java
| 1
|
请完成以下Java代码
|
public static User getSingletonInstance(String name, String email, String country) {
if (instance == null) {
synchronized (User.class) {
if (instance == null) {
instance = new User(name, email, country);
}
}
}
return instance;
}
private User(String name, String email, String country) {
this.name = name;
this.email = email;
|
this.country = country;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getCountry() {
return country;
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-creational-2\src\main\java\com\baeldung\constructorsstaticfactorymethods\entities\User.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Session getSession() {
return this.session;
}
}
/**
* Reactive server properties.
*/
public static class Reactive {
private final Session session = new Session();
public Session getSession() {
return this.session;
}
public static class Session {
/**
* Session timeout. If a duration suffix is not specified, seconds will be
* used.
*/
@DurationUnit(ChronoUnit.SECONDS)
private Duration timeout = Duration.ofMinutes(30);
/**
* Maximum number of sessions that can be stored.
*/
private int maxSessions = 10000;
@NestedConfigurationProperty
private final Cookie cookie = new Cookie();
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public int getMaxSessions() {
return this.maxSessions;
}
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
public Cookie getCookie() {
return this.cookie;
}
}
}
/**
* Strategies for supporting forward headers.
|
*/
public enum ForwardHeadersStrategy {
/**
* Use the underlying container's native support for forwarded headers.
*/
NATIVE,
/**
* Use Spring's support for handling forwarded headers.
*/
FRAMEWORK,
/**
* Ignore X-Forwarded-* headers.
*/
NONE
}
public static class Encoding {
/**
* Mapping of locale to charset for response encoding.
*/
private @Nullable Map<Locale, Charset> mapping;
public @Nullable Map<Locale, Charset> getMapping() {
return this.mapping;
}
public void setMapping(@Nullable Map<Locale, Charset> mapping) {
this.mapping = mapping;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\ServerProperties.java
| 2
|
请完成以下Java代码
|
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status of the currently running check
*/
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
@Override
public org.compiere.model.I_AD_User getSupervisor() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Supervisor_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSupervisor(org.compiere.model.I_AD_User Supervisor)
{
set_ValueFromPO(COLUMNNAME_Supervisor_ID, org.compiere.model.I_AD_User.class, Supervisor);
}
/** Set Vorgesetzter.
@param Supervisor_ID
Supervisor for this user/organization - used for escalation and approval
*/
@Override
public void setSupervisor_ID (int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID));
}
/** Get Vorgesetzter.
@return Supervisor for this user/organization - used for escalation and approval
*/
@Override
public int getSupervisor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID);
if (ii == null)
return 0;
|
return ii.intValue();
}
/**
* WeekDay AD_Reference_ID=167
* Reference name: Weekdays
*/
public static final int WEEKDAY_AD_Reference_ID=167;
/** Sonntag = 7 */
public static final String WEEKDAY_Sonntag = "7";
/** Montag = 1 */
public static final String WEEKDAY_Montag = "1";
/** Dienstag = 2 */
public static final String WEEKDAY_Dienstag = "2";
/** Mittwoch = 3 */
public static final String WEEKDAY_Mittwoch = "3";
/** Donnerstag = 4 */
public static final String WEEKDAY_Donnerstag = "4";
/** Freitag = 5 */
public static final String WEEKDAY_Freitag = "5";
/** Samstag = 6 */
public static final String WEEKDAY_Samstag = "6";
/** Set Day of the Week.
@param WeekDay
Day of the Week
*/
@Override
public void setWeekDay (java.lang.String WeekDay)
{
set_Value (COLUMNNAME_WeekDay, WeekDay);
}
/** Get Day of the Week.
@return Day of the Week
*/
@Override
public java.lang.String getWeekDay ()
{
return (java.lang.String)get_Value(COLUMNNAME_WeekDay);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Scheduler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ClientRegionShortcut getShortcut() {
return this.shortcut != null ? this.shortcut : DEFAULT_CLIENT_REGION_SHORTCUT;
}
public void setShortcut(ClientRegionShortcut shortcut) {
this.shortcut = shortcut;
}
}
public static class PoolProperties {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
public static class ServerRegionProperties {
public static final RegionShortcut DEFAULT_SERVER_REGION_SHORTCUT = RegionShortcut.PARTITION;
private RegionShortcut shortcut;
public RegionShortcut getShortcut() {
return this.shortcut != null ? this.shortcut : DEFAULT_SERVER_REGION_SHORTCUT;
}
public void setShortcut(RegionShortcut shortcut) {
this.shortcut = shortcut;
}
}
public static class SessionProperties {
@NestedConfigurationProperty
private final SessionAttributesProperties attributes = new SessionAttributesProperties();
@NestedConfigurationProperty
private final SessionExpirationProperties expiration = new SessionExpirationProperties();
@NestedConfigurationProperty
private final SessionRegionProperties region = new SessionRegionProperties();
@NestedConfigurationProperty
private final SessionSerializerProperties serializer = new SessionSerializerProperties();
public SessionAttributesProperties getAttributes() {
return this.attributes;
}
public SessionExpirationProperties getExpiration() {
return this.expiration;
}
public SessionRegionProperties getRegion() {
return this.region;
}
public SessionSerializerProperties getSerializer() {
return this.serializer;
}
}
public static class SessionAttributesProperties {
private String[] indexable;
public String[] getIndexable() {
return this.indexable;
}
|
public void setIndexable(String[] indexable) {
this.indexable = indexable;
}
}
public static class SessionExpirationProperties {
private int maxInactiveIntervalSeconds;
public int getMaxInactiveIntervalSeconds() {
return this.maxInactiveIntervalSeconds;
}
public void setMaxInactiveIntervalSeconds(int maxInactiveIntervalSeconds) {
this.maxInactiveIntervalSeconds = maxInactiveIntervalSeconds;
}
public void setMaxInactiveInterval(Duration duration) {
int maxInactiveIntervalInSeconds = duration != null
? Long.valueOf(duration.toSeconds()).intValue()
: GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS;
setMaxInactiveIntervalSeconds(maxInactiveIntervalInSeconds);
}
}
public static class SessionRegionProperties {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
public static class SessionSerializerProperties {
private String beanName;
public String getBeanName() {
return this.beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\SpringSessionProperties.java
| 2
|
请完成以下Java代码
|
public class BookBorrowResponse {
private String userId;
private String bookId;
private String status;
public BookBorrowResponse(String userId, String bookId, String status) {
this.userId = userId;
this.bookId = bookId;
this.status = status;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
|
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-webflux\src\main\java\com\baeldung\spring\convertmonoobject\BookBorrowResponse.java
| 1
|
请完成以下Java代码
|
class UpperBoundAllocationStrategy extends AbstractAllocationStrategy
{
@Nullable
private final Capacity capacityOverride;
/**
* @param capacityOverride optional capacity that can override the one from the packing instructions.
*/
public UpperBoundAllocationStrategy(
@Nullable final Capacity capacityOverride,
@NonNull final AllocationStrategySupportingServicesFacade services)
{
super(AllocationDirection.INBOUND_ALLOCATION, services);
this.capacityOverride = capacityOverride;
}
@Override
protected IHUItemStorage getHUItemStorage(final I_M_HU_Item item, final IAllocationRequest request)
{
final IHUItemStorage storage = super.getHUItemStorage(item, request);
// make sure that the capacity is forced by the user, not the system
// If capacityOverride is null it means that we were asked to take the defaults
if (capacityOverride != null && !storage.isPureVirtual())
{
storage.setCustomCapacity(capacityOverride);
}
return storage;
}
@Override
protected IAllocationResult allocateOnIncludedHUItem(
@NonNull final I_M_HU_Item item,
@NonNull final IAllocationRequest request)
{
// Prevent allocating on a included HU item
final HUItemType itemType = services.getItemType(item);
if (HUItemType.HandlingUnit.equals(itemType))
{
if (services.isDeveloperMode())
{
throw new AdempiereException("HUs which are used in " + this + " shall not have included HUs. They shall be pure TUs."
+ "\n Item: " + item
|
// + "\n PI: " + handlingUnitsBL.getPI(item.getM_HU()).getName()
+ "\n Request: " + request);
}
return AllocationUtils.nullResult();
}
//
// We are about to allocate to Virtual HUs linked to given "item" (which shall be of type Material).
// In this case we rely on the standard logic.
return super.allocateOnIncludedHUItem(item, request);
}
/**
* Does nothing, returns null result.
*/
@Override
protected IAllocationResult allocateRemainingOnIncludedHUItem(final I_M_HU_Item item, final IAllocationRequest request)
{
return AllocationUtils.nullResult();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\UpperBoundAllocationStrategy.java
| 1
|
请完成以下Java代码
|
public CountResultDto getJobsCount(UriInfo uriInfo) {
JobQueryDto queryDto = new JobQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryJobsCount(queryDto);
}
@Override
public CountResultDto queryJobsCount(JobQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
JobQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
@Override
public BatchDto setRetries(SetJobRetriesDto setJobRetriesDto) {
try {
EnsureUtil.ensureNotNull("setJobRetriesDto", setJobRetriesDto);
EnsureUtil.ensureNotNull("retries", setJobRetriesDto.getRetries());
} catch (NullValueException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
JobQuery jobQuery = null;
if (setJobRetriesDto.getJobQuery() != null) {
JobQueryDto jobQueryDto = setJobRetriesDto.getJobQuery();
jobQueryDto.setObjectMapper(getObjectMapper());
jobQuery = jobQueryDto.toQuery(getProcessEngine());
|
}
try {
SetJobRetriesByJobsAsyncBuilder builder = getProcessEngine().getManagementService()
.setJobRetriesByJobsAsync(setJobRetriesDto.getRetries().intValue())
.jobIds(setJobRetriesDto.getJobIds())
.jobQuery(jobQuery);
if(setJobRetriesDto.isDueDateSet()) {
builder.dueDate(setJobRetriesDto.getDueDate());
}
Batch batch = builder.executeAsync();
return BatchDto.fromBatch(batch);
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
}
@Override
public void updateSuspensionState(JobSuspensionStateDto dto) {
if (dto.getJobId() != null) {
String message = "Either jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey can be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
dto.updateSuspensionState(getProcessEngine());
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\JobRestServiceImpl.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8088
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://127.0.0.1:3306/demo?useUnicod
|
e=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
|
repos\springboot-demo-master\mysql\src\main\resources\application.yaml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public ResponseEntity<Object> saveUser(@RequestBody User user) {
return new ResponseEntity<>(userService.saveUser(user), HttpStatus.OK);
}
/**
* 修改用户信息
* api :localhost:8099/users
* @param user
* @return
*/
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
@ApiModelProperty(value="user",notes = "修改后用户信息的json串")
@ApiOperation(value = "新增用户", notes="返回新增的用户信息")
public ResponseEntity<Object> updateUser(@RequestBody User user) {
|
return new ResponseEntity<>(userService.updateUser(user), HttpStatus.OK);
}
/**
* 通过ID删除用户
* api :localhost:8099/users/2
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseBody
@ApiOperation(value = "通过id删除用户信息", notes="返回删除状态1 成功 0 失败")
public ResponseEntity<Object> deleteUser(@PathVariable Integer id) {
return new ResponseEntity<>(userService.removeUser(id.longValue()), HttpStatus.OK);
}
}
|
repos\springBoot-master\springboot-swagger-ui\src\main\java\com\abel\example\controller\UserController.java
| 2
|
请完成以下Java代码
|
public Date timestamp() {
return this.timestamp;
}
byte[] bodyAsByteArray() throws IOException {
var bodyStream = new ByteArrayOutputStream();
var channel = Channels.newChannel(bodyStream);
for (ByteBuffer byteBuffer : body()) {
channel.write(byteBuffer);
}
return bodyStream.toByteArray();
}
String bodyAsString() throws IOException {
InputStream byteStream = new ByteArrayInputStream(bodyAsByteArray());
if (headers.getOrEmpty(HttpHeaders.CONTENT_ENCODING).contains("gzip")) {
byteStream = new GZIPInputStream(byteStream);
}
return new String(FileCopyUtils.copyToByteArray(byteStream));
}
public static class Builder {
private final HttpStatusCode statusCode;
private final HttpHeaders headers = new HttpHeaders();
private final List<ByteBuffer> body = new ArrayList<>();
private @Nullable Instant timestamp;
public Builder(HttpStatusCode statusCode) {
this.statusCode = statusCode;
}
public Builder header(String name, String value) {
this.headers.add(name, value);
return this;
}
public Builder headers(HttpHeaders headers) {
this.headers.addAll(headers);
return this;
}
public Builder timestamp(Instant timestamp) {
this.timestamp = timestamp;
|
return this;
}
public Builder timestamp(Date timestamp) {
this.timestamp = timestamp.toInstant();
return this;
}
public Builder body(String data) {
return appendToBody(ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8)));
}
public Builder appendToBody(ByteBuffer byteBuffer) {
this.body.add(byteBuffer);
return this;
}
public CachedResponse build() {
return new CachedResponse(statusCode, headers, body, timestamp == null ? new Date() : Date.from(timestamp));
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\CachedResponse.java
| 1
|
请完成以下Java代码
|
public class PDF2TextExample {
private static final String PDF = "src/main/resources/pdf.pdf";
private static final String TXT = "src/main/resources/txt.txt";
public static void main(String[] args) {
try {
generateTxtFromPDF(PDF);
generatePDFFromTxt(TXT);
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
private static void generateTxtFromPDF(String filename) throws IOException {
File f = new File(filename);
String parsedText;
PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
parser.parse();
COSDocument cosDoc = parser.getDocument();
PDFTextStripper pdfStripper = new PDFTextStripper();
PDDocument pdDoc = new PDDocument(cosDoc);
parsedText = pdfStripper.getText(pdDoc);
if (cosDoc != null)
cosDoc.close();
if (pdDoc != null)
pdDoc.close();
PrintWriter pw = new PrintWriter("src/output/pdf.txt");
pw.print(parsedText);
pw.close();
}
|
private static void generatePDFFromTxt(String filename) throws IOException, DocumentException {
Document pdfDoc = new Document(PageSize.A4);
PdfWriter.getInstance(pdfDoc, new FileOutputStream("src/output/txt.pdf"))
.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
pdfDoc.open();
Font myfont = new Font();
myfont.setStyle(Font.NORMAL);
myfont.setSize(11);
pdfDoc.add(new Paragraph("\n"));
BufferedReader br = new BufferedReader(new FileReader(filename));
String strLine;
while ((strLine = br.readLine()) != null) {
Paragraph para = new Paragraph(strLine + "\n", myfont);
para.setAlignment(Element.ALIGN_JUSTIFIED);
pdfDoc.add(para);
}
pdfDoc.close();
br.close();
}
}
|
repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\PDF2TextExample.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SessionListener implements HttpSessionListener, HttpSessionIdListener, ApplicationContextAware {
private static final Logger LOG = LoggerFactory.getLogger(SessionListener.class);
private final UserAccessService userAccessService;
@Autowired
public SessionListener(UserAccessService userAccessService) {
this.userAccessService = userAccessService;
}
@Override
public void sessionIdChanged(HttpSessionEvent se, String oldSessionId) {
LOG.info("sessionIdChanged: {}->{}", oldSessionId, se.getSession().getId());
}
@Override
public void sessionCreated(HttpSessionEvent se) {
LOG.info("sessionCreated: {}", se.getSession().getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
|
LOG.info("sessionDestroyed: {}", se.getSession().getId());
userAccessService.logout(SessionId.from(se.getSession().getId()));
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
LOG.info("setApplicationContext");
if (applicationContext instanceof WebApplicationContext) {
WebApplicationContext webApplicationContext = (WebApplicationContext) applicationContext;
webApplicationContext.getServletContext().setSessionTimeout(5);
} else {
LOG.warn("ERROR: Must be inside a web application context !");
}
}
}
|
repos\spring-examples-java-17\spring-security\src\main\java\itx\examples\springboot\security\springsecurity\config\SessionListener.java
| 2
|
请完成以下Java代码
|
public ProcessInstanceQueryDto getProcessInstanceQuery() {
return processInstanceQuery;
}
public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) {
this.processInstanceQuery = processInstanceQuery;
}
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
}
|
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public boolean isSkipSubprocesses() {
return skipSubprocesses;
}
public void setSkipSubprocesses(Boolean skipSubprocesses) {
this.skipSubprocesses = skipSubprocesses;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\batch\DeleteProcessInstancesDto.java
| 1
|
请完成以下Java代码
|
public static Set<String> columnNames()
{
return getColumnName2typesMap().keySet();
}
public static final InvoiceWriteOffAmountType valueOfColumnNameOrNull(final String columnName)
{
final InvoiceWriteOffAmountType type = getColumnName2typesMap().get(columnName);
return type;
}
public static final InvoiceWriteOffAmountType valueOfColumnName(final String columnName)
{
final InvoiceWriteOffAmountType type = getColumnName2typesMap().get(columnName);
if (type == null)
{
throw new IllegalArgumentException("No type for " + columnName);
}
return type;
}
|
private static Map<String, InvoiceWriteOffAmountType> _columnName2types;
private static final Map<String, InvoiceWriteOffAmountType> getColumnName2typesMap()
{
if (_columnName2types == null)
{
// NOTE: we preserve the same order as the values() are.
final ImmutableMap.Builder<String, InvoiceWriteOffAmountType> columnName2types = ImmutableMap.builder();
for (final InvoiceWriteOffAmountType type : values())
{
final String columnName = type.columnName();
columnName2types.put(columnName, type);
}
_columnName2types = columnName2types.build();
}
return _columnName2types;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceWriteOffAmountType.java
| 1
|
请完成以下Java代码
|
public class Person {
private final String name;
private final Integer age;
private Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
@JsonPOJOBuilder
static class Builder {
String name;
Integer age;
|
Builder withName(String name) {
this.name = name;
return this;
}
Builder withAge(Integer age) {
this.age = age;
return this;
}
Person build() {
return new Person(name, age);
}
}
}
|
repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\immutable\Person.java
| 1
|
请完成以下Java代码
|
public void updateQtyPromisedAndSave(final I_C_RfQResponseLine rfqResponseLine)
{
final BigDecimal qtyPromised = Services.get(IRfqDAO.class).calculateQtyPromised(rfqResponseLine);
rfqResponseLine.setQtyPromised(qtyPromised);
InterfaceWrapperHelper.save(rfqResponseLine);
}
// @Override
// public void uncloseInTrx(final I_C_RfQResponse rfqResponse)
// {
// if (!isClosed(rfqResponse))
// {
// throw new RfQDocumentNotClosedException(getSummary(rfqResponse));
// }
//
|
// //
// final IRfQEventDispacher rfQEventDispacher = getRfQEventDispacher();
// rfQEventDispacher.fireBeforeUnClose(rfqResponse);
//
// //
// // Mark as NOT closed
// rfqResponse.setDocStatus(X_C_RfQResponse.DOCSTATUS_Completed);
// InterfaceWrapperHelper.save(rfqResponse);
// updateRfQResponseLinesStatus(rfqResponse);
//
// //
// rfQEventDispacher.fireAfterUnClose(rfqResponse);
//
// // Make sure it's saved
// InterfaceWrapperHelper.save(rfqResponse);
// }
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfqBL.java
| 1
|
请完成以下Java代码
|
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitaets-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitaets-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Field Value.
@param FieldValue Field Value */
public void setFieldValue (String FieldValue)
{
set_Value (COLUMNNAME_FieldValue, FieldValue);
}
/** Get Field Value.
@return Field Value */
public String getFieldValue ()
{
return (String)get_Value(COLUMNNAME_FieldValue);
}
/** Set Value Format.
@param FieldValueFormat Value Format */
public void setFieldValueFormat (String FieldValueFormat)
{
set_Value (COLUMNNAME_FieldValueFormat, FieldValueFormat);
}
/** Get Value Format.
@return Value Format */
public String getFieldValueFormat ()
{
return (String)get_Value(COLUMNNAME_FieldValueFormat);
}
/** Set Null Value.
@param IsNullFieldValue Null Value */
public void setIsNullFieldValue (boolean IsNullFieldValue)
{
set_Value (COLUMNNAME_IsNullFieldValue, Boolean.valueOf(IsNullFieldValue));
}
/** Get Null Value.
@return Null Value */
public boolean isNullFieldValue ()
{
Object oo = get_Value(COLUMNNAME_IsNullFieldValue);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
|
return "Y".equals(oo);
}
return false;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Type AD_Reference_ID=540203 */
public static final int TYPE_AD_Reference_ID=540203;
/** Set Field Value = SV */
public static final String TYPE_SetFieldValue = "SV";
/** Set Art.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
public void setType (String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Type of Validation (SQL, Java Script, Java Language)
*/
public String getType ()
{
return (String)get_Value(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI_Action.java
| 1
|
请完成以下Java代码
|
protected String doIt()
{
if (!isPartialDeliveryAllowed())
{
if (!getView().isApproved())
{
throw new AdempiereException("Not all rows were approved");
}
}
final ImmutableSet<PickingCandidateId> validPickingCandidates = getValidPickingCandidates();
if (!validPickingCandidates.isEmpty())
{
deliverAndInvoice(validPickingCandidates);
}
return MSG_OK;
}
private ImmutableSet<PickingCandidateId> getValidPickingCandidates()
{
return getRowsNotAlreadyProcessed()
.stream()
.filter(ProductsToPickRow::isEligibleForProcessing)
.map(ProductsToPickRow::getPickingCandidateId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
private void deliverAndInvoice(final ImmutableSet<PickingCandidateId> validPickingCandidates)
{
final List<PickingCandidate> pickingCandidates = processAllPickingCandidates(validPickingCandidates);
final Set<HuId> huIdsToDeliver = pickingCandidates
.stream()
.filter(PickingCandidate::isPacked)
.map(PickingCandidate::getPackedToHuId)
.collect(ImmutableSet.toImmutableSet());
|
final List<I_M_HU> husToDeliver = handlingUnitsRepo.getByIds(huIdsToDeliver);
HUShippingFacade.builder()
.hus(husToDeliver)
.addToShipperTransportationId(shipperTransportationId)
.completeShipments(true)
.failIfNoShipmentCandidatesFound(true)
.invoiceMode(BillAssociatedInvoiceCandidates.IF_INVOICE_SCHEDULE_PERMITS)
.createShipperDeliveryOrders(true)
.build()
.generateShippingDocuments();
}
private List<ProductsToPickRow> getRowsNotAlreadyProcessed()
{
return streamAllRows()
.filter(row -> !row.isProcessed())
.collect(ImmutableList.toImmutableList());
}
private boolean isPartialDeliveryAllowed()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_AllowPartialDelivery, false);
}
private ImmutableList<PickingCandidate> processAllPickingCandidates(final ImmutableSet<PickingCandidateId> pickingCandidateIdsToProcess)
{
return trxManager.callInNewTrx(() -> pickingCandidatesService
.process(pickingCandidateIdsToProcess)
.getPickingCandidates());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_4EyesReview_ProcessAll.java
| 1
|
请完成以下Java代码
|
public void setM_Locator_ID (final int M_Locator_ID)
{
if (M_Locator_ID < 1)
set_Value (COLUMNNAME_M_Locator_ID, null);
else
set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID);
}
@Override
public int getM_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Locator_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_Replenish_ID (final int M_Replenish_ID)
{
if (M_Replenish_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Replenish_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Replenish_ID, M_Replenish_ID);
}
@Override
public int getM_Replenish_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Replenish_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
|
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
/**
* ReplenishType AD_Reference_ID=164
* Reference name: M_Replenish Type
*/
public static final int REPLENISHTYPE_AD_Reference_ID=164;
/** Maximalbestand beibehalten = 2 */
public static final String REPLENISHTYPE_MaximalbestandBeibehalten = "2";
/** Manuell = 0 */
public static final String REPLENISHTYPE_Manuell = "0";
/** Bei Unterschreitung Minimalbestand = 1 */
public static final String REPLENISHTYPE_BeiUnterschreitungMinimalbestand = "1";
/** Custom = 9 */
public static final String REPLENISHTYPE_Custom = "9";
/** Zuk?nftigen Bestand sichern = 7 */
public static final String REPLENISHTYPE_ZukNftigenBestandSichern = "7";
@Override
public void setReplenishType (final java.lang.String ReplenishType)
{
set_Value (COLUMNNAME_ReplenishType, ReplenishType);
}
@Override
public java.lang.String getReplenishType()
{
return get_ValueAsString(COLUMNNAME_ReplenishType);
}
@Override
public void setTimeToMarket (final int TimeToMarket)
{
set_Value (COLUMNNAME_TimeToMarket, TimeToMarket);
}
@Override
public int getTimeToMarket()
{
return get_ValueAsInt(COLUMNNAME_TimeToMarket);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Replenish.java
| 1
|
请完成以下Java代码
|
private void createAndHandleMainDataRequestForOldValues(
@NonNull final OldShipmentScheduleData oldShipmentScheduleData,
@NonNull final MainDataRecordIdentifier identifier)
{
final BigDecimal oldReservedQuantity = oldShipmentScheduleData.getOldReservedQuantity();
final BigDecimal oldOrderedQuantity = oldShipmentScheduleData.getOldOrderedQuantity();
if (oldReservedQuantity.signum() == 0 && oldOrderedQuantity.signum() == 0)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("Skipping this event because it has oldReservedQuantity and oldOrderedQuantity = zero");
return;
}
final UpdateMainDataRequest request = UpdateMainDataRequest.builder()
.identifier(identifier)
.qtyDemandSalesOrder(oldReservedQuantity.negate())
.orderedSalesQty(oldOrderedQuantity.negate())
.build();
dataUpdateRequestHandler.handleDataUpdateRequest(request);
if (sysConfigBL.getBooleanValue(SYSCFG_BOM_SUPPORT, true))
{
final ProductBOMRequest bomRequest = ProductBOMRequest.builder()
.productDescriptor(identifier.getProductDescriptor())
.date(identifier.getDate())
.build();
final Optional<ProductBOM> productBOMOptional = productBOMBL.retrieveValidProductBOM(bomRequest);
if (!productBOMOptional.isPresent())
{
return;
}
final ProductBOM productBOM = productBOMOptional.get();
final I_C_UOM uom = productBL.getStockUOM(identifier.getProductDescriptor().getProductId());
final Quantity qty = Quantity.of(oldOrderedQuantity.negate(), uom);
|
final Map<ProductDescriptor, Quantity> components = productBOMBL.calculateRequiredQtyInStockUOMForComponents(qty, productBOM);
for (final Map.Entry<ProductDescriptor, Quantity> component : components.entrySet())
{
final MainDataRecordIdentifier bomIdentifier = MainDataRecordIdentifier.builder()
.productDescriptor(component.getKey())
.date(identifier.getDate())
.build();
final UpdateMainDataRequest requestForBOM = UpdateMainDataRequest.builder()
.identifier(bomIdentifier)
.orderedSalesQty(component.getValue().toBigDecimal())
.build();
dataUpdateRequestHandler.handleDataUpdateRequest(requestForBOM);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\eventhandler\ShipmentScheduleEventHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class TokenBasedAuthService
{
private final Logger logger = Logger.getLogger(TokenBasedAuthService.class.getName());
private final ConcurrentHashMap<String, Authentication> restApiAuthToken = new ConcurrentHashMap<>();
@NonNull
private final List<PreAuthenticatedIdentity> preAuthenticatedIdentities;
public TokenBasedAuthService(@NonNull final List<PreAuthenticatedIdentity> preAuthenticatedIdentities)
{
this.preAuthenticatedIdentities = preAuthenticatedIdentities;
}
public void store(
@NonNull final String token,
@Nullable final List<GrantedAuthority> grantedAuthorities,
@NonNull final TokenCredentials tokenCredentials)
{
final PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(token, tokenCredentials, grantedAuthorities);
restApiAuthToken.put(token, authentication);
}
@NonNull
public Optional<Authentication> retrieve(@Nullable final Object token)
{
if (token == null)
{
return Optional.empty();
}
return Optional.ofNullable(restApiAuthToken.get(String.valueOf(token)));
}
public void expiryToken(@NonNull final Object token)
{
restApiAuthToken.remove(String.valueOf(token));
}
|
public int getNumberOfAuthenticatedTokens(@NonNull final String authority)
{
final SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority);
return (int)restApiAuthToken.values()
.stream()
.map(Authentication::getAuthorities)
.filter(item -> item.contains(grantedAuthority))
.count();
}
@PostConstruct
private void registerPreAuthenticatedIdentities()
{
for (final PreAuthenticatedIdentity preAuthenticatedIdentity : preAuthenticatedIdentities)
{
final Optional<PreAuthenticatedAuthenticationToken> preAuthenticatedAuthenticationToken = preAuthenticatedIdentity.getPreAuthenticatedToken();
if (preAuthenticatedAuthenticationToken.isEmpty())
{
logger.warning(preAuthenticatedIdentity.getClass().getName() + ": not configured!");
continue;
}
restApiAuthToken.put((String)preAuthenticatedAuthenticationToken.get().getPrincipal(), preAuthenticatedAuthenticationToken.get());
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\restapi\auth\TokenBasedAuthService.java
| 2
|
请完成以下Java代码
|
public boolean isExpired() {
return this.cached.isExpired();
}
private void flushIfRequired() {
if (RedisSessionRepository.this.flushMode == FlushMode.IMMEDIATE) {
save();
}
}
private boolean hasChangedSessionId() {
return !getId().equals(this.originalSessionId);
}
private void save() {
saveChangeSessionId();
saveDelta();
if (this.isNew) {
this.isNew = false;
}
}
private void saveChangeSessionId() {
if (hasChangedSessionId()) {
if (!this.isNew) {
String originalSessionIdKey = getSessionKey(this.originalSessionId);
String sessionIdKey = getSessionKey(getId());
RedisSessionRepository.this.sessionRedisOperations.rename(originalSessionIdKey, sessionIdKey);
}
this.originalSessionId = getId();
|
}
}
private void saveDelta() {
if (this.delta.isEmpty()) {
return;
}
String key = getSessionKey(getId());
RedisSessionRepository.this.sessionRedisOperations.opsForHash().putAll(key, new HashMap<>(this.delta));
RedisSessionRepository.this.sessionRedisOperations.expireAt(key,
Instant.ofEpochMilli(getLastAccessedTime().toEpochMilli())
.plusSeconds(getMaxInactiveInterval().getSeconds()));
this.delta.clear();
}
}
}
|
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\RedisSessionRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result update(@RequestBody Article article, @TokenToUser AdminUser loginUser) {
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (articleService.update(article) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("修改失败");
}
}
/**
* 删除
*/
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
|
public Result delete(@RequestBody Integer[] ids, @TokenToUser AdminUser loginUser) {
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (ids.length < 1) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "参数异常!");
}
if (articleService.deleteBatch(ids) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
}
|
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\controller\ArticleController.java
| 2
|
请完成以下Java代码
|
private void transferHandlingUnit(final IHUContext huContext,
final I_M_ReceiptSchedule rs,
final I_M_HU hu,
final I_M_InOutLine receiptLine)
{
//
// Assign it to Receipt Line
assignHU(receiptLine, hu);
//
// Transfer attributes from HU to receipt line's ASI
final IHUContextProcessorExecutor executor = huTrxBL.createHUContextProcessorExecutor(huContext);
executor.run((IHUContextProcessor)huContext1 -> {
final IHUTransactionAttributeBuilder trxAttributesBuilder = executor.getTrxAttributesBuilder();
final IAttributeStorageFactory attributeStorageFactory = trxAttributesBuilder.getAttributeStorageFactory();
final IAttributeStorage huAttributeStorageFrom = attributeStorageFactory.getAttributeStorage(hu);
final IAttributeStorage receiptLineAttributeStorageTo = attributeStorageFactory.getAttributeStorage(receiptLine);
final IHUStorageFactory storageFactory = huContext1.getHUStorageFactory();
final IHUStorage huStorageFrom = storageFactory.getStorage(hu);
final IHUAttributeTransferRequestBuilder requestBuilder = new HUAttributeTransferRequestBuilder(huContext1)
.setProductId(ProductId.ofRepoId(rs.getM_Product_ID()))
.setQty(receiptScheduleBL.getQtyMoved(rs))
.setUOM(loadOutOfTrx(rs.getC_UOM_ID(), I_C_UOM.class))
.setAttributeStorageFrom(huAttributeStorageFrom)
.setAttributeStorageTo(receiptLineAttributeStorageTo)
.setHUStorageFrom(huStorageFrom);
final IHUAttributeTransferRequest request = requestBuilder.create();
trxAttributesBuilder.transferAttributes(request);
|
return IHUContextProcessor.NULL_RESULT;
});
//
// Create HU snapshots
huSnapshotProducer.addModel(hu);
}
private void unassignHU(final I_M_ReceiptSchedule_Alloc rsa)
{
//
// De-activate this allocation because we moved the HU to receipt line
// TODO: provide proper implementation. See http://dewiki908/mediawiki/index.php/06103_Create_proper_HU_transactions_when_creating_Receipt_from_Schedules_%28102206835942%29
rsa.setIsActive(false);
InterfaceWrapperHelper.save(rsa);
}
private void assignHU(final I_M_InOutLine receiptLine, final I_M_HU hu)
{
final String trxName = InterfaceWrapperHelper.getTrxName(receiptLine);
huAssignmentBL.assignHU(receiptLine, hu, trxName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\InOutProducerFromReceiptScheduleHU.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void regionValuesPointcut() { }
@Around("regionPointcut() && regionGetPointcut()")
public Object regionGetAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return PdxInstanceWrapper.from(joinPoint.proceed());
}
@Around("regionPointcut() && regionGetAllPointcut()")
public Object regionGetAllAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return asMap(joinPoint.proceed()).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, mapEntry -> PdxInstanceWrapper.from(mapEntry.getValue())));
}
@Around("regionPointcut() && regionGetEntryPointcut()")
public Object regionGetEntryAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return RegionEntryWrapper.from(joinPoint.proceed());
}
@Around("regionPointcut() && regionSelectValuePointcut()")
public Object regionSelectValueAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return PdxInstanceWrapper.from(joinPoint.proceed());
}
@Around("regionPointcut() && regionValuesPointcut()")
public Object regionValuesAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return asCollection(joinPoint.proceed()).stream()
.map(PdxInstanceWrapper::from)
.collect(Collectors.toList());
}
public static class RegionEntryWrapper<K, V> implements Region.Entry<K, V> {
@SuppressWarnings("unchecked")
public static <T, K, V> T from(T value) {
return value instanceof Region.Entry
? (T) new RegionEntryWrapper<>((Region.Entry<K, V>) value)
: value;
}
private final Region.Entry<K, V> delegate;
protected RegionEntryWrapper(@NonNull Region.Entry<K, V> regionEntry) {
Assert.notNull(regionEntry, "Region.Entry must not be null");
this.delegate = regionEntry;
}
protected @NonNull Region.Entry<K, V> getDelegate() {
return this.delegate;
}
@Override
public boolean isDestroyed() {
return getDelegate().isDestroyed();
}
@Override
public boolean isLocal() {
return getDelegate().isLocal();
}
@Override
public K getKey() {
return getDelegate().getKey();
|
}
@Override
public Region<K, V> getRegion() {
return getDelegate().getRegion();
}
@Override
public CacheStatistics getStatistics() {
return getDelegate().getStatistics();
}
@Override
public Object setUserAttribute(Object userAttribute) {
return getDelegate().setUserAttribute(userAttribute);
}
@Override
public Object getUserAttribute() {
return getDelegate().getUserAttribute();
}
@Override
public V setValue(V value) {
return getDelegate().setValue(value);
}
@Override
@SuppressWarnings("unchecked")
public V getValue() {
return (V) PdxInstanceWrapper.from(getDelegate().getValue());
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\support\PdxInstanceWrapperRegionAspect.java
| 2
|
请完成以下Java代码
|
public class Contracts
{
private static final Logger logger = LoggerFactory.getLogger(Contracts.class);
@Getter
private final BPartner bpartner;
@Getter
private final ImmutableList<Contract> contracts;
public Contracts(
@NonNull final BPartner bpartner,
@NonNull final List<Contract> contracts)
{
this.bpartner = bpartner;
this.contracts = ImmutableList.copyOf(contracts);
}
public List<Product> getProducts()
{
final TreeSet<Product> products = new TreeSet<>(Product.COMPARATOR_Id);
for (final Contract contract : getContracts())
{
products.addAll(contract.getProducts());
}
return new ArrayList<>(products);
}
@Nullable
public ContractLine getContractLineOrNull(final Product product, final LocalDate date)
{
final List<ContractLine> matchingLinesWithRfq = new LinkedList<>();
final List<ContractLine> matchingLinesOthers = new LinkedList<>();
for (final Contract contract : getContracts())
{
if (!contract.matchesDate(date))
{
continue;
}
final ContractLine contractLine = contract.getContractLineForProductOrNull(product);
|
if (contractLine == null)
{
continue;
}
if (contract.isRfq())
{
matchingLinesWithRfq.add(contractLine);
}
else
{
matchingLinesOthers.add(contractLine);
}
}
// Contracts with RfQ (priority)
if (!matchingLinesWithRfq.isEmpty())
{
if (matchingLinesWithRfq.size() > 1)
{
logger.warn("More then one matching contracts (with RfQ) found for {}/{}: {}", product, date, matchingLinesWithRfq);
}
return matchingLinesWithRfq.get(0);
}
// Contracts without RfQ
if (!matchingLinesOthers.isEmpty())
{
if (matchingLinesOthers.size() > 1)
{
logger.warn("More then one matching contracts found for {}/{}: {}", product, date, matchingLinesOthers);
}
return matchingLinesOthers.get(0);
}
// No matching contract line
return null;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Contracts.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DocumentPrintOptionDescriptorsList
{
public static final DocumentPrintOptionDescriptorsList EMPTY = new DocumentPrintOptionDescriptorsList(ImmutableList.of());
ImmutableList<DocumentPrintOptionDescriptor> options;
private DocumentPrintOptionDescriptorsList(@NonNull final List<DocumentPrintOptionDescriptor> options)
{
this.options = ImmutableList.copyOf(options);
}
public static DocumentPrintOptionDescriptorsList of(@NonNull final List<DocumentPrintOptionDescriptor> options)
{
return !options.isEmpty()
? new DocumentPrintOptionDescriptorsList(options)
: EMPTY;
}
|
public DocumentPrintOptions getDefaults()
{
final DocumentPrintOptions.DocumentPrintOptionsBuilder builder = DocumentPrintOptions.builder()
.sourceName("AD_Process defaults");
for (final DocumentPrintOptionDescriptor option : options)
{
if (option.getDefaultValue() == null)
{
continue;
}
builder.option(option.getInternalName(), option.getDefaultValue());
}
return builder.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentPrintOptionDescriptorsList.java
| 2
|
请完成以下Java代码
|
public class FactAcctChangesList
{
public static final FactAcctChangesList EMPTY = new FactAcctChangesList(ImmutableList.of());
private final ImmutableList<FactAcctChanges> allLines;
private final ImmutableListMultimap<AcctSchemaId, FactAcctChanges> linesToAddGroupedByAcctSchemaId;
private final ImmutableMap<FactLineMatchKey, FactAcctChanges> linesToChangeByKey;
private final ImmutableMap<FactLineMatchKey, FactAcctChanges> linesToRemoveByKey;
private FactAcctChangesList(@NonNull final List<FactAcctChanges> list)
{
this.allLines = ImmutableList.copyOf(list);
this.linesToAddGroupedByAcctSchemaId = list.stream()
.filter(changes -> changes.getType().isAdd())
.collect(ImmutableListMultimap.toImmutableListMultimap(FactAcctChanges::getAcctSchemaId, changes -> changes));
this.linesToChangeByKey = list.stream()
.filter(changes -> changes.getType().isChange())
.collect(ImmutableMap.toImmutableMap(FactAcctChanges::getMatchKey, changes -> changes));
this.linesToRemoveByKey = list.stream()
.filter(changes -> changes.getType().isDelete())
.collect(ImmutableMap.toImmutableMap(FactAcctChanges::getMatchKey, changes -> changes));
}
public static FactAcctChangesList ofList(@NonNull final List<FactAcctChanges> list)
{
return !list.isEmpty() ? new FactAcctChangesList(list) : EMPTY;
}
public static Collector<FactAcctChanges, ?, FactAcctChangesList> collect()
{
return GuavaCollectors.collectUsingListAccumulator(FactAcctChangesList::ofList);
}
|
public boolean isEmpty() {return allLines.isEmpty();}
public void forEachRemove(@NonNull final Consumer<FactAcctChanges> consumer)
{
linesToRemoveByKey.values().forEach(consumer);
}
public FactAcctChangesList removingIf(@NonNull final Predicate<FactAcctChanges> predicate)
{
if (allLines.isEmpty())
{
return this;
}
final ArrayList<FactAcctChanges> allLinesAfterRemove = new ArrayList<>(allLines.size());
for (final FactAcctChanges line : allLines)
{
final boolean remove = predicate.test(line);
if (!remove)
{
allLinesAfterRemove.add(line);
}
}
if (allLines.size() == allLinesAfterRemove.size())
{
return this; // no changes
}
return ofList(allLinesAfterRemove);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\factacct_userchanges\FactAcctChangesList.java
| 1
|
请完成以下Java代码
|
private IAllocationDestination createAllocationDestinationAsSourceHUs()
{
final Collection<I_M_HU> sourceHUs = sourceHUsRepository.retrieveActualSourceHUs(ImmutableSet.of(huId));
if (sourceHUs.isEmpty())
{
throw new AdempiereException("No source HUs found for M_HU_ID=" + huId);
}
return HUListAllocationSourceDestination.of(sourceHUs);
}
/**
* Create the context with the tread-inherited transaction! Otherwise, the loader won't be able to access the HU's material item and therefore won't load anything!
*/
private IAllocationRequest createAllocationRequest(
@NonNull final PickingCandidate candidate,
@NonNull final Quantity qtyToRemove)
{
final IMutableHUContext huContext = huContextFactory.createMutableHUContextForProcessing();
return AllocationUtils.builder()
.setHUContext(huContext)
.setProduct(productId)
.setQuantity(qtyToRemove)
.setDateAsToday()
.setFromReferencedTableRecord(pickingCandidateRepository.toTableRecordReference(candidate)) // the m_hu_trx_Line coming out of this will reference the picking candidate
.setForceQtyAllocation(true)
.create();
}
|
private HUListAllocationSourceDestination createAllocationSourceAsHU()
{
final I_M_HU hu = load(huId, I_M_HU.class);
// we made sure that if the target HU is active, so the source HU also needs to be active. Otherwise, goods would just seem to vanish
if (!X_M_HU.HUSTATUS_Active.equals(hu.getHUStatus()))
{
throw new AdempiereException("not an active HU").setParameter("hu", hu);
}
final HUListAllocationSourceDestination source = HUListAllocationSourceDestination.of(hu);
source.setDestroyEmptyHUs(true);
return source;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\RemoveQtyFromHUCommand.java
| 1
|
请完成以下Java代码
|
private Optional<Object> getDefaultValue(final String variableName)
{
// FIXME: hardcoded default to avoid a lot of warnings
if (variableName.endsWith("_ID"))
{
return Optional.of(InterfaceWrapperHelper.getFirstValidIdByColumnName(variableName) - 1);
}
// TODO: find some defaults?
return Optional.empty();
}
/**
* Gets variable's value from global context.
*
* @return value or <code>null</code> if does not apply
*/
private Object getGlobalContext(final String variableName, final Class<?> targetType)
{
if (Integer.class.equals(targetType)
|| int.class.equals(targetType))
{
return Env.getContextAsInt(getCtx(), variableName);
}
else if (java.util.Date.class.equals(targetType)
|| Timestamp.class.equals(targetType))
{
return Env.getContextAsDate(getCtx(), variableName);
}
else if (Boolean.class.equals(targetType))
{
final String valueStr = Env.getContext(getCtx(), variableName);
return DisplayType.toBoolean(valueStr, null);
}
final String valueStr = Env.getContext(getCtx(), variableName);
//
// Use some default value
if (Check.isEmpty(valueStr))
{
// FIXME hardcoded. when we will do a proper login, this won't be necessary
if (variableName.startsWith("$Element_"))
{
return Boolean.FALSE;
}
}
return valueStr;
}
/** Converts field value to {@link Evaluatee2} friendly string */
private static String convertToString(final Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof Boolean)
{
return DisplayType.toBooleanString((Boolean)value);
}
else if (value instanceof String)
{
return value.toString();
}
else if (value instanceof LookupValue)
{
return ((LookupValue)value).getIdAsString();
}
else if (value instanceof java.util.Date)
{
final java.util.Date valueDate = (java.util.Date)value;
return Env.toString(valueDate);
}
else
{
return value.toString();
}
}
private static Integer convertToInteger(final Object valueObj)
{
if (valueObj == null)
{
return null;
}
else if (valueObj instanceof Integer)
{
|
return (Integer)valueObj;
}
else if (valueObj instanceof Number)
{
return ((Number)valueObj).intValue();
}
else if (valueObj instanceof IntegerLookupValue)
{
return ((IntegerLookupValue)valueObj).getIdAsInt();
}
else
{
final String valueStr = valueObj.toString().trim();
if (valueStr.isEmpty())
{
return null;
}
return Integer.parseInt(valueStr);
}
}
private static BigDecimal convertToBigDecimal(final Object valueObj)
{
if (valueObj == null)
{
return null;
}
else if (valueObj instanceof BigDecimal)
{
return (BigDecimal)valueObj;
}
else
{
final String valueStr = valueObj.toString().trim();
if (valueStr.isEmpty())
{
return null;
}
return new BigDecimal(valueStr);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentEvaluatee.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<Object[]> fetchBooksWithAuthorsViaArrayOfObjects() {
List<Object[]> books = bookRepository.findByViaQueryArrayOfObjects();
System.out.println("\nResult set:");
books.forEach(b -> System.out.println(Arrays.toString(b)));
briefOverviewOfPersistentContextContent();
return books;
}
private void briefOverviewOfPersistentContextContent() {
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
int managedEntities = persistenceContext.getNumberOfManagedEntities();
int collectionEntriesSize = persistenceContext.getCollectionEntriesSize();
System.out.println("\n-----------------------------------");
System.out.println("Total number of managed entities: " + managedEntities);
System.out.println("Total number of collection entries: " + collectionEntriesSize + "\n");
// getEntitiesByKey() will be removed and probably replaced with #iterateEntities()
Map<EntityKey, Object> entitiesByKey = persistenceContext.getEntitiesByKey();
entitiesByKey.forEach((key, value) -> System.out.println(key + ":" + value));
|
for (Object entry : entitiesByKey.values()) {
EntityEntry ee = persistenceContext.getEntry(entry);
System.out.println(
"Entity name: " + ee.getEntityName()
+ " | Status: " + ee.getStatus()
+ " | State: " + Arrays.toString(ee.getLoadedState()));
};
System.out.println("\n-----------------------------------\n");
}
private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() {
SharedSessionContractImplementor sharedSession = entityManager.unwrap(
SharedSessionContractImplementor.class
);
return sharedSession.getPersistenceContext();
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootNestedVsVirtualProjection\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "grad_year")
private int gradYear;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
|
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getGradYear() {
return gradYear;
}
public void setGradYear(int gradYear) {
this.gradYear = gradYear;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteriaquery\Student.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected Integer getOrSaveKeyId(String strKey) {
if (strKey.length() > MAX_KEY_LENGTH) {
log.warn("[ts_kv_latest] Value size [{}] exceeds maximum size [{}] of column [key] and will be truncated!",
strKey.length(), MAX_KEY_LENGTH);
log.warn("Affected data:\n{}", strKey);
strKey = strKey.substring(0, MAX_KEY_LENGTH);
}
Integer keyId = tsKvDictionaryMap.get(strKey);
if (keyId == null) {
Optional<KeyDictionaryEntry> tsKvDictionaryOptional;
tsKvDictionaryOptional = keyDictionaryRepository.findById(new KeyDictionaryCompositeKey(strKey));
if (!tsKvDictionaryOptional.isPresent()) {
tsCreationLock.lock();
try {
tsKvDictionaryOptional = keyDictionaryRepository.findById(new KeyDictionaryCompositeKey(strKey));
if (!tsKvDictionaryOptional.isPresent()) {
KeyDictionaryEntry keyDictionaryEntry = new KeyDictionaryEntry();
keyDictionaryEntry.setKey(strKey);
try {
KeyDictionaryEntry saved = keyDictionaryRepository.save(keyDictionaryEntry);
tsKvDictionaryMap.put(saved.getKey(), saved.getKeyId());
keyId = saved.getKeyId();
} catch (ConstraintViolationException e) {
tsKvDictionaryOptional = keyDictionaryRepository.findById(new KeyDictionaryCompositeKey(strKey));
|
KeyDictionaryEntry dictionary = tsKvDictionaryOptional.orElseThrow(() -> new RuntimeException("Failed to get TsKvDictionary entity from DB!"));
tsKvDictionaryMap.put(dictionary.getKey(), dictionary.getKeyId());
keyId = dictionary.getKeyId();
}
} else {
keyId = tsKvDictionaryOptional.get().getKeyId();
}
} finally {
tsCreationLock.unlock();
}
} else {
keyId = tsKvDictionaryOptional.get().getKeyId();
tsKvDictionaryMap.put(strKey, keyId);
}
}
return keyId;
}
private void loadSql(Path sqlFile, Connection conn) throws Exception {
String sql = new String(Files.readAllBytes(sqlFile), Charset.forName("UTF-8"));
conn.createStatement().execute(sql); //NOSONAR, ignoring because method used to execute thingsboard database upgrade script
Thread.sleep(5000);
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\migrate\CassandraTsLatestToSqlMigrateService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Collection<String> getNames() {
return names;
}
// This method is needed because we have a different way of querying list and single objects via MyBatis.
// Querying lists wraps the object in a ListQueryParameterObject
public InternalVariableInstanceQueryImpl getParameter() {
return this;
}
@Override
public boolean isRetained(Collection<VariableInstanceEntity> databaseEntities, Collection<CachedEntity> cachedEntities,
VariableInstanceEntity entity, Object param) {
return isRetained(entity, (InternalVariableInstanceQueryImpl) param);
}
@Override
public boolean isRetained(VariableInstanceEntity entity, Object param) {
return isRetained(entity, (InternalVariableInstanceQueryImpl) param);
}
public boolean isRetained(VariableInstanceEntity entity, InternalVariableInstanceQueryImpl param) {
if (param.executionId != null && !param.executionId.equals(entity.getExecutionId())) {
return false;
}
if (param.scopeId != null && !param.scopeId.equals(entity.getScopeId())) {
return false;
}
if (param.scopeIds != null && !param.scopeIds.contains(entity.getScopeId())) {
return false;
}
if (param.taskId != null && !param.taskId.equals(entity.getTaskId())) {
return false;
}
if (param.processInstanceId != null && !param.processInstanceId.equals(entity.getProcessInstanceId())) {
return false;
}
if (param.withoutTaskId && entity.getTaskId() != null) {
return false;
}
if (param.subScopeId != null && !param.subScopeId.equals(entity.getSubScopeId())) {
|
return false;
}
if (param.subScopeIds != null && !param.subScopeIds.contains(entity.getSubScopeId())) {
return false;
}
if (param.withoutSubScopeId && entity.getSubScopeId() != null) {
return false;
}
if (param.scopeType != null && !param.scopeType.equals(entity.getScopeType())) {
return false;
}
if (param.scopeTypes != null && !param.scopeTypes.isEmpty() && !param.scopeTypes.contains(entity.getScopeType())) {
return false;
}
if (param.id != null && !param.id.equals(entity.getId())) {
return false;
}
if (param.taskIds != null && !param.taskIds.contains(entity.getTaskId())) {
return false;
}
if (param.executionIds != null && !param.executionIds.contains(entity.getExecutionId())) {
return false;
}
if (param.name != null && !param.name.equals(entity.getName())) {
return false;
}
if (param.names != null && !param.names.isEmpty() && !param.names.contains(entity.getName())) {
return false;
}
return true;
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\InternalVariableInstanceQueryImpl.java
| 2
|
请完成以下Java代码
|
public Collection<Class<? extends PPOrderRequestedEvent>> getHandledEventType()
{
return ImmutableList.of(PPOrderRequestedEvent.class);
}
@Override
public void handleEvent(@NonNull final PPOrderRequestedEvent event)
{
createProductionOrder(event);
}
/**
* Creates a production order. Note that it does not fire an event, because production orders can be created and changed for many reasons,<br>
* and therefore we leave the event-firing to a model interceptor.
*/
@VisibleForTesting
I_PP_Order createProductionOrder(@NonNull final PPOrderRequestedEvent ppOrderRequestedEvent)
{
final PPOrder ppOrder = ppOrderRequestedEvent.getPpOrder();
final PPOrderData ppOrderData = ppOrder.getPpOrderData();
final Instant dateOrdered = ppOrderRequestedEvent.getDateOrdered();
final ProductId productId = ProductId.ofRepoId(ppOrderData.getProductDescriptor().getProductId());
final I_C_UOM uom = productBL.getStockUOM(productId);
final Quantity qtyRequired = Quantity.of(ppOrderData.getQtyRequired(), uom);
return ppOrderService.createOrder(PPOrderCreateRequest.builder()
|
.clientAndOrgId(ppOrderData.getClientAndOrgId())
.productPlanningId(ProductPlanningId.ofRepoIdOrNull(ppOrderData.getProductPlanningId()))
.materialDispoGroupId(ppOrderData.getMaterialDispoGroupId())
.plantId(ppOrderData.getPlantId())
.workstationId(ppOrderData.getWorkstationId())
.warehouseId(ppOrderData.getWarehouseId())
//
.productId(productId)
.attributeSetInstanceId(AttributeSetInstanceId.ofRepoIdOrNone(ppOrderData.getProductDescriptor().getAttributeSetInstanceId()))
.qtyRequired(qtyRequired)
//
.dateOrdered(dateOrdered)
.datePromised(ppOrderData.getDatePromised())
.dateStartSchedule(ppOrderData.getDateStartSchedule())
//
.shipmentScheduleId(ShipmentScheduleId.ofRepoIdOrNull(ppOrderData.getShipmentScheduleIdAsRepoId()))
.salesOrderLineId(OrderLineId.ofRepoIdOrNull(ppOrderData.getOrderLineIdAsRepoId()))
//
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\event\PPOrderRequestedEventHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void delResourceList(Long adminId) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":" + adminId;
redisService.del(key);
}
@Override
public void delResourceListByRole(Long roleId) {
UmsAdminRoleRelationExample example = new UmsAdminRoleRelationExample();
example.createCriteria().andRoleIdEqualTo(roleId);
List<UmsAdminRoleRelation> relationList = adminRoleRelationMapper.selectByExample(example);
if (CollUtil.isNotEmpty(relationList)) {
String keyPrefix = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":";
List<String> keys = relationList.stream().map(relation -> keyPrefix + relation.getAdminId()).collect(Collectors.toList());
redisService.del(keys);
}
}
@Override
public void delResourceListByRoleIds(List<Long> roleIds) {
UmsAdminRoleRelationExample example = new UmsAdminRoleRelationExample();
example.createCriteria().andRoleIdIn(roleIds);
List<UmsAdminRoleRelation> relationList = adminRoleRelationMapper.selectByExample(example);
if (CollUtil.isNotEmpty(relationList)) {
String keyPrefix = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":";
List<String> keys = relationList.stream().map(relation -> keyPrefix + relation.getAdminId()).collect(Collectors.toList());
redisService.del(keys);
}
}
@Override
public void delResourceListByResource(Long resourceId) {
List<Long> adminIdList = adminRoleRelationDao.getAdminIdList(resourceId);
if (CollUtil.isNotEmpty(adminIdList)) {
String keyPrefix = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":";
List<String> keys = adminIdList.stream().map(adminId -> keyPrefix + adminId).collect(Collectors.toList());
redisService.del(keys);
}
}
|
@Override
public UmsAdmin getAdmin(String username) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + username;
return (UmsAdmin) redisService.get(key);
}
@Override
public void setAdmin(UmsAdmin admin) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + admin.getUsername();
redisService.set(key, admin, REDIS_EXPIRE);
}
@Override
public List<UmsResource> getResourceList(Long adminId) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":" + adminId;
return (List<UmsResource>) redisService.get(key);
}
@Override
public void setResourceList(Long adminId, List<UmsResource> resourceList) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_RESOURCE_LIST + ":" + adminId;
redisService.set(key, resourceList, REDIS_EXPIRE);
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsAdminCacheServiceImpl.java
| 2
|
请完成以下Java代码
|
private static Map<String, String> errorMessageParameters(Map<String, String> parameters) {
parameters.put("error", BearerTokenErrorCodes.INSUFFICIENT_SCOPE);
parameters.put("error_description",
"The request requires higher privileges than provided by the access token.");
parameters.put("error_uri", "https://tools.ietf.org/html/rfc6750#section-3.1");
return parameters;
}
private static Mono<Void> respond(ServerWebExchange exchange, Map<String, String> parameters) {
String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters);
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
exchange.getResponse().getHeaders().set(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate);
return exchange.getResponse().setComplete();
}
private static String computeWWWAuthenticateHeaderValue(Map<String, String> parameters) {
|
StringBuilder wwwAuthenticate = new StringBuilder();
wwwAuthenticate.append("Bearer");
if (!parameters.isEmpty()) {
wwwAuthenticate.append(" ");
int i = 0;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
wwwAuthenticate.append(entry.getKey()).append("=\"").append(entry.getValue()).append("\"");
if (i != parameters.size() - 1) {
wwwAuthenticate.append(", ");
}
i++;
}
}
return wwwAuthenticate.toString();
}
}
|
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\web\access\server\BearerTokenServerAccessDeniedHandler.java
| 1
|
请完成以下Java代码
|
public String getMessage() {
return message;
}
public void setMessage(String errorMessage) {
this.message = errorMessage;
}
public int getLine() {
return line;
}
public void setLine(int line) {
this.line = line;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
|
}
public String getMainElementId() {
return mainElementId;
}
public void setMainElementId(String mainElementId) {
this.mainElementId = mainElementId;
}
public List<String> getЕlementIds() {
return еlementIds;
}
public void setЕlementIds(List<String> elementIds) {
this.еlementIds = elementIds;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ProblemDto.java
| 1
|
请完成以下Java代码
|
public void updateGroup(GroupDto group) {
ensureNotReadOnly();
Group dbGroup = findGroupObject();
if(dbGroup == null) {
throw new InvalidRequestException(Status.NOT_FOUND, "Group with id " + resourceId + " does not exist");
}
group.update(dbGroup);
identityService.saveGroup(dbGroup);
}
public void deleteGroup() {
ensureNotReadOnly();
identityService.deleteGroup(resourceId);
}
|
public GroupMembersResource getGroupMembersResource() {
return new GroupMembersResourceImpl(getProcessEngine().getName(), resourceId, rootResourcePath, getObjectMapper());
}
protected Group findGroupObject() {
try {
return identityService.createGroupQuery()
.groupId(resourceId)
.singleResult();
} catch(ProcessEngineException e) {
throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, "Exception while performing group query: "+e.getMessage());
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\identity\impl\GroupResourceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class StoreOrdersResponse {
@XmlElement(required = true)
protected StoreOrdersResponseType orderResult;
/**
* Gets the value of the orderResult property.
*
* @return
* possible object is
* {@link StoreOrdersResponseType }
*
*/
public StoreOrdersResponseType getOrderResult() {
return orderResult;
|
}
/**
* Sets the value of the orderResult property.
*
* @param value
* allowed object is
* {@link StoreOrdersResponseType }
*
*/
public void setOrderResult(StoreOrdersResponseType value) {
this.orderResult = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\StoreOrdersResponse.java
| 2
|
请完成以下Java代码
|
public ExecutionEntity resolveRepresentativeExecution() {
return eventScopeExecution;
}
@Override
public void removeChild(MigratingScopeInstance migratingScopeInstance) {
childInstances.remove(migratingScopeInstance);
}
@Override
public void addChild(MigratingScopeInstance migratingScopeInstance) {
if (migratingScopeInstance instanceof MigratingEventScopeInstance) {
childInstances.add((MigratingEventScopeInstance) migratingScopeInstance);
}
else {
throw MIGRATION_LOGGER.cannotHandleChild(this, migratingScopeInstance);
}
}
@Override
public void addChild(MigratingCompensationEventSubscriptionInstance migratingEventSubscription) {
this.childCompensationSubscriptionInstances.add(migratingEventSubscription);
}
@Override
public void removeChild(MigratingCompensationEventSubscriptionInstance migratingEventSubscription) {
this.childCompensationSubscriptionInstances.remove(migratingEventSubscription);
}
@Override
public boolean migrates() {
return targetScope != null;
}
@Override
public void detachChildren() {
Set<MigratingProcessElementInstance> childrenCopy = new HashSet<MigratingProcessElementInstance>(getChildren());
for (MigratingProcessElementInstance child : childrenCopy) {
child.detachState();
|
}
}
@Override
public void remove(boolean skipCustomListeners, boolean skipIoMappings) {
// never invokes listeners and io mappings because this does not remove an active
// activity instance
eventScopeExecution.remove();
migratingEventSubscription.remove();
setParent(null);
}
@Override
public Collection<MigratingProcessElementInstance> getChildren() {
Set<MigratingProcessElementInstance> children = new HashSet<MigratingProcessElementInstance>(childInstances);
children.addAll(childCompensationSubscriptionInstances);
return children;
}
@Override
public Collection<MigratingScopeInstance> getChildScopeInstances() {
return new HashSet<MigratingScopeInstance>(childInstances);
}
@Override
public void removeUnmappedDependentInstances() {
}
public MigratingCompensationEventSubscriptionInstance getEventSubscription() {
return migratingEventSubscription;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingEventScopeInstance.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RelatedDunningsForInvoicesProvider implements RelatedRecordsProvider
{
@Override
public SourceRecordsKey getSourceRecordsKey()
{
return SourceRecordsKey.of(I_C_Invoice.Table_Name);
}
@Override
public IPair<SourceRecordsKey, List<ITableRecordReference>> provideRelatedRecords(
@NonNull final List<ITableRecordReference> records)
{
final ImmutableList<InvoiceId> invoiceIds = records
.stream()
.map(ref -> InvoiceId.ofRepoId(ref.getRecord_ID()))
.collect(ImmutableList.toImmutableList());
final List<Integer> dunningDocIds = Services.get(IQueryBL.class).createQueryBuilder(I_C_Dunning_Candidate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Dunning_Candidate.COLUMN_AD_Table_ID, getTableId(I_C_Invoice.class))
|
.addInArrayFilter(I_C_Dunning_Candidate.COLUMN_Record_ID, invoiceIds)
.andCollectChildren(I_C_DunningDoc_Line_Source.COLUMN_C_Dunning_Candidate_ID)
.addOnlyActiveRecordsFilter()
.andCollect(I_C_DunningDoc_Line_Source.COLUMN_C_DunningDoc_Line_ID)
.addOnlyActiveRecordsFilter()
.andCollect(I_C_DunningDoc_Line.COLUMN_C_DunningDoc_ID)
.addOnlyActiveRecordsFilter()
.create()
.listIds();
final SourceRecordsKey sourceRecordsKey = SourceRecordsKey.of(I_C_DunningDoc.Table_Name);
final ImmutableList<ITableRecordReference> referenceList = dunningDocIds
.stream()
.distinct()
.map(dunningDocId -> TableRecordReference.of(I_C_DunningDoc.Table_Name, dunningDocId))
.collect(ImmutableList.toImmutableList());
return ImmutablePair.of(sourceRecordsKey, referenceList);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\order\restart\RelatedDunningsForInvoicesProvider.java
| 2
|
请完成以下Java代码
|
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
|
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
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_PA_ReportLine.java
| 1
|
请完成以下Java代码
|
public void merge(ConfigurableEnvironment parent) {
for (PropertySource<?> ps : parent.getPropertySources()) {
if (!this.getPropertySources().contains(ps.getName())) {
this.getPropertySources().addLast(ps);
}
}
super.merge(parent);
}
/** {@inheritDoc} */
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
super.customizePropertySources(propertySources);
}
/** {@inheritDoc} */
@Override
public MutablePropertySources getPropertySources() {
return this.encryptablePropertySources;
}
/** {@inheritDoc} */
@Override
public MutablePropertySources getOriginalPropertySources() {
|
return super.getPropertySources();
}
/** {@inheritDoc} */
@Override
public void setEncryptablePropertySources(MutablePropertySources propertySources) {
this.encryptablePropertySources = propertySources;
((MutableConfigurablePropertyResolver)this.getPropertyResolver()).setPropertySources(propertySources);
}
/** {@inheritDoc} */
@Override
protected ConfigurablePropertyResolver createPropertyResolver(MutablePropertySources propertySources) {
return EnvironmentInitializer.createPropertyResolver(propertySources);
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\environment\StandardEncryptableServletEnvironment.java
| 1
|
请完成以下Java代码
|
public String getLabelFormatType ()
{
return (String)get_Value(COLUMNNAME_LabelFormatType);
}
/** 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 Print Text.
@param PrintName
The label text to be printed on a document or correspondence.
*/
public void setPrintName (String PrintName)
{
set_Value (COLUMNNAME_PrintName, PrintName);
}
/** Get Print Text.
@return The label text to be printed on a document or correspondence.
*/
public String getPrintName ()
{
return (String)get_Value(COLUMNNAME_PrintName);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
|
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getSeqNo()));
}
/** Set X Position.
@param XPosition
Absolute X (horizontal) position in 1/72 of an inch
*/
public void setXPosition (int XPosition)
{
set_Value (COLUMNNAME_XPosition, Integer.valueOf(XPosition));
}
/** Get X Position.
@return Absolute X (horizontal) position in 1/72 of an inch
*/
public int getXPosition ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_XPosition);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Y Position.
@param YPosition
Absolute Y (vertical) position in 1/72 of an inch
*/
public void setYPosition (int YPosition)
{
set_Value (COLUMNNAME_YPosition, Integer.valueOf(YPosition));
}
/** Get Y Position.
@return Absolute Y (vertical) position in 1/72 of an inch
*/
public int getYPosition ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_YPosition);
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_AD_PrintLabelLine.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.